@rizom/brain 0.2.0-alpha.495 → 0.2.0-alpha.496
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/brain.js +222 -222
- package/dist/chunks/{app-1p9yf7n6.js → app-ygmc0bkd.js} +2 -2
- package/dist/chunks/{blog-post-adapter-ymh1dn8t.js → blog-post-adapter-aqek4r23.js} +2 -2
- package/dist/chunks/{index-390n8ge8.js → index-1af7q36h.js} +3 -3
- package/dist/chunks/{index-jp81rj6x.js → index-4jdfvr30.js} +2 -2
- package/dist/chunks/{index-y0wh3bnp.js → index-5bq8yawt.js} +3 -3
- package/dist/chunks/{index-y0wh3bnp.js.map → index-5bq8yawt.js.map} +3 -3
- package/dist/chunks/{index-sq9ptpvr.js → index-6crtt8mr.js} +2 -2
- package/dist/chunks/{index-a5na8p4p.js → index-r6a0hpn8.js} +3 -3
- package/dist/chunks/{index-a5na8p4p.js.map → index-r6a0hpn8.js.map} +1 -1
- package/dist/chunks/{index-c36br3r2.js → index-wqq0pdyw.js} +2 -2
- package/dist/chunks/linkedin-template-6m1rc1a6.js +5 -0
- package/dist/chunks/{rss-datasource-j65pv9gj.js → rss-datasource-75h1bpzq.js} +2 -2
- package/dist/entities.js +1 -1
- package/dist/index.js +1 -1
- package/dist/interfaces.js +1 -1
- package/dist/model.js +42 -42
- package/dist/model.js.map +1 -1
- package/dist/plugins.js +1 -1
- package/dist/services.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/linkedin-template-2dcckpkt.js +0 -5
- /package/dist/chunks/{app-1p9yf7n6.js.map → app-ygmc0bkd.js.map} +0 -0
- /package/dist/chunks/{blog-post-adapter-ymh1dn8t.js.map → blog-post-adapter-aqek4r23.js.map} +0 -0
- /package/dist/chunks/{index-390n8ge8.js.map → index-1af7q36h.js.map} +0 -0
- /package/dist/chunks/{index-jp81rj6x.js.map → index-4jdfvr30.js.map} +0 -0
- /package/dist/chunks/{index-sq9ptpvr.js.map → index-6crtt8mr.js.map} +0 -0
- /package/dist/chunks/{index-c36br3r2.js.map → index-wqq0pdyw.js.map} +0 -0
- /package/dist/chunks/{linkedin-template-2dcckpkt.js.map → linkedin-template-6m1rc1a6.js.map} +0 -0
- /package/dist/chunks/{rss-datasource-j65pv9gj.js.map → rss-datasource-75h1bpzq.js.map} +0 -0
|
@@ -38,7 +38,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=n,Error.captureStackTrac
|
|
|
38
38
|
hash text NOT NULL,
|
|
39
39
|
created_at numeric
|
|
40
40
|
)
|
|
41
|
-
`;await t.run(i);let s=(await t.values(b`SELECT id, hash, created_at FROM ${b.identifier(r)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(c)=>{for(let l of e)if(!s||Number(s[2])<l.folderMillis){for(let u of l.sql)await c.run(b.raw(u));await c.run(b`INSERT INTO ${b.identifier(r)} ("hash", "created_at") VALUES(${l.hash}, ${l.folderMillis})`)}})}}class Sx{static[D]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Yr{static[D]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,n;if(this.fields)n=this.fields;else if(W(e,It))n=Object.fromEntries(Object.keys(e._.selectedFields).map((r)=>[r,e[r]]));else if(W(e,ra))n=e[Rt].selectedFields;else if(W(e,fe))n={};else n=jc(e);return new xx({table:e,fields:n,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class Rz extends Sx{static[D]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=$u(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let c of Kr(e))this.usedTables.add(c)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,n)=>{let r=this.tableName,i=$u(t);for(let o of Kr(t))this.usedTables.add(o);if(typeof i==="string"&&this.config.joins?.some((o)=>o.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof r==="string")this.config.fields={[r]:this.config.fields};if(typeof i==="string"&&!W(t,fe)){let o=W(t,It)?t._.selectedFields:W(t,Er)?t[Rt].selectedFields:t[ae.Symbol.Columns];this.config.fields[i]=o}}if(typeof n==="function")n=n(new Proxy(this.config.fields,new Lt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:n,table:t,joinType:e,alias:i}),typeof i==="string")switch(e){case"left":{this.joinsNotNullableMap[i]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[i]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[i]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[i]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(n)=>{let r=typeof n==="function"?n(u3()):n;if(!Zu(this.getSelectedFields(),r.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new Lt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new Lt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new Lt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new Lt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=n;else this.config.orderBy=n}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...Kr(this.config.table)),this.config.joins)for(let n of this.config.joins)t.push(...Kr(n.table));return new Proxy(new It(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new Lt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Lt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class xx extends Rz{static[D]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=Ir(this.config.fields),n=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return n.joinsNotNullableMap=this.joinsNotNullableMap,n}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.all()}}TD(xx,[An]);function cf(e,t){return(n,r,...i)=>{let o=[r,...i].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!Zu(n.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return n.addSetOperators(o)}}var u3=()=>({union:p3,unionAll:d3,intersect:m3,except:f3}),p3=cf("union",!1),d3=cf("union",!0),m3=cf("intersect",!1),f3=cf("except",!1);class Wu{static[D]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=W(e,Nc)?e:void 0,this.dialectConfig=W(e,Nc)?void 0:e}$with=(e,t)=>{let n=this;return{as:(i)=>{if(typeof i==="function")i=i(n);return new Proxy(new Nu(i.getSQL(),t??("getSelectedFields"in i?i.getSelectedFields()??{}:{}),e,!0),new Lt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function n(i){return new Yr({fields:i??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(i){return new Yr({fields:i??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:n,selectDistinct:r}}select(e){return new Yr({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Yr({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new yx(this.dialectConfig);return this.dialect}}class lf{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[D]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((n)=>{let r={},i=this.table[ae.Symbol.Columns];for(let o of Object.keys(n)){let s=n[o];r[o]=W(s,fe)?s:new rr(s,i[o])}return r});return new vx(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Wu):e;if(!W(t,fe)&&!Zu(this.table[Qm],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new vx(this.table,t,this.session,this.dialect,this.withList,!0)}}class vx extends An{constructor(e,t,n,r,i,o){super();this.session=n,this.dialect=r,this.config={table:e,values:t,withList:i,select:o}}static[D]="SQLiteInsert";config;returning(e=this.config.table[qt.Symbol.Columns]){return this.config.returning=Ir(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(b` on conflict do nothing`);else{let t=Array.isArray(e.target)?b`${e.target}`:b`${[e.target]}`,n=e.where?b` where ${e.where}`:b``;this.config.onConflict.push(b` on conflict ${t} do nothing${n}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?b` where ${e.where}`:void 0,n=e.targetWhere?b` where ${e.targetWhere}`:void 0,r=e.setWhere?b` where ${e.setWhere}`:void 0,i=Array.isArray(e.target)?b`${e.target}`:b`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,Ym(this.config.table,e.set));return this.config.onConflict.push(b` on conflict ${i}${n} do update set ${o}${t}${r}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Kr(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class uf{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[D]="SQLiteUpdateBuilder";set(e){return new kz(this.table,Ym(this.table,e),this.session,this.dialect,this.withList)}}class kz extends An{constructor(e,t,n,r,i){super();this.session=n,this.dialect=r,this.config={set:t,table:e,withList:i,joins:[]}}static[D]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,n)=>{let r=$u(t);if(typeof r==="string"&&this.config.joins.some((i)=>i.alias===r))throw Error(`Alias "${r}" is already used in this query`);if(typeof n==="function"){let i=this.config.from?W(t,qt)?t[ae.Symbol.Columns]:W(t,It)?t._.selectedFields:W(t,ra)?t[Rt].selectedFields:void 0:void 0;n=n(new Proxy(this.config.table[ae.Symbol.Columns],new Lt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),i&&new Proxy(i,new Lt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:n,table:t,joinType:e,alias:r}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[ae.Symbol.Columns],new Lt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(t)?t:[t];this.config.orderBy=n}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[qt.Symbol.Columns]){return this.config.returning=Ir(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Kr(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class Ju extends fe{constructor(e){super(Ju.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Ju.buildCount(e.source,e.filters)}sql;static[D]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return b`(select count(*) from ${e}${b.raw(" where ").if(t)}${t})`}static buildCount(e,t){return b`select count(*) from ${e}${b.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}class Tx{constructor(e,t,n,r,i,o,s,c){this.mode=e,this.fullSchema=t,this.schema=n,this.tableNamesMap=r,this.table=i,this.tableConfig=o,this.dialect=s,this.session=c}static[D]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new wx(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new pf(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new wx(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new pf(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}}class pf extends An{constructor(e,t,n,r,i,o,s,c,l){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=o,this.session=s,this.config=c,this.mode=l}static[D]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:n}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](n,void 0,this.mode==="first"?"get":"all",!0,(r,i)=>{let o=r.map((s)=>tf(this.schema,this.tableConfig,s,t.selection,i));if(this.mode==="first")return o[0];return o})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}}class wx extends pf{static[D]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}class Bc extends An{constructor(e,t,n,r,i){super();this.execute=e,this.getSQL=t,this.dialect=r,this.mapBatchResult=i,this.config={action:n}}static[D]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}class Hu{constructor(e,t,n,r){this.resultKind=e,this.dialect=t,this.session=n,this._=r?{schema:r.schema,fullSchema:r.fullSchema,tableNamesMap:r.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let i=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))i[o]=new Tx(e,r.fullSchema,this._.schema,this._.tableNamesMap,r.fullSchema[o],s,t,n);this.$cache={invalidate:async(o)=>{}}}static[D]="BaseSQLiteDatabase";query;$with=(e,t)=>{let n=this;return{as:(i)=>{if(typeof i==="function")i=i(new Wu(n.dialect));return new Proxy(new Nu(i.getSQL(),t??("getSelectedFields"in i?i.getSelectedFields()??{}:{}),e,!0),new Lt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Ju({source:e,filters:t,session:this.session})}with(...e){let t=this;function n(c){return new Yr({fields:c??void 0,session:t.session,dialect:t.dialect,withList:e})}function r(c){return new Yr({fields:c??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function i(c){return new uf(c,t.session,t.dialect,e)}function o(c){return new lf(c,t.session,t.dialect,e)}function s(c){return new af(c,t.session,t.dialect,e)}return{select:n,selectDistinct:r,update:i,insert:o,delete:s}}select(e){return new Yr({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Yr({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new uf(e,this.session,this.dialect)}$cache;insert(e){return new lf(e,this.session,this.dialect)}delete(e){return new af(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?b.raw(e):e.getSQL();if(this.resultKind==="async")return new Bc(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?b.raw(e):e.getSQL();if(this.resultKind==="async")return new Bc(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?b.raw(e):e.getSQL();if(this.resultKind==="async")return new Bc(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?b.raw(e):e.getSQL();if(this.resultKind==="async")return new Bc(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}class Pz{static[D]="Cache"}class Gu extends Pz{strategy(){return"all"}static[D]="NoopCache";async get(e){return}async put(e,t,n,r){}async onMutate(e){}}async function Cx(e,t){let n=`${e}-${JSON.stringify(t)}`,i=new TextEncoder().encode(n),o=await crypto.subtle.digest("SHA-256",i);return[...new Uint8Array(o)].map((l)=>l.toString(16).padStart(2,"0")).join("")}class Az extends An{constructor(e){super();this.resultCb=e}static[D]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}}class Ex{constructor(e,t,n,r,i,o){if(this.mode=e,this.executeMethod=t,this.query=n,this.cache=r,this.queryMetadata=i,this.cacheConfig=o,r&&r.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[D]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,n){if(this.cache===void 0||W(this.cache,Gu)||this.queryMetadata===void 0)try{return await n()}catch(r){throw new Yi(e,t,r)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await n()}catch(r){throw new Yi(e,t,r)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[r]=await Promise.all([n(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return r}catch(r){throw new Yi(e,t,r)}if(!this.cacheConfig)try{return await n()}catch(r){throw new Yi(e,t,r)}if(this.queryMetadata.type==="select"){let r=await this.cache.get(this.cacheConfig.tag??await Cx(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(r===void 0){let i;try{i=await n()}catch(o){throw new Yi(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await Cx(e,t),i,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),i}return r}try{return await n()}catch(r){throw new Yi(e,t,r)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new Az(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}}class Ix{constructor(e){this.dialect=e}static[D]="SQLiteSession";prepareOneTimeQuery(e,t,n,r,i,o,s){return this.prepareQuery(e,t,n,r,i,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(n){throw new Mc({cause:n,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}}class Rx extends Hu{constructor(e,t,n,r,i=0){super(e,t,n,r);this.schema=r,this.nestedIndex=i}static[D]="SQLiteTransaction";rollback(){throw new nx}}var O=ot("entities",{id:V("id").notNull(),entityType:V("entityType").notNull(),content:V("content").notNull(),contentHash:V("contentHash").notNull(),visibility:V("visibility",{enum:["public","shared","restricted"]}).notNull().default("public"),metadata:V("metadata",{mode:"json"}).$type().notNull().default(b`'{}'`),created:xe("created").notNull().$defaultFn(()=>Date.now()),updated:xe("updated").notNull().$defaultFn(()=>Date.now())},(e)=>({pk:Dn({columns:[e.id,e.entityType]}),visibilityCheck:Uo("entities_visibility_check",b`${e.visibility} IN ('public', 'shared', 'restricted')`)}));function Rr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function kx(e){if(Array.isArray(e))return e.map((t)=>t===void 0?null:kx(t));if(Rr(e))return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,kx(n)]));return e}function ia(e){return JSON.stringify(kx(e))}function ir({contentHash:e,metadata:t,visibility:n}){return Ei(ia({contentHash:e,metadata:t,visibility:n}))}var Oz=200,g3=4,_c=new TextDecoder("utf-8",{ignoreBOM:!0}),df={id:b`CAST(${O.id} AS BLOB)`,entityType:b`CAST(${O.entityType} AS BLOB)`,content:b`CAST(${O.content} AS BLOB)`,contentHash:O.contentHash,metadata:O.metadata,visibility:O.visibility};async function Dz(e,t,n,r){r?.throwIfAborted();let i=n&&new Set(n.map((s)=>JSON.stringify([s.entityType,s.field]))),o=new Map;for(let s of t.getGroupings())for(let c of s.types){if(i&&!i.has(JSON.stringify([c,s.field])))continue;let l=o.get(c)??new Set;l.add(s.field),o.set(c,l)}if(o.size===0)return;await zz(e,t,o,void 0,r)}async function zz(e,t,n,r,i){i?.throwIfAborted();let o=await e.select(df).from(O).where(H(Ke(O.entityType,[...n.keys()]),h3(r))).orderBy(Ue(O.entityType),Ue(O.id)).limit(Oz);await y3(e,t,o,n,i);let s=o.at(-1);if(!s||o.length<Oz)return;return zz(e,t,n,{type:_c.decode(s.entityType),id:_c.decode(s.id)},i)}function h3(e){if(!e)return;return cn(Xi(O.entityType,e.type),H(A(O.entityType,e.type),Xi(O.id,e.id)))}async function y3(e,t,n,r,i){i?.throwIfAborted();let o=n.flatMap((c)=>{let l=_c.decode(c.entityType),u=_c.decode(c.id),p=jz(t,{type:l,id:u,destination:H(A(O.entityType,l),A(O.id,u)),fields:r.get(l)??new Set},c);return p?[p]:[]});if(o.length===0)return;let s=await e.transaction(async(c)=>{let l=[];for(let u of o)if(i?.throwIfAborted(),await Nz(c,t,u)==="conflict")l.push(u.target);return l});for(let c of s){let l=(await e.select(df).from(O).where(c.destination).limit(1))[0];await Mz(e,t,c,l,g3-1,i)}}async function Mz(e,t,n,r,i,o){if(o?.throwIfAborted(),!r)return;if(i===0)throw Error("Grouping reprojection exceeded concurrent-write retry limit");let s=jz(t,n,r);if(!s)return;if(await e.transaction((u)=>(o?.throwIfAborted(),Nz(u,t,s)))!=="conflict")return;let l=(await e.select(df).from(O).where(n.destination).limit(1))[0];return Mz(e,t,n,l,i-1,o)}function jz(e,t,n){let r=new Set(e.groupingFields(t.type)),i=new Set([...t.fields].filter((l)=>r.has(l)));if(i.size===0)return;t={...t,fields:i};let o=_c.decode(n.content),s=e.projectStoredMetadata(t.type,o,n.metadata),c={...n.metadata};for(let l of t.fields)if(delete c[l],Object.hasOwn(s,l))c[l]=s[l];if(ia(c)===ia(n.metadata))return;return{target:t,row:n,content:o,metadata:c}}async function Nz(e,t,n){let{target:r,row:i,content:o,metadata:s}=n,c=(await e.select(df).from(O).where(r.destination).limit(1))[0];if(!c)return"deleted";let l=new Set(t.groupingFields(r.type));if([...r.fields].some((u)=>!l.has(u)))return"conflict";if(ir(c)!==ir(i)||_c.decode(c.content)!==o)return"conflict";return await e.update(O).set({metadata:s}).where(r.destination),"updated"}class Px{dependencies;running;initialized=!1;fullRequested=!1;constructor(e){this.dependencies=e}isReady(){return this.initialized&&!this.running&&!this.hasWork()}invalidate(){this.initialized=!1}run(e=!1){if(this.running)return this.fullRequested||=e,this.running;if(this.fullRequested||=e||!this.initialized,this.isReady())return Promise.resolve();return this.running=this.drain().catch((t)=>{throw this.invalidate(),t}).finally(()=>{this.running=void 0}),this.running}hasWork(){return this.fullRequested||this.dependencies.pending().length>0}async drain(){for(let e=0;e<4;e++){await this.dependencies.refresh();let t=this.dependencies.pending(),n=this.fullRequested;this.fullRequested=!1;try{if(n||t.length>0)await this.dependencies.project(n?void 0:t)}catch(r){throw this.fullRequested||=n,r}if(this.dependencies.complete(t),await this.dependencies.refresh(),!this.hasWork()){this.initialized=!0;return}}throw Error("Grouping definitions changed repeatedly during reprojection; retry when changes settle")}}import{createClient as b3,LibsqlError as Lz}from"@libsql/client";import{createClient as Ox}from"@libsql/client";class ff extends Ix{constructor(e,t,n,r,i){super(t);this.client=e,this.schema=n,this.options=r,this.tx=i,this.logger=r.logger??new ix,this.cache=r.cache??new Gu}static[D]="LibSQLSession";logger;cache;prepareQuery(e,t,n,r,i,o,s){return new _z(this.client,e,this.logger,this.cache,o,s,t,this.tx,n,r,i)}async batch(e){let t=[],n=[];for(let i of e){let o=i._prepare(),s=o.getQuery();t.push(o),n.push({sql:s.sql,args:s.params})}return(await this.client.batch(n)).map((i,o)=>t[o].mapResult(i,!0))}async migrate(e){let t=[],n=[];for(let i of e){let o=i._prepare(),s=o.getQuery();t.push(o),n.push({sql:s.sql,args:s.params})}return(await this.client.migrate(n)).map((i,o)=>t[o].mapResult(i,!0))}async transaction(e,t){let n=await this.client.transaction(),r=new ff(this.client,this.dialect,this.schema,this.options,n),i=new Ax("async",this.dialect,r,this.schema);try{let o=await e(i);return await n.commit(),o}catch(o){throw await n.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}}class Ax extends Rx{static[D]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,n=new Ax("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(b.raw(`savepoint ${t}`));try{let r=await e(n);return await this.session.run(b.raw(`release savepoint ${t}`)),r}catch(r){throw await this.session.run(b.raw(`rollback to savepoint ${t}`)),r}}}class _z extends Ex{constructor(e,t,n,r,i,o,s,c,l,u,p){super("async",l,t,r,i,o);this.client=e,this.logger=n,this.fields=s,this.tx=c,this._isResponseInArrayMode=u,this.customResultMapper=p,this.customResultMapper=p,this.fields=s}static[D]="LibSQLPreparedQuery";async run(e){let t=_u(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let n={sql:this.query.sql,args:t};return this.tx?this.tx.execute(n):this.client.execute(n)})}async all(e){let{fields:t,logger:n,query:r,tx:i,client:o,customResultMapper:s}=this;if(!t&&!s){let l=_u(r.params,e??{});return n.logQuery(r.sql,l),await this.queryWithCache(r.sql,l,async()=>{let u={sql:r.sql,args:l};return(i?i.execute(u):o.execute(u)).then(({rows:p})=>this.mapAllResult(p))})}let c=await this.values(e);return this.mapAllResult(c)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((n)=>Bz(n));if(this.customResultMapper)return this.customResultMapper(e,mf);return e.map((n)=>ox(this.fields,Array.prototype.slice.call(n).map((r)=>mf(r)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:n,query:r,tx:i,client:o,customResultMapper:s}=this;if(!t&&!s){let l=_u(r.params,e??{});return n.logQuery(r.sql,l),await this.queryWithCache(r.sql,l,async()=>{let u={sql:r.sql,args:l};return(i?i.execute(u):o.execute(u)).then(({rows:p})=>this.mapGetResult(p))})}let c=await this.values(e);return this.mapGetResult(c)}mapGetResult(e,t){if(t)e=e.rows;let n=e[0];if(!this.fields&&!this.customResultMapper)return Bz(n);if(!n)return;if(this.customResultMapper)return this.customResultMapper(e,mf);return ox(this.fields,Array.prototype.slice.call(n).map((r)=>mf(r)),this.joinsNotNullableMap)}async values(e){let t=_u(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let n={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(n):this.client.execute(n)).then(({rows:r})=>r)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}function Bz(e){return Object.keys(e).reduce((t,n)=>{if(Object.prototype.propertyIsEnumerable.call(e,n))t[n]=e[n];return t},{})}function mf(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}class Fz extends Hu{static[D]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}function Fc(e,t={}){let n=new bx({casing:t.casing}),r;if(t.logger===!0)r=new rx;else if(t.logger!==!1)r=t.logger;let i;if(t.schema){let c=LD(t.schema,ZD);i={fullSchema:t.schema,schema:c.tables,tableNamesMap:c.tableNamesMap}}let o=new ff(e,n,i,{logger:r,cache:t.cache},void 0),s=new Fz("async",n,o,i);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}function gf(...e){if(typeof e[0]==="string"){let t=Ox({url:e[0]});return Fc(t,e[1])}if(CD(e[0])){let{connection:t,client:n,...r}=e[0];if(n)return Fc(n,r);let i=typeof t==="string"?Ox({url:t}):Ox(t);return Fc(i,r)}return Fc(e[0],e[1])}((e)=>{function t(n){return Fc({},n)}e.mock=t})(gf||(gf={}));function qz(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}var S3=5000,x3=5,v3=40;function w3(e){return e instanceof Lz&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Vu(e,t){let n=Date.now()+(t.budgetMs??S3),r=async(i)=>{if(t.isClosed())throw new Lz("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!w3(o))throw o;await t.afterRefusal?.();let s=Math.min(x3*2**(i-1),v3),c=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+c>=n)throw o;if(await new Promise((l)=>setTimeout(l,c)),t.isClosed()||Date.now()>=n)throw o;return r(i+1)}};return r(1)}function Dx(e,t={}){let n=b3({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let p=function(m,g){return Vu(()=>typeof m==="string"?s(m,g):s(m),{isClosed:i,budgetMs:o})},r=n.transaction.bind(n),i=()=>n.closed,o=t.contentionRetryBudgetMs,s=n.execute.bind(n),c=n.batch.bind(n),l=n.migrate.bind(n),u={isClosed:i,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(n.reconnect())}};n.execute=p,n.batch=(m,g)=>Vu(()=>c(m,g),u),n.migrate=(m)=>Vu(()=>l(m),u),n.transaction=(m)=>Vu(()=>r(m),u)}return n}function Xr(e){let{url:t,schema:n}=e,r=qz(e),i={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=r?Dx({url:t,authToken:r},i):Dx({url:t},i);return{db:gf(o,{schema:n}),client:o,url:t}}async function ei(e,t){if(!t.startsWith("file:"))return;let n=()=>e.closed===!0;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await Vu(()=>e.execute(r),{isClosed:n})}import T3 from"crypto";import zx from"fs";function Zz(e){let t=e.migrationsFolder,n=[],r=`${t}/meta/_journal.json`;if(!zx.existsSync(r))throw Error("Can't find meta/_journal.json file");let i=zx.readFileSync(`${t}/meta/_journal.json`).toString(),o=JSON.parse(i);for(let s of o.entries){let c=`${t}/${s.tag}.sql`;try{let l=zx.readFileSync(`${t}/${s.tag}.sql`).toString(),u=l.split("--> statement-breakpoint").map((p)=>p);n.push({sql:u,bps:s.breakpoints,folderMillis:s.when,hash:T3.createHash("sha256").update(l).digest("hex")})}catch{throw Error(`No file ${c} found in ${t} folder`)}}return n}async function $z(e,t){let n=Zz(t),r=t.migrationsTable??"__drizzle_migrations",i=b`
|
|
41
|
+
`;await t.run(i);let s=(await t.values(b`SELECT id, hash, created_at FROM ${b.identifier(r)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(c)=>{for(let l of e)if(!s||Number(s[2])<l.folderMillis){for(let u of l.sql)await c.run(b.raw(u));await c.run(b`INSERT INTO ${b.identifier(r)} ("hash", "created_at") VALUES(${l.hash}, ${l.folderMillis})`)}})}}class Sx{static[D]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class Yr{static[D]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,n;if(this.fields)n=this.fields;else if(W(e,It))n=Object.fromEntries(Object.keys(e._.selectedFields).map((r)=>[r,e[r]]));else if(W(e,ra))n=e[Rt].selectedFields;else if(W(e,fe))n={};else n=jc(e);return new xx({table:e,fields:n,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class Rz extends Sx{static[D]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=$u(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let c of Kr(e))this.usedTables.add(c)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,n)=>{let r=this.tableName,i=$u(t);for(let o of Kr(t))this.usedTables.add(o);if(typeof i==="string"&&this.config.joins?.some((o)=>o.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof r==="string")this.config.fields={[r]:this.config.fields};if(typeof i==="string"&&!W(t,fe)){let o=W(t,It)?t._.selectedFields:W(t,Er)?t[Rt].selectedFields:t[ae.Symbol.Columns];this.config.fields[i]=o}}if(typeof n==="function")n=n(new Proxy(this.config.fields,new Lt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:n,table:t,joinType:e,alias:i}),typeof i==="string")switch(e){case"left":{this.joinsNotNullableMap[i]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[i]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[i]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[i]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(n)=>{let r=typeof n==="function"?n(u3()):n;if(!Zu(this.getSelectedFields(),r.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new Lt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new Lt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new Lt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new Lt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=n;else this.config.orderBy=n}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...Kr(this.config.table)),this.config.joins)for(let n of this.config.joins)t.push(...Kr(n.table));return new Proxy(new It(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new Lt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Lt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class xx extends Rz{static[D]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=Ir(this.config.fields),n=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return n.joinsNotNullableMap=this.joinsNotNullableMap,n}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.all()}}TD(xx,[An]);function cf(e,t){return(n,r,...i)=>{let o=[r,...i].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!Zu(n.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return n.addSetOperators(o)}}var u3=()=>({union:p3,unionAll:d3,intersect:m3,except:f3}),p3=cf("union",!1),d3=cf("union",!0),m3=cf("intersect",!1),f3=cf("except",!1);class Wu{static[D]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=W(e,Nc)?e:void 0,this.dialectConfig=W(e,Nc)?void 0:e}$with=(e,t)=>{let n=this;return{as:(i)=>{if(typeof i==="function")i=i(n);return new Proxy(new Nu(i.getSQL(),t??("getSelectedFields"in i?i.getSelectedFields()??{}:{}),e,!0),new Lt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function n(i){return new Yr({fields:i??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(i){return new Yr({fields:i??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:n,selectDistinct:r}}select(e){return new Yr({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Yr({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new yx(this.dialectConfig);return this.dialect}}class lf{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[D]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((n)=>{let r={},i=this.table[ae.Symbol.Columns];for(let o of Object.keys(n)){let s=n[o];r[o]=W(s,fe)?s:new rr(s,i[o])}return r});return new vx(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Wu):e;if(!W(t,fe)&&!Zu(this.table[Qm],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new vx(this.table,t,this.session,this.dialect,this.withList,!0)}}class vx extends An{constructor(e,t,n,r,i,o){super();this.session=n,this.dialect=r,this.config={table:e,values:t,withList:i,select:o}}static[D]="SQLiteInsert";config;returning(e=this.config.table[qt.Symbol.Columns]){return this.config.returning=Ir(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(b` on conflict do nothing`);else{let t=Array.isArray(e.target)?b`${e.target}`:b`${[e.target]}`,n=e.where?b` where ${e.where}`:b``;this.config.onConflict.push(b` on conflict ${t} do nothing${n}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?b` where ${e.where}`:void 0,n=e.targetWhere?b` where ${e.targetWhere}`:void 0,r=e.setWhere?b` where ${e.setWhere}`:void 0,i=Array.isArray(e.target)?b`${e.target}`:b`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,Ym(this.config.table,e.set));return this.config.onConflict.push(b` on conflict ${i}${n} do update set ${o}${t}${r}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Kr(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class uf{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[D]="SQLiteUpdateBuilder";set(e){return new kz(this.table,Ym(this.table,e),this.session,this.dialect,this.withList)}}class kz extends An{constructor(e,t,n,r,i){super();this.session=n,this.dialect=r,this.config={set:t,table:e,withList:i,joins:[]}}static[D]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,n)=>{let r=$u(t);if(typeof r==="string"&&this.config.joins.some((i)=>i.alias===r))throw Error(`Alias "${r}" is already used in this query`);if(typeof n==="function"){let i=this.config.from?W(t,qt)?t[ae.Symbol.Columns]:W(t,It)?t._.selectedFields:W(t,ra)?t[Rt].selectedFields:void 0:void 0;n=n(new Proxy(this.config.table[ae.Symbol.Columns],new Lt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),i&&new Proxy(i,new Lt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:n,table:t,joinType:e,alias:r}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[ae.Symbol.Columns],new Lt({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(t)?t:[t];this.config.orderBy=n}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[qt.Symbol.Columns]){return this.config.returning=Ir(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:Kr(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class Ju extends fe{constructor(e){super(Ju.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Ju.buildCount(e.source,e.filters)}sql;static[D]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return b`(select count(*) from ${e}${b.raw(" where ").if(t)}${t})`}static buildCount(e,t){return b`select count(*) from ${e}${b.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}class Tx{constructor(e,t,n,r,i,o,s,c){this.mode=e,this.fullSchema=t,this.schema=n,this.tableNamesMap=r,this.table=i,this.tableConfig=o,this.dialect=s,this.session=c}static[D]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new wx(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new pf(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new wx(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new pf(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}}class pf extends An{constructor(e,t,n,r,i,o,s,c,l){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=o,this.session=s,this.config=c,this.mode=l}static[D]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:n}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](n,void 0,this.mode==="first"?"get":"all",!0,(r,i)=>{let o=r.map((s)=>tf(this.schema,this.tableConfig,s,t.selection,i));if(this.mode==="first")return o[0];return o})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}}class wx extends pf{static[D]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}class Bc extends An{constructor(e,t,n,r,i){super();this.execute=e,this.getSQL=t,this.dialect=r,this.mapBatchResult=i,this.config={action:n}}static[D]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}class Hu{constructor(e,t,n,r){this.resultKind=e,this.dialect=t,this.session=n,this._=r?{schema:r.schema,fullSchema:r.fullSchema,tableNamesMap:r.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let i=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))i[o]=new Tx(e,r.fullSchema,this._.schema,this._.tableNamesMap,r.fullSchema[o],s,t,n);this.$cache={invalidate:async(o)=>{}}}static[D]="BaseSQLiteDatabase";query;$with=(e,t)=>{let n=this;return{as:(i)=>{if(typeof i==="function")i=i(new Wu(n.dialect));return new Proxy(new Nu(i.getSQL(),t??("getSelectedFields"in i?i.getSelectedFields()??{}:{}),e,!0),new Lt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Ju({source:e,filters:t,session:this.session})}with(...e){let t=this;function n(c){return new Yr({fields:c??void 0,session:t.session,dialect:t.dialect,withList:e})}function r(c){return new Yr({fields:c??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function i(c){return new uf(c,t.session,t.dialect,e)}function o(c){return new lf(c,t.session,t.dialect,e)}function s(c){return new af(c,t.session,t.dialect,e)}return{select:n,selectDistinct:r,update:i,insert:o,delete:s}}select(e){return new Yr({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Yr({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new uf(e,this.session,this.dialect)}$cache;insert(e){return new lf(e,this.session,this.dialect)}delete(e){return new af(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?b.raw(e):e.getSQL();if(this.resultKind==="async")return new Bc(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?b.raw(e):e.getSQL();if(this.resultKind==="async")return new Bc(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?b.raw(e):e.getSQL();if(this.resultKind==="async")return new Bc(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?b.raw(e):e.getSQL();if(this.resultKind==="async")return new Bc(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}class Pz{static[D]="Cache"}class Gu extends Pz{strategy(){return"all"}static[D]="NoopCache";async get(e){return}async put(e,t,n,r){}async onMutate(e){}}async function Cx(e,t){let n=`${e}-${JSON.stringify(t)}`,i=new TextEncoder().encode(n),o=await crypto.subtle.digest("SHA-256",i);return[...new Uint8Array(o)].map((l)=>l.toString(16).padStart(2,"0")).join("")}class Az extends An{constructor(e){super();this.resultCb=e}static[D]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}}class Ex{constructor(e,t,n,r,i,o){if(this.mode=e,this.executeMethod=t,this.query=n,this.cache=r,this.queryMetadata=i,this.cacheConfig=o,r&&r.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[D]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,n){if(this.cache===void 0||W(this.cache,Gu)||this.queryMetadata===void 0)try{return await n()}catch(r){throw new Yi(e,t,r)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await n()}catch(r){throw new Yi(e,t,r)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[r]=await Promise.all([n(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return r}catch(r){throw new Yi(e,t,r)}if(!this.cacheConfig)try{return await n()}catch(r){throw new Yi(e,t,r)}if(this.queryMetadata.type==="select"){let r=await this.cache.get(this.cacheConfig.tag??await Cx(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(r===void 0){let i;try{i=await n()}catch(o){throw new Yi(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await Cx(e,t),i,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),i}return r}try{return await n()}catch(r){throw new Yi(e,t,r)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new Az(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}}class Ix{constructor(e){this.dialect=e}static[D]="SQLiteSession";prepareOneTimeQuery(e,t,n,r,i,o,s){return this.prepareQuery(e,t,n,r,i,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(n){throw new Mc({cause:n,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}}class Rx extends Hu{constructor(e,t,n,r,i=0){super(e,t,n,r);this.schema=r,this.nestedIndex=i}static[D]="SQLiteTransaction";rollback(){throw new nx}}var O=ot("entities",{id:V("id").notNull(),entityType:V("entityType").notNull(),content:V("content").notNull(),contentHash:V("contentHash").notNull(),visibility:V("visibility",{enum:["public","shared","restricted"]}).notNull().default("public"),metadata:V("metadata",{mode:"json"}).$type().notNull().default(b`'{}'`),created:xe("created").notNull().$defaultFn(()=>Date.now()),updated:xe("updated").notNull().$defaultFn(()=>Date.now())},(e)=>({pk:Dn({columns:[e.id,e.entityType]}),visibilityCheck:Uo("entities_visibility_check",b`${e.visibility} IN ('public', 'shared', 'restricted')`)}));function Rr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function kx(e){if(Array.isArray(e))return e.map((t)=>t===void 0?null:kx(t));if(Rr(e))return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,kx(n)]));return e}function ia(e){return JSON.stringify(kx(e))}function ir({contentHash:e,metadata:t,visibility:n}){return Ei(ia({contentHash:e,metadata:t,visibility:n}))}var Oz=200,g3=4,_c=new TextDecoder("utf-8",{ignoreBOM:!0}),df={id:b`CAST(${O.id} AS BLOB)`,entityType:b`CAST(${O.entityType} AS BLOB)`,content:b`CAST(${O.content} AS BLOB)`,contentHash:O.contentHash,metadata:O.metadata,visibility:O.visibility};async function Dz(e,t,n,r){r?.throwIfAborted();let i=n&&new Set(n.map((s)=>JSON.stringify([s.entityType,s.field]))),o=new Map;for(let s of t.getGroupings())for(let c of s.types){if(i&&!i.has(JSON.stringify([c,s.field])))continue;let l=o.get(c)??new Set;l.add(s.field),o.set(c,l)}if(o.size===0)return;await zz(e,t,o,void 0,r)}async function zz(e,t,n,r,i){i?.throwIfAborted();let o=await e.select(df).from(O).where(H(Ke(O.entityType,[...n.keys()]),h3(r))).orderBy(Ue(O.entityType),Ue(O.id)).limit(Oz);await y3(e,t,o,n,i);let s=o.at(-1);if(!s||o.length<Oz)return;return zz(e,t,n,{type:_c.decode(s.entityType),id:_c.decode(s.id)},i)}function h3(e){if(!e)return;return cn(Xi(O.entityType,e.type),H(A(O.entityType,e.type),Xi(O.id,e.id)))}async function y3(e,t,n,r,i){i?.throwIfAborted();let o=n.flatMap((c)=>{let l=_c.decode(c.entityType),u=_c.decode(c.id),p=jz(t,{type:l,id:u,destination:H(A(O.entityType,l),A(O.id,u)),fields:r.get(l)??new Set},c);return p?[p]:[]});if(o.length===0)return;let s=await e.transaction(async(c)=>{let l=[];for(let u of o)if(i?.throwIfAborted(),await Nz(c,t,u)==="conflict")l.push(u.target);return l});for(let c of s){let l=(await e.select(df).from(O).where(c.destination).limit(1))[0];await Mz(e,t,c,l,g3-1,i)}}async function Mz(e,t,n,r,i,o){if(o?.throwIfAborted(),!r)return;if(i===0)throw Error("Grouping reprojection exceeded concurrent-write retry limit");let s=jz(t,n,r);if(!s)return;if(await e.transaction((u)=>(o?.throwIfAborted(),Nz(u,t,s)))!=="conflict")return;let l=(await e.select(df).from(O).where(n.destination).limit(1))[0];return Mz(e,t,n,l,i-1,o)}function jz(e,t,n){let r=new Set(e.groupingFields(t.type)),i=new Set([...t.fields].filter((l)=>r.has(l)));if(i.size===0)return;t={...t,fields:i};let o=_c.decode(n.content),s=e.projectStoredMetadata(t.type,o,n.metadata),c={...n.metadata};for(let l of t.fields)if(delete c[l],Object.hasOwn(s,l))c[l]=s[l];if(ia(c)===ia(n.metadata))return;return{target:t,row:n,content:o,metadata:c}}async function Nz(e,t,n){let{target:r,row:i,content:o,metadata:s}=n,c=(await e.select(df).from(O).where(r.destination).limit(1))[0];if(!c)return"deleted";let l=new Set(t.groupingFields(r.type));if([...r.fields].some((u)=>!l.has(u)))return"conflict";if(ir(c)!==ir(i)||_c.decode(c.content)!==o)return"conflict";return await e.update(O).set({metadata:s}).where(r.destination),"updated"}class Px{dependencies;running;initialized=!1;fullRequested=!1;constructor(e){this.dependencies=e}isReady(){return this.initialized&&!this.running&&!this.hasWork()}invalidate(){this.initialized=!1}run(e=!1){if(this.running)return this.fullRequested||=e,this.running;if(this.fullRequested||=e||!this.initialized,this.isReady())return Promise.resolve();return this.running=this.drain().catch((t)=>{throw this.invalidate(),t}).finally(()=>{this.running=void 0}),this.running}hasWork(){return this.fullRequested||this.dependencies.pending().length>0}async drain(){for(let e=0;e<4;e++){await this.dependencies.refresh();let t=this.dependencies.pending(),n=this.fullRequested;this.fullRequested=!1;try{if(n||t.length>0)await this.dependencies.project(n?void 0:t)}catch(r){throw this.fullRequested||=n,r}if(this.dependencies.complete(t),await this.dependencies.refresh(),!this.hasWork()){this.initialized=!0;return}}throw Error("Grouping definitions changed repeatedly during reprojection; retry when changes settle")}}import{createClient as b3,LibsqlError as Lz}from"@libsql/client";import{createClient as Ox}from"@libsql/client";class ff extends Ix{constructor(e,t,n,r,i){super(t);this.client=e,this.schema=n,this.options=r,this.tx=i,this.logger=r.logger??new ix,this.cache=r.cache??new Gu}static[D]="LibSQLSession";logger;cache;prepareQuery(e,t,n,r,i,o,s){return new _z(this.client,e,this.logger,this.cache,o,s,t,this.tx,n,r,i)}async batch(e){let t=[],n=[];for(let i of e){let o=i._prepare(),s=o.getQuery();t.push(o),n.push({sql:s.sql,args:s.params})}return(await this.client.batch(n)).map((i,o)=>t[o].mapResult(i,!0))}async migrate(e){let t=[],n=[];for(let i of e){let o=i._prepare(),s=o.getQuery();t.push(o),n.push({sql:s.sql,args:s.params})}return(await this.client.migrate(n)).map((i,o)=>t[o].mapResult(i,!0))}async transaction(e,t){let n=await this.client.transaction(),r=new ff(this.client,this.dialect,this.schema,this.options,n),i=new Ax("async",this.dialect,r,this.schema);try{let o=await e(i);return await n.commit(),o}catch(o){throw await n.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}}class Ax extends Rx{static[D]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,n=new Ax("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(b.raw(`savepoint ${t}`));try{let r=await e(n);return await this.session.run(b.raw(`release savepoint ${t}`)),r}catch(r){throw await this.session.run(b.raw(`rollback to savepoint ${t}`)),r}}}class _z extends Ex{constructor(e,t,n,r,i,o,s,c,l,u,p){super("async",l,t,r,i,o);this.client=e,this.logger=n,this.fields=s,this.tx=c,this._isResponseInArrayMode=u,this.customResultMapper=p,this.customResultMapper=p,this.fields=s}static[D]="LibSQLPreparedQuery";async run(e){let t=_u(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let n={sql:this.query.sql,args:t};return this.tx?this.tx.execute(n):this.client.execute(n)})}async all(e){let{fields:t,logger:n,query:r,tx:i,client:o,customResultMapper:s}=this;if(!t&&!s){let l=_u(r.params,e??{});return n.logQuery(r.sql,l),await this.queryWithCache(r.sql,l,async()=>{let u={sql:r.sql,args:l};return(i?i.execute(u):o.execute(u)).then(({rows:p})=>this.mapAllResult(p))})}let c=await this.values(e);return this.mapAllResult(c)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((n)=>Bz(n));if(this.customResultMapper)return this.customResultMapper(e,mf);return e.map((n)=>ox(this.fields,Array.prototype.slice.call(n).map((r)=>mf(r)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:n,query:r,tx:i,client:o,customResultMapper:s}=this;if(!t&&!s){let l=_u(r.params,e??{});return n.logQuery(r.sql,l),await this.queryWithCache(r.sql,l,async()=>{let u={sql:r.sql,args:l};return(i?i.execute(u):o.execute(u)).then(({rows:p})=>this.mapGetResult(p))})}let c=await this.values(e);return this.mapGetResult(c)}mapGetResult(e,t){if(t)e=e.rows;let n=e[0];if(!this.fields&&!this.customResultMapper)return Bz(n);if(!n)return;if(this.customResultMapper)return this.customResultMapper(e,mf);return ox(this.fields,Array.prototype.slice.call(n).map((r)=>mf(r)),this.joinsNotNullableMap)}async values(e){let t=_u(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let n={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(n):this.client.execute(n)).then(({rows:r})=>r)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}function Bz(e){return Object.keys(e).reduce((t,n)=>{if(Object.prototype.propertyIsEnumerable.call(e,n))t[n]=e[n];return t},{})}function mf(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}class Fz extends Hu{static[D]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}function Fc(e,t={}){let n=new bx({casing:t.casing}),r;if(t.logger===!0)r=new rx;else if(t.logger!==!1)r=t.logger;let i;if(t.schema){let c=LD(t.schema,ZD);i={fullSchema:t.schema,schema:c.tables,tableNamesMap:c.tableNamesMap}}let o=new ff(e,n,i,{logger:r,cache:t.cache},void 0),s=new Fz("async",n,o,i);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}function gf(...e){if(typeof e[0]==="string"){let t=Ox({url:e[0]});return Fc(t,e[1])}if(CD(e[0])){let{connection:t,client:n,...r}=e[0];if(n)return Fc(n,r);let i=typeof t==="string"?Ox({url:t}):Ox(t);return Fc(i,r)}return Fc(e[0],e[1])}((e)=>{function t(n){return Fc({},n)}e.mock=t})(gf||(gf={}));function qz(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}var S3=5000,x3=5,v3=40;function w3(e){return e instanceof Lz&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Vu(e,t){let n=Date.now()+(t.budgetMs??S3),r=async(i)=>{if(t.isClosed())throw new Lz("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!w3(o))throw o;await t.afterRefusal?.();let s=Math.min(x3*2**(i-1),v3),c=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+c>=n)throw o;if(await new Promise((l)=>setTimeout(l,c)),t.isClosed()||Date.now()>=n)throw o;return r(i+1)}};return r(1)}function Dx(e,t={}){let n=b3({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let p=function(m,g){return Vu(()=>typeof m==="string"?s(m,g):s(m),u)},r=n.transaction.bind(n),i=()=>n.closed,o=t.contentionRetryBudgetMs,s=n.execute.bind(n),c=n.batch.bind(n),l=n.migrate.bind(n),u={isClosed:i,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(n.reconnect())}};n.execute=p,n.batch=(m,g)=>Vu(()=>c(m,g),u),n.migrate=(m)=>Vu(()=>l(m),u),n.transaction=(m)=>Vu(()=>r(m),u)}return n}function Xr(e){let{url:t,schema:n}=e,r=qz(e),i={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=r?Dx({url:t,authToken:r},i):Dx({url:t},i);return{db:gf(o,{schema:n}),client:o,url:t}}async function ei(e,t){if(!t.startsWith("file:"))return;let n=()=>e.closed===!0;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await Vu(()=>e.execute(r),{isClosed:n})}import T3 from"crypto";import zx from"fs";function Zz(e){let t=e.migrationsFolder,n=[],r=`${t}/meta/_journal.json`;if(!zx.existsSync(r))throw Error("Can't find meta/_journal.json file");let i=zx.readFileSync(`${t}/meta/_journal.json`).toString(),o=JSON.parse(i);for(let s of o.entries){let c=`${t}/${s.tag}.sql`;try{let l=zx.readFileSync(`${t}/${s.tag}.sql`).toString(),u=l.split("--> statement-breakpoint").map((p)=>p);n.push({sql:u,bps:s.breakpoints,folderMillis:s.when,hash:T3.createHash("sha256").update(l).digest("hex")})}catch{throw Error(`No file ${c} found in ${t} folder`)}}return n}async function $z(e,t){let n=Zz(t),r=t.migrationsTable??"__drizzle_migrations",i=b`
|
|
42
42
|
CREATE TABLE IF NOT EXISTS ${b.identifier(r)} (
|
|
43
43
|
id SERIAL PRIMARY KEY,
|
|
44
44
|
hash text NOT NULL,
|
|
@@ -194,5 +194,5 @@ Result:`);if(n===-1)return;let r=e.slice(n+9).trim();if(!r)return;try{return JSO
|
|
|
194
194
|
`)}function Ete(e){return e.split(`
|
|
195
195
|
`).flatMap((t)=>{let n=t.match(Tte);if(!n)return[];let r=(n[3]??"").split(",").map((i)=>i.trim()).filter(Boolean);return[{name:n[1]??"",description:n[2]??"",tags:r}]})}var P1=new ns(Oh,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:Cte,parser:Ete},{key:"notes",label:"Notes",type:"string"}]});function Ite(e){return P1.format(e)}function Rte(e){if(!e.trim())return Oh.parse({});try{return P1.parse(e)}catch{return Oh.parse({})}}import{EventEmitter as M1}from"events";var Ct={REGISTERED:"registered",INITIALIZED:"initialized",ERROR:"error",DISABLED:"disabled"},zr={REGISTERED:"plugin:registered",BEFORE_INITIALIZE:"plugin:before_initialize",INITIALIZED:"plugin:initialized",ERROR:"plugin:error",DISABLED:"plugin:disabled"};class Mr extends Error{pluginId;constructor(e,t){super(`Plugin ${e}: ${t}`);this.name="PluginError",this.pluginId=e}}function A1(e,t){return Reflect.get(e,t,e)}function O1(e,t,n){if(typeof e!=="function")throw TypeError("Cannot apply a non-callable trapped member");return Reflect.apply(e,t,n)}class mE{scope;ingress=new Set;closePromise=null;closed=!1;constructor(){this.scope=te.runSync(vt.make())}assertOpen(){if(this.closed)throw Error("Cannot register a resource after plugin teardown")}acquire(e,t){this.assertOpen();let n=e();try{this.addFinalizer(()=>t(n))}catch(r){try{t(n)}catch(i){throw AggregateError([r,i],"Plugin acquisition rollback failed",{cause:i})}throw r}return n}addFinalizer(e){this.assertOpen(),te.runSync(vt.addFinalizer(this.scope,te.promise(async()=>{await e()})))}addIngress(e){this.assertOpen(),this.ingress.add(e)}close(e=bt.void){return this.closed=!0,this.closePromise??=this.closeScope(e),this.closePromise}async closeScope(e){let t,n=!1,r=[...this.ingress].reverse();for(let c of r)try{c.stopAdmission()}catch(l){if(!n)t=l;n=!0}let i=await Promise.allSettled(r.map((c)=>Promise.resolve().then(()=>c.drain())));this.ingress.clear();let o=i.find((c)=>c.status==="rejected");if(!n&&o)t=o.reason,n=!0;let s=await te.runPromiseExit(vt.close(this.scope,e));if(!n&&bt.isFailure(s))t=Xn.squash(s.cause),n=!0;if(n)throw t}}function Xp(e,t,n,r){return new Proxy(e,{get(i,o){let s=A1(i,o);if(typeof o==="string"&&t.some((c)=>c===o)&&typeof s==="function")return(...c)=>n.acquire(()=>O1(s,i,c),(l)=>r(c,l));return typeof s==="function"?s.bind(i):s}})}function Yp(e,t,n){return Xp(e,t,n,(r)=>{let i=r[0];if(typeof i==="string")e.unregisterPlugin(i)})}function D1(e,t){let n=e.getMessageBus(),r=new Set,i={send:(G)=>n.send(G),hasHandlers:(G)=>n.hasHandlers?.(G)??!1,subscribe:(G,I,ee)=>{t.assertOpen();let he=!0,Ee=new Set,We=(se)=>{if(!he)return{noop:!0};let ue,Ae=new Promise((rt)=>{ue=rt});Ee.add(Ae);let ie=()=>{Ee.delete(Ae),ue()},Xe;try{Xe=Promise.resolve(I(se))}catch(rt){throw ie(),rt}return Xe.then((rt)=>(ie(),rt),(rt)=>{throw ie(),rt})},Ye=n.subscribe(G,We,ee),Ie={type:G,originalHandler:I,stopAdmission:()=>{if(!he)return;he=!1,Ye(),r.delete(Ie)}};r.add(Ie);try{t.addIngress({stopAdmission:Ie.stopAdmission,drain:async()=>{await Promise.all(Ee)}})}catch(se){throw Ie.stopAdmission(),se}return Ie.stopAdmission},unsubscribe:(G,I)=>{let ee=[...r].filter((he)=>he.type===G&&he.originalHandler===I);if(ee.length===0){n.unsubscribe(G,I);return}for(let he of ee)he.stopAdmission()},collect:(G)=>n.collect(G),validateMessage:(G,I)=>n.validateMessage(G,I),getHandlerCount:(G)=>n.getHandlerCount(G),getTargetedHandlerCount:(G,I)=>n.getTargetedHandlerCount(G,I),clearHandlers:(G)=>n.clearHandlers(G),clearAllHandlers:()=>n.clearAllHandlers()},o=e.getAttachmentRegistry(),s={...o,register:(G,I,ee)=>t.acquire(()=>o.register(G,I,ee),(he)=>he())},c=e.getEntityRegistry(),l=Xp(c,["registerEntityType"],t,(G)=>{let I=G[0];if(typeof I==="string")c.unregisterEntityType(I)}),u=Yp(e.getProfileKindRegistry(),["register"],t),p=Yp(e.getChannelRegistry(),["registerDescriptor","registerDeliveryProvider"],t),m=Yp(e.getInboxRegistry(),["registerSource"],t),g=Yp(e.getInboxFollowUpRegistry(),["registerKind"],t),f=e.getAccountSettingsRegistry(),v=Xp(f,["register"],t,(G,I)=>{O1(f.unregister,f,[I])}),w=Yp(e.getOperationalHealthRegistry(),["register"],t),k=e.getDataSourceRegistry(),P=Xp(k,["register"],t,(G)=>{let I=G[0];if(typeof I==="object"&&I!==null&&"id"in I&&typeof I.id==="string"){let ee=I.id.includes(":")?I.id:`shell:${I.id}`;k.unregister(ee)}}),B=e.getInsightsRegistry(),j=Xp(B,["register"],t,(G)=>{let I=G[0];if(typeof I==="string")B.unregister(I)}),Y=new Proxy(e,{get(G,I){if(I==="getMessageBus")return()=>i;if(I==="getAttachmentRegistry")return()=>s;if(I==="getEntityRegistry")return()=>l;if(I==="getDataSourceRegistry")return()=>P;if(I==="getProfileKindRegistry")return()=>u;if(I==="getChannelRegistry")return()=>p;if(I==="getInboxRegistry")return()=>m;if(I==="getInboxFollowUpRegistry")return()=>g;if(I==="getOperationalHealthRegistry")return()=>w;if(I==="getAccountSettingsRegistry")return()=>v;if(I==="getInsightsRegistry")return()=>j;let ee=A1(G,I);return typeof ee==="function"?ee.bind(G):ee}});return yF(e,Y),Y}class fE{plugins;events;daemonRegistry;logger;projectionRegistry;resourceScopes=new Map;releasePromises=new Map;constructor(e,t,n,r,i){this.plugins=e,this.events=t,this.daemonRegistry=n,this.projectionRegistry=r,this.logger=i.child("PluginLifecycle")}async initializePlugin(e,t,n){let r=this.plugins.get(e);if(!r)throw new Mr(e,"Registration failed: Plugin is not registered");let i=r.plugin,o=new mE;o.addFinalizer(()=>t.unregisterPluginCapabilities?.(e)),o.addFinalizer(()=>t.getJobQueueService().unregisterPluginHandlers(e)),o.addFinalizer(()=>this.projectionRegistry.unregisterPlugin(e)),this.resourceScopes.set(e,o),this.releasePromises.delete(e),this.logger.debug(`Initializing plugin: ${e}`);try{this.events.emit(zr.BEFORE_INITIALIZE,e,i);let s=await i.register(D1(t,o),n);return r.status=Ct.INITIALIZED,this.logger.debug(`Initialized plugin: ${e}`),this.events.emit(zr.INITIALIZED,e,i),s}catch(s){throw this.logger.error(`Error initializing plugin ${e}: ${Be(s)}`),await this.failPluginInitialization(e,s),s}}async finalizePluginRegistration(e){let t=this.plugins.get(e);if(!t)throw new Mr(e,"Registration finalization failed: Plugin is not registered");if(t.status!==Ct.INITIALIZED)return;try{await t.plugin.finalizeRegistration?.(),this.logger.debug(`Registration finalized for plugin: ${e}`)}catch(n){throw await this.failPluginInitialization(e,n),n}}async readyPlugin(e){let t=this.plugins.get(e);if(!t)throw new Mr(e,"Ready failed: Plugin is not registered");if(t.status!==Ct.INITIALIZED){this.logger.debug(`Skipping ready hook for non-initialized plugin: ${e}`);return}try{await t.plugin.ready?.(),this.logger.debug(`Ready hook completed for plugin: ${e}`)}catch(n){let r=sl(n);t.status=Ct.ERROR,t.error=r;try{this.events.emit(zr.ERROR,e,r)}catch(i){this.logger.error(`Plugin error listener failed for ${e}`,i)}throw r}}async startPluginDaemons(e){let t=this.plugins.get(e);if(t?.status!==Ct.INITIALIZED)return;try{await this.daemonRegistry.startPlugin(e),this.logger.debug(`Started daemons for plugin: ${e}`)}catch(n){if(t.plugin.requiresDaemonStartup?.())throw n;this.logger.warn(`Daemon ${e} failed to start: ${Be(n)}`)}}async failPluginInitialization(e,t){let n=this.plugins.get(e);if(!n)return;let r=n.status!==Ct.ERROR,i=sl(t);if(n.status=Ct.ERROR,n.error=i,await this.releasePluginResources(e,bt.fail(t)),r)try{this.events.emit(zr.ERROR,e,i)}catch(o){this.logger.error(`Plugin error listener failed for ${e}`,o)}}async disablePlugin(e){let t=this.plugins.get(e);if(!t){this.logger.warn(`Cannot disable plugin ${e}: not registered`);return}if(t.status===Ct.DISABLED)return;this.logger.debug(`Disabling plugin: ${e}`);let n=t.status===Ct.ERROR;await this.releasePluginResources(e,bt.void);let r=this.plugins.get(e);if(!n&&r&&r.status!==Ct.DISABLED)r.status=Ct.DISABLED,this.events.emit(zr.DISABLED,e,r.plugin);this.logger.debug(`Disabled plugin: ${e}`)}releasePluginResources(e,t){let n=this.releasePromises.get(e);if(n)return n;let r=this.releasePluginResourcesOnce(e,t);return this.releasePromises.set(e,r),r}async releasePluginResourcesOnce(e,t){let n=this.plugins.get(e);if(!n)return;try{await this.daemonRegistry.stopPlugin(e),this.logger.debug(`Stopped daemons for plugin: ${e}`)}catch(i){this.logger.error(`Failed to stop daemons for plugin: ${e}`,i)}let r=this.resourceScopes.get(e);if(this.resourceScopes.delete(e),r)try{await r.close(t)}catch(i){this.logger.error(`Failed to close resources for plugin ${e}`,i)}if(n.plugin.shutdown)try{await n.plugin.shutdown(),this.logger.debug(`Shutdown completed for plugin: ${e}`)}catch(i){this.logger.error(`Plugin shutdown failed for ${e}:`,i)}for(let i of this.daemonRegistry.getByPlugin(e))try{await this.daemonRegistry.unregister(i.name)}catch(o){this.logger.error(`Failed to unregister daemon ${i.name} for plugin ${e}`,o)}}}class gE{plugins;events;logger;constructor(e,t,n){this.plugins=e,this.events=t,this.logger=n.child("DependencyResolver")}async resolveInitializationOrder(e){this.logger.debug("Resolving plugin initialization order...");let t=Array.from(this.plugins.keys()),n=new Set,r=!0;while(r&&n.size<t.length){r=!1;for(let s of t){if(n.has(s))continue;if(!this.plugins.get(s))continue;if(this.getUnmetDependencies(s).length===0)try{await e(s),n.add(s),r=!0}catch(u){let p=Be(u);this.logger.error(`Failed to initialize plugin ${s}: ${p}`),n.add(s),r=!0}}}let i=t.filter((s)=>!n.has(s));if(i.length>0){let s=i.join(", ");this.logger.error(`Failed to initialize plugins due to dependency issues: ${s}`);for(let c of i){let l=this.getUnmetDependencies(c);this.logger.error(`Plugin ${c} has unmet dependencies: ${l.join(", ")}`);let u=this.plugins.get(c);if(u)u.status=Ct.ERROR,u.error=new Mr(c,`Unmet dependencies: ${l.join(", ")}`);this.events.emit(zr.ERROR,c,u?.error)}}let o=new Set;for(let[s,c]of this.plugins)if(c.status===Ct.INITIALIZED)o.add(s);return this.logger.debug(`Resolved ${o.size} of ${t.length} plugins`),{initialized:o,failed:i}}getUnmetDependencies(e){let t=this.plugins.get(e);if(!t)return[];let{dependencies:n}=t,r=[];for(let i of n){let o=this.plugins.get(i);if(!o){r.push(i);continue}if(o.status!==Ct.INITIALIZED)r.push(i)}return r}}class hE{logger;projectionRegistry;constructor(e,t){this.logger=e.child("CapabilityRegistrar"),this.projectionRegistry=t}async registerCapabilities(e,t,n,r){if(!r?.executionOnly&&n.tools.length>0)e.registerTools(t,n.tools),this.logger.debug(`Registered ${n.tools.length} tools from ${t}`);if(!r?.executionOnly&&n.resources.length>0)e.registerResources(t,n.resources),this.logger.debug(`Registered ${n.resources.length} resources from ${t}`);if(!r?.executionOnly&&n.instructions)e.registerInstructions(t,n.instructions),this.logger.debug(`Registered instructions from ${t}`);let i=n.projectionRules??[];try{for(let o of i)this.projectionRegistry.registerRule(t,o)}catch(o){throw this.projectionRegistry.unregisterPlugin(t),o}if(i.length>0)this.logger.debug(`Registered ${i.length} projection rules from ${t}`)}}class Dh{projections=new Map;rules=new Map;static createFresh(){return new Dh}constructor(){}registerRule(e,t){if(!Object.isFrozen(t))throw Error(`Projection rule "${t.id}" must be created with defineProjectionRule`);let n=this.projections.get(t.id);if(n)throw Error(`Projection "${t.id}" is already registered by "${n.pluginId}"`);let r={id:t.id,pluginId:e,targetType:t.targetType,sources:t.sources.map((o)=>({kind:o.kind,types:[...o.types],...o.excludeTypes?{excludeTypes:[...o.excludeTypes]}:{}}))};this.projections.set(t.id,r),this.rules.set(t.id,t);let i=!0;return()=>{if(!i)return;if(i=!1,this.rules.get(t.id)===t)this.rules.delete(t.id);if(this.projections.get(t.id)===r)this.projections.delete(t.id)}}unregisterPlugin(e){for(let[t,n]of this.projections)if(n.pluginId===e)this.projections.delete(t),this.rules.delete(t)}list(){return Array.from(this.projections.values()).sort((e,t)=>e.id.localeCompare(t.id)).map(Ate)}listRules(){return[...this.rules.values()].sort((e,t)=>e.id.localeCompare(t.id))}validate(e){let t=this.list(),n=new Set(e.map(({type:s})=>s));for(let s of t)if(!n.has(s.targetType))throw Error(`Projection "${s.id}" targets unregistered entity type "${s.targetType}"`);let r=e.filter(({projectionSource:s})=>s).map(({type:s})=>s).sort(),i=Ote(t,r),o=zte(t,i)[0];if(o){let s=Mte(o,i);throw Error(`Projection cycle is not supported: ${[...s,s[0]].join(" -> ")}`)}return Pte({projections:t,edges:i,unknownSourceTypes:kte(t,n)})}}function kte(e,t){let n=[];for(let r of e){let i=[...new Set(r.sources.flatMap((o)=>[...o.types,...o.excludeTypes??[]]).filter((o)=>o!=="*"&&!t.has(o)))].sort();if(i.length>0)n.push({projectionId:r.id,types:i})}return n}function Pte(e){for(let t of e.projections){for(let n of t.sources){if(Object.freeze(n.types),n.excludeTypes)Object.freeze(n.excludeTypes);Object.freeze(n)}Object.freeze(t.sources),Object.freeze(t)}for(let t of e.edges)Object.freeze(t.causes),Object.freeze(t);for(let t of e.unknownSourceTypes)Object.freeze(t.types),Object.freeze(t);return Object.freeze(e.unknownSourceTypes),Object.freeze(e.projections),Object.freeze(e.edges),Object.freeze(e)}function Ate(e){return{...e,sources:e.sources.map((t)=>({...t,types:[...t.types],...t.excludeTypes?{excludeTypes:[...t.excludeTypes]}:{}}))}}function Ote(e,t){let n=new Map;for(let r of e)for(let i of e){let o=Dte(r,i,t);if(o.length===0)continue;n.set(`${r.id}\x00${i.id}`,new Set(o))}return Array.from(n,([r,i])=>{let[o="",s=""]=r.split("\x00");return{from:o,to:s,causes:[...i].sort()}}).sort((r,i)=>r.from.localeCompare(i.from)||r.to.localeCompare(i.to))}function Dte(e,t,n){let r=[];for(let i of t.sources){let o=new Set(i.excludeTypes??[]);if((i.types.includes("*")?[...i.types.filter((c)=>c!=="*"),...n]:i.types).includes(e.targetType)&&!o.has(e.targetType))r.push(`entity:${e.targetType}`)}return[...new Set(r)]}function zte(e,t){let n=e.map(({id:m})=>m).sort(),r=z1(n,t),i=new Map,o=new Map,s=[],c=new Set,l=[],u=0,p=(m)=>{i.set(m,u),o.set(m,u),u++,s.push(m),c.add(m);for(let w of r.get(m)??[])if(!i.has(w))p(w),o.set(m,Math.min(o.get(m)??0,o.get(w)??0));else if(c.has(w))o.set(m,Math.min(o.get(m)??0,i.get(w)??0));if(o.get(m)!==i.get(m))return;let g=[],f;do{if(f=s.pop(),!f)break;c.delete(f),g.push(f)}while(f!==m);let v=r.get(m)?.includes(m)??!1;if(g.length>1||v)l.push(g.sort())};for(let m of n)if(!i.has(m))p(m);return l.sort((m,g)=>(m[0]??"").localeCompare(g[0]??""))}function Mte(e,t){let n=new Set(e),r=z1(e,t),i=[...e].sort()[0];if(!i)return[];if(r.get(i)?.includes(i))return[i];let o=(s,c)=>{for(let l of r.get(s)??[]){if(!n.has(l))continue;if(l===i)return c;if(c.includes(l))continue;let u=o(l,[...c,l]);if(u)return u}return};return o(i,[i])??[...e].sort()}function z1(e,t){let n=new Map;for(let r of e)n.set(r,[]);for(let r of t){let i=n.get(r.from);if(i&&!i.includes(r.to))i.push(r.to)}for(let r of n.values())r.sort();return n}async function j1(e){let n=(await te.runPromise(te.all(e.map((r)=>te.result(te.tryPromise({try:r,catch:(i)=>i}))),{concurrency:"unbounded"}))).find(Kn.isFailure);if(n)throw n.failure}class zh{plugins=new Map;logger;events=new M1;daemonRegistry;shell=null;initializedPluginIds=[];pluginLifecycle;dependencyResolver;capabilityRegistrar;projectionRegistry=Dh.createFresh();projectionGraph;static createFresh(e,t){return new zh(e,t)}setShell(e){this.shell=e}constructor(e,t){this.logger=e.child("PluginManager"),this.events=new M1,this.daemonRegistry=t,this.pluginLifecycle=new fE(this.plugins,this.events,this.daemonRegistry,this.projectionRegistry,e),this.dependencyResolver=new gE(this.plugins,this.events,e),this.capabilityRegistrar=new hE(e,this.projectionRegistry)}registerPlugin(e){if(!e.id)throw new Mr("unknown","Registration failed: Plugin must have an id");if(this.logger.debug(`Registering plugin: ${e.id} (${e.version})`),this.plugins.has(e.id)){let i=this.plugins.get(e.id)?.plugin.version;throw new Mr(e.id,`Registration failed: Plugin is already registered with version ${i}`)}let t=e.dependencies??[],n={plugin:e,status:Ct.REGISTERED,dependencies:t};this.plugins.set(e.id,n),this.logger.debug(`Registered plugin: ${e.id} (${e.version})`),this.events.emit(zr.REGISTERED,e.id,e)}async initializePlugins(e){this.logger.debug("Initializing plugins..."),this.initializedPluginIds=[];let t=await this.dependencyResolver.resolveInitializationOrder(async(n)=>{await this.initializePlugin(n,e)});this.logger.debug(`Initialized ${t.initialized.size} of ${this.plugins.size} plugins`)}async registerInterfaceChannels(e,t){let n=this.shell;if(!n)throw Error("Cannot register interface channels: Shell not set. Call setShell() first.");for(let r of e)try{await r.registerChannelsForExecution?.(n,t)}catch(i){this.logger.error(`Channel registration failed for interface ${r.id}: ${Be(i)}`)}}async initializePlugin(e,t){if(!this.shell)throw new Mr(e,"Cannot initialize plugin: Shell not set. Call setShell() first.");let n=this.shell;try{let r=await this.pluginLifecycle.initializePlugin(e,n,t);await this.capabilityRegistrar.registerCapabilities(n,e,r,{executionOnly:t?.executionOnly}),this.initializedPluginIds.push(e)}catch(r){throw await this.pluginLifecycle.failPluginInitialization(e,r),r}}async finalizePluginRegistrations(){this.logger.debug("Finalizing plugin registrations...");for(let n of this.initializedPluginIds)await this.pluginLifecycle.finalizePluginRegistration(n);if(!this.shell)throw Error("Cannot validate projections before the shell is set");let e=this.shell.getEntityRegistry(),t=this.projectionRegistry.validate(e.getAllEntityTypes().map((n)=>{let r=e.getEntityTypeConfig(n);return{type:n,projectionSource:r.projectionSource!==!1&&r.projectionSourceRole!=="excluded"}}));this.projectionGraph=t;for(let n of t.unknownSourceTypes)this.logger.warn("Projection declares entity source types no installed plugin registers",{projectionId:n.projectionId,types:n.types});this.logger.debug("Validated projection graph",{projections:t.projections.length,edges:t.edges.length})}getProjectionGraphSnapshot(){if(!this.projectionGraph)throw Error("Projection graph has not been finalized");return this.projectionGraph}getProjectionRulesSnapshot(){if(!this.projectionGraph)throw Error("Projection graph has not been finalized");return Object.freeze(this.projectionRegistry.listRules())}async readyPlugins(){this.logger.debug("Dispatching plugin ready hooks...");try{await j1(this.initializedPluginIds.map((e)=>()=>this.pluginLifecycle.readyPlugin(e)))}catch(e){for(let t of this.initializedPluginIds){let n=this.plugins.get(t);if(n?.status===Ct.ERROR)await this.pluginLifecycle.failPluginInitialization(t,n.error??e)}throw e}}async startPluginDaemons(){this.logger.debug("Starting plugin daemons..."),await j1(this.initializedPluginIds.map((e)=>()=>this.pluginLifecycle.startPluginDaemons(e)))}getPlugin(e){return this.plugins.get(e)?.plugin}getPluginStatus(e){return this.plugins.get(e)?.status}hasPlugin(e){return this.plugins.has(e)}isPluginInitialized(e){return this.plugins.get(e)?.status===Ct.INITIALIZED}getAllPluginIds(){return Array.from(this.plugins.keys())}getAllPlugins(){return new Map(this.plugins)}getFailedPlugins(){return Array.from(this.plugins.entries()).filter((e)=>e[1].status===Ct.ERROR&&e[1].error!==void 0).map(([e,t])=>({id:e,error:t.error}))}getPluginPackageName(e){return this.plugins.get(e)?.plugin.packageName}async disablePlugin(e){await this.pluginLifecycle.disablePlugin(e)}async shutdownPlugins(){let e=new Set;for(let t of[...this.initializedPluginIds].reverse())await this.disablePlugin(t),e.add(t);for(let t of[...this.plugins.keys()].reverse())if(!e.has(t))await this.disablePlugin(t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}getEventEmitter(){return this.events}}var N1={public:0,trusted:1,admin:2},jte=[{id:"dashboard",pluginId:"dashboard",label:"Dashboard",visibility:"public",requiresActiveSession:!1},{id:"web-chat",pluginId:"web-chat",label:"Chat",visibility:"trusted",requiresActiveSession:!0},{id:"studio",pluginId:"studio",label:"Studio",visibility:"public",requiresActiveSession:!0}];function Nte(e,t){let n=N1[t.permissionLevel??"public"],r=[];for(let{id:i,pluginId:o,label:s,visibility:c,requiresActiveSession:l}of jte){let u=t.self?.id===i;if(!u&&(n<N1[c]||l&&t.hasActiveSession!==!0))continue;let p=e.filter((f)=>f.pluginId===o&&!(i==="studio"&&f.fullPath==="/chat")).map((f)=>f.fullPath).sort((f,v)=>f.length-v.length),m=i==="web-chat"&&p.length>0?e.find((f)=>f.pluginId==="studio"&&f.fullPath==="/chat")?.fullPath:void 0,g=u?t.self?.href:m??p[0];if(g!==void 0)r.push({id:i,label:s,href:g,isActive:i===t.activeId,...l?{requiresActiveSession:!0}:{}})}return r}export{Oc as va,Hm as wa,b as xa,Fu as ya,jc as za,A as Aa,Zo as Ba,H as Ca,cn as Da,Xi as Ea,PD as Fa,On as Ga,Ke as Ha,Xt as Ia,eo as Ja,na as Ka,ef as La,Ue as Ma,wt as Na,$D as Oa,Uo as Pa,xe as Qa,V as Ra,ot as Sa,ut as Ta,fx as Ua,Dn as Va,O as Wa,Rr as Xa,gf as Ya,Dx as Za,Xr as _a,ei as $a,$z as ab,C3 as bb,E3 as cb,Zt as db,Wo as eb,zt as fb,kt as gb,or as hb,to as ib,Qe as jb,Pr as kb,Uz as lb,Ii as mb,Si as nb,xi as ob,Wm as pb,wi as qb,Ac as rb,Cr as sb,YO as tb,Bte as ub,_te as vb,Mi as wb,Ut as xb,jh as yb,td as zb,Da as Ab,nr as Bb,QO as Cb,Sf as Db,xf as Eb,qx as Fb,Zx as Gb,vf as Hb,wf as Ib,Ux as Jb,Cf as Kb,qc as Lb,no as Mb,Jx as Nb,it as Ob,Zge as Pb,ar as Qb,ti as Rb,iv as Sb,ov as Tb,o5 as Ub,s5 as Vb,et as Wb,F1 as Xb,vE as Yb,x as Zb,Fe as _b,Pt as $b,ji as ac,Fn as bc,Br as cc,wE as dc,Jte as ec,Hte as fc,Gte as gc,id as hc,fs as ic,Nh as jc,CE as kc,Xte as lc,q1 as mc,ene as nc,bo as oc,IE as pc,tne as qc,nne as rc,rne as sc,ine as tc,one as uc,sne as vc,Z1 as wc,be as xc,So as yc,ane as zc,pt as Ac,$e as Bc,at as Cc,xo as Dc,vo as Ec,Qt as Fc,qh as Gc,_r as Hc,dt as Ic,ct as Jc,mne as Kc,Y1 as Lc,El as Mc,Ma as Nc,Nt as Oc,Jh as Pc,bne as Qc,nq as Rc,Il as Sc,wn as Tc,si as Uc,wne as Vc,iq as Wc,ai as Xc,Gn as Yc,sn as Zc,tt as _c,Lr as $c,Vh as ad,yt as bd,mn as cd,qr as dd,ze as ed,Yh as fd,Xh as gd,pi as hd,JE as id,dd as jd,Io as kd,Wne as ld,Ml as md,Jne as nd,Hne as od,oI as pd,bd as qd,ay as rd,sI as sd,Se as td,Pe as ud,xd as vd,Je as wd,an as xd,Cq as yd,uy as zd,py as Ad,dy as Bd,zq as Cd,jq as Dd,Is as Ed,Ro as Fd,Nq as Gd,di as Hd,qq as Id,Kq as Jd,qn as Kd,Zn as Ld,Zi as Md,kd as Nd,fn as Od,fi as Pd,Cn as Qd,Bl as Rd,Ha as Sd,gi as Td,At as Ud,Ga as Vd,He as Wd,gn as Xd,ny as Yd,md as Zd,je as _d,Me as $d,fZ as ae,fI as be,Ze as ce,gr as de,gI as ee,mi as fe,vd as ge,gy as he,yI as ie,wd as je,Kn as ke,Yne as le,nre as me,Td as ne,ire as oe,ore as pe,cre as qe,Et as re,lre as se,ure as te,pre as ue,dre as ve,vI as we,mre as xe,fre as ye,gre as ze,hre as Ae,yre as Be,jl as Ce,bre as De,Sre as Ee,xre as Fe,vre as Ge,wre as He,Ot as Ie,Ore as Je,u$ as Ke,Dre as Le,p$ as Me,Kt as Ne,Va as Oe,Fl as Pe,ks as Qe,hr as Re,f$ as Se,Zr as Te,zre as Ue,Mre as Ve,Ld as We,Nre as Xe,Bre as Ye,qd as Ze,Zd as _e,qre as $e,R$ as af,Zre as bf,As as cf,Ure as df,ko as ef,js as ff,Xa as gf,oe as hf,Oe as if,De as jf,Yl as kf,Le as lf,hn as mf,yn as nf,rm as of,hi as pf,ge as qf,$n as rf,im as sf,Yn as tf,iie as uf,Ui as vf,ac as wf,cc as xf,ru as yf,Mo as zf,uc as Af,zb as Bf,oP as Cf,jo as Df,Gi as Ef,fU as Ff,oie as Gf,sie as Hf,hU as If,aie as Jf,GP as Kf,yr as Lf,zU as Mf,UW as Nf,WW as Of,JW as Pf,sS as Qf,KW as Rf,XW as Sf,eJ as Tf,tJ as Uf,pu as Vf,nJ as Wf,du as Xf,iJ as Yf,sJ as Zf,cJ as _f,uJ as $f,pJ as ag,mJ as bg,gJ as cg,aS as dg,xJ as eg,Hr as fg,kJ as gg,jA as hg,Xn as ig,_J as jg,gu as kg,MU as lg,Hb as mg,Gb as ng,jU as og,NU as pg,BU as qg,_U as rg,Fs as sg,cu as tg,qU as ug,GU as vg,bt as wg,die as xg,Ls as yg,mie as zg,mc as Ag,fie as Bg,gie as Cg,qs as Dg,hie as Eg,yie as Fg,Vb as Gg,rW as Hg,Qb as Ig,dc as Jg,iW as Kg,oW as Lg,sW as Mg,lu as Ng,wm as Og,aW as Pg,vt as Qg,gc as Rg,Zs as Sg,uu as Tg,iS as Ug,RA as Vg,$s as Wg,yW as Xg,Rm as Yg,oS as Zg,bW as _g,fc as $g,vW as ah,Ws as bh,MA as ch,bu as dh,Js as eh,Pie as fh,ZA as gh,Aie as hh,GJ as ih,Oie as jh,$A as kh,Am as lh,Die as mh,zie as nh,Mie as oh,tH as ph,uS as qh,nH as rh,dS as sh,jie as th,hc as uh,oH as vh,Nie as wh,cH as xh,Fie as yh,Lie as zh,$ie as Ah,Uie as Bh,zm as Ch,Yie as Dh,SS as Eh,Xie as Fh,eoe as Gh,Su as Hh,Bo as Ih,bi as Jh,Tc as Kh,DH as Lh,LH as Mh,ZH as Nh,lO as Oh,Bm as Ph,wr as Qh,tG as Rh,fO as Sh,Vr as Th,wG as Uh,Ec as Vh,CG as Wh,EG as Xh,Vs as Yh,IG as Zh,RG as _h,Qi as $h,tr as ai,Tr as bi,kG as ci,ES as di,PG as ei,MG as fi,CS as gi,jG as hi,NG as ii,BG as ji,IO as ki,_G as li,FG as mi,Ic as ni,ZG as oi,Ki as pi,JG as qi,HG as ri,RO as si,kO as ti,Qs as ui,QG as vi,KG as wi,YG as xi,eV as yi,nV as zi,rV as Ai,oV as Bi,cV as Ci,lV as Di,mV as Ei,fV as Fi,gV as Gi,yV as Hi,PO as Ii,AO as Ji,wV as Ki,TV as Li,CV as Mi,EV as Ni,IV as Oi,OV as Pi,zV as Qi,MV as Ri,jV as Si,BV as Ti,LV as Ui,qV as Vi,$V as Wi,GV as Xi,VV as Yi,e2 as Zi,t2 as _i,Cu as $i,i2 as aj,o2 as bj,s2 as cj,c2 as dj,l2 as ej,u2 as fj,p2 as gj,DO as hj,f2 as ij,g2 as jj,h2 as kj,Eu as lj,x2 as mj,v2 as nj,C2 as oj,IS as pj,R2 as qj,Ks as rj,A2 as sj,O2 as tj,D2 as uj,zO as vj,j2 as wj,F2 as xj,Y2 as yj,X2 as zj,eQ as Aj,tQ as Bj,rQ as Cj,sQ as Dj,aQ as Ej,cQ as Fj,lQ as Gj,Iu as Hj,Ru as Ij,gQ as Jj,hQ as Kj,yQ as Lj,SQ as Mj,vQ as Nj,TQ as Oj,jO as Pj,EQ as Qj,RQ as Rj,PQ as Sj,OQ as Tj,MQ as Uj,QQ as Vj,KQ as Wj,YQ as Xj,XQ as Yj,eK as Zj,tK as _j,te as $j,ku as ak,rK as bk,iK as ck,oK as dk,aK as ek,cK as fk,Qr as gk,_O as hk,Rc as ik,LO as jk,qO as kk,Ioe as lk,AS as mk,Pn as nk,Ys as ok,rce as pk,_o as qk,uv as rk,dv as sk,oo as tk,_f as uk,P0 as vk,Vo as wk,A0 as xk,nbe as yk,rbe as zk,Ff as Ak,T as Bk,so as Ck,y as Dk,ne as Ek,h as Fk,ln as Gk,j0 as Hk,ao as Ik,lr as Jk,Mn as Kk,np as Lk,ce as Mk,_t as Nk,_e as Ok,F0 as Pk,L0 as Qk,qe as Rk,Wc as Sk,Jc as Tk,Ko as Uk,fM as Vk,ng as Wk,Yc as Xk,Fv as Yk,Lv as Zk,Qv as _k,lg as $k,aw as al,gg as bl,Sj as cl,xj as dl,Fo as el,ZS as fl,t4 as gl,lw as hl,vj as il,yg as jl,uw as kl,wj as ll,Ou as ml,Ece as nl,Ice as ol,$S as pl,Rce as ql,kce as rl,Pce as sl,Ace as tl,Oce as ul,Dce as vl,zce as wl,Mce as xl,dw as yl,Tj as zl,lo as Al,ol as Bl,_Ae as Cl,rT as Dl,iT as El,NN as Fl,BN as Gl,_N as Hl,FN as Il,H4 as Jl,G4 as Kl,wg as Ll,Q4 as Ml,il as Nl,ns as Ol,T4 as Pl,C4 as Ql,Y4 as Rl,ZN as Sl,e8 as Tl,WN as Ul,n8 as Vl,Tg as Wl,q as Xl,ft as Yl,is as Zl,gT as _l,yT as $l,bT as am,ST as bm,vp as cm,wp as dm,xT as em,vT as fm,v8 as gm,Hn as hm,Cg as im,Eg as jm,Aze as km,Oze as lm,w8 as mm,Dze as nm,Mze as om,A8 as pm,jze as qm,Nze as rm,Bze as sm,_ze as tm,Fze as um,Lze as vm,qze as wm,Zze as xm,$ze as ym,Uze as zm,Wze as Am,N8 as Bm,B8 as Cm,Hze as Dm,Gze as Em,Vze as Fm,Qze as Gm,Kze as Hm,Yze as Im,Xze as Jm,e0e as Km,le as Lm,$t as Mm,va as Nm,po as Om,Ig as Pm,Rg as Qm,hB as Rm,yB as Sm,q8 as Tm,kg as Um,mw as Vm,n4 as Wm,r4 as Xm,fw as Ym,gw as Zm,Ep as _m,Ag as $m,OT as an,J8 as bn,zT as cn,zg as dn,DT as en,MT as fn,V8 as gn,Mg as hn,Q8 as in,Bg as jn,Aj as kn,Bj as ln,Ew as mn,Ow as nn,kN as on,$g as pn,BT as qn,Ip as rn,FT as sn,RX as tn,kX as un,PX as vn,qT as wn,AX as xn,OX as yn,DX as zn,N7 as An,fl as Bn,oL as Cn,lL as Dn,FC as En,Nn as Fn,ah as Gn,pL as Hn,ZC as In,yL as Jn,$p as Kn,bL as Ln,hl as Mn,SL as Nn,JX as On,xL as Pn,vL as Qn,ree as Rn,TL as Sn,cee as Tn,lee as Un,uee as Vn,pee as Wn,dee as Xn,UC as Yn,go as Zn,See as _n,WC as $n,VC as ao,vee as bo,nn as co,rY as do,iY as eo,oY as fo,aY as go,e_ as ho,r_ as io,s_ as jo,oC as ko,c_ as lo,nF as mo,E7 as no,P7 as oo,u_ as po,d_ as qo,KT as ro,M7 as so,WNe as to,j7 as uo,pF as vo,Jg as wo,xC as xo,vC as yo,CF as zo,gl as Ao,Vg as Bo,Qg as Co,Fp as Do,Kg as Eo,DF as Fo,Lp as Go,V7 as Ho,Q7 as Io,K7 as Jo,Y7 as Ko,X7 as Lo,qp as Mo,Zp as No,Tee as Oo,zL as Po,Eee as Qo,_L as Ro,fX as So,bX as To,nh as Uo,ZF as Vo,$F as Wo,SX as Xo,FL as Yo,ih as Zo,NC as _o,IX as $o,LL as ap,yl as bp,UL as cp,WL as dp,JL as ep,HL as fp,VL as gp,YC as hp,XC as ip,XL as jp,eE as kp,gh as lp,n1 as mp,hh as np,tE as op,r1 as pp,i1 as qp,s1 as rp,a1 as sp,yh as tp,u1 as up,p1 as vp,Sh as wp,Jp as xp,Hp as yp,d1 as zp,m1 as Ap,f1 as Bp,aE as Cp,Gp as Dp,h1 as Ep,y1 as Fp,b1 as Gp,S1 as Hp,x1 as Ip,hte as Jp,Eh as Kp,v1 as Lp,Ih as Mp,Rh as Np,kh as Op,w1 as Pp,Ia as Qp,Ph as Rp,Kp as Sp,T1 as Tp,pE as Up,E1 as Vp,wte as Wp,dE as Xp,Ite as Yp,Rte as Zp,Mr as _p,zh as $p,Nte as aq};
|
|
196
196
|
|
|
197
|
-
//# debugId=
|
|
198
|
-
//# sourceMappingURL=index-
|
|
197
|
+
//# debugId=45CCA96411CE4A8864756E2164756E21
|
|
198
|
+
//# sourceMappingURL=index-5bq8yawt.js.map
|