@beeblock/svelar 0.4.8 → 0.5.0

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/cli/bin.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- var da=Object.defineProperty;var Qe=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var w=(o,e)=>()=>(o&&(e=o(o=0)),e);var L=(o,e)=>{for(var t in e)da(o,t,{get:e[t],enumerable:!0})};function S(o,e){let t=Symbol.for(o),s=globalThis;return s[t]||(s[t]=e()),s[t]}var E=w(()=>{"use strict"});var R={};L(R,{Connection:()=>f});var ys,f,P=w(()=>{"use strict";E();ys=class{connections=new Map;config=null;defaultName="default";configure(e){this.config=e,this.defaultName=e.default}async connection(e){let t=e??this.defaultName;if(this.connections.has(t))return this.connections.get(t).drizzle;if(!this.config)throw new Error("Database not configured. Call Connection.configure() first, or register DatabaseServiceProvider.");let s=this.config.connections[t];if(!s)throw new Error(`Database connection "${t}" is not defined in configuration.`);let r=await this.createConnection(s);return this.connections.set(t,r),r.drizzle}async rawClient(e){let t=e??this.defaultName;return await this.connection(t),this.connections.get(t).rawClient}async raw(e,t=[],s){let r=await this.connection(s),i=this.getConfig(s);switch(i.driver){case"sqlite":{let a=await this.rawClient(s),n=t.map(m=>typeof m=="boolean"?m?1:0:m instanceof Date?m.toISOString():m),l=a.prepare(e),c=e.trimStart().toUpperCase();return c.startsWith("SELECT")||c.startsWith("PRAGMA")||c.startsWith("WITH")?l.all(...n):l.run(...n)}case"postgres":return(await this.rawClient(s))(e,...t);case"mysql":{let a=await this.rawClient(s),[n]=await a.execute(e,t);return n}default:throw new Error(`Unsupported driver: ${i.driver}`)}}getDriver(e){return this.getConfig(e).driver}getConfig(e){let t=e??this.defaultName;if(!this.config)throw new Error("Database not configured.");let s=this.config.connections[t];if(!s)throw new Error(`Database connection "${t}" is not defined.`);return s}async disconnect(e){if(e){let t=this.connections.get(e);t&&(await this.closeConnection(t),this.connections.delete(e))}else{for(let[t,s]of this.connections)await this.closeConnection(s);this.connections.clear()}}isConnected(e){return this.connections.has(e??this.defaultName)}async transaction(e,t){let s=this.getConfig(t),r=await this.rawClient(t);switch(s.driver){case"sqlite":{r.exec("BEGIN");try{let i=await e();return r.exec("COMMIT"),i}catch(i){throw r.exec("ROLLBACK"),i}}case"postgres":{await r`BEGIN`;try{let i=await e();return await r`COMMIT`,i}catch(i){throw await r`ROLLBACK`,i}}case"mysql":{let i=await r.getConnection();await i.beginTransaction();try{let a=await e();return await i.commit(),i.release(),a}catch(a){throw await i.rollback(),i.release(),a}}default:throw new Error(`Unsupported driver: ${s.driver}`)}}async createConnection(e){switch(e.driver){case"sqlite":return this.createSQLiteConnection(e);case"postgres":return this.createPostgresConnection(e);case"mysql":return this.createMySQLConnection(e);default:throw new Error(`Unsupported database driver: ${e.driver}`)}}async createSQLiteConnection(e){let t=e.filename??e.database??":memory:";try{let s=(await import("better-sqlite3")).default,{drizzle:r}=await import("drizzle-orm/better-sqlite3"),i=new s(t);return i.pragma("journal_mode = WAL"),i.pragma("foreign_keys = ON"),{drizzle:r(i),config:e,rawClient:i}}catch(s){let r;try{r=(await new Function("mod","return import(mod)")("node:sqlite")).DatabaseSync}catch{throw new Error(`No SQLite driver available. Install better-sqlite3 (npm install better-sqlite3) or use Node.js v22+ which includes built-in SQLite support. Original error: ${s instanceof Error?s.message:String(s)}`)}let i=new r(t);i.exec("PRAGMA journal_mode = WAL"),i.exec("PRAGMA foreign_keys = ON");let a={prepare(l){let c=i.prepare(l);return{all(...m){return c.all(...m)},run(...m){return c.run(...m)},get(...m){return c.get(...m)}}},exec(l){i.exec(l)},pragma(l){return i.prepare(`PRAGMA ${l}`).all()},close(){i.close()}},n;try{let{drizzle:l}=await import("drizzle-orm/better-sqlite3");n=l(a)}catch{n=a}return{drizzle:n,config:e,rawClient:a}}}async createPostgresConnection(e){let t=(await import("postgres")).default,{drizzle:s}=await import("drizzle-orm/postgres-js"),r=e.url??`postgres://${e.user}:${e.password}@${e.host??"localhost"}:${e.port??5432}/${e.database}`,i=t(r);return{drizzle:s(i),config:e,rawClient:i}}async createMySQLConnection(e){let t=await import("mysql2/promise"),{drizzle:s}=await import("drizzle-orm/mysql2"),r=t.createPool({host:e.host??"localhost",port:e.port??3306,database:e.database,user:e.user,password:e.password,uri:e.url});return{drizzle:s(r),config:e,rawClient:r}}async closeConnection(e){try{switch(e.config.driver){case"sqlite":e.rawClient.close();break;case"postgres":await e.rawClient.end();break;case"mysql":await e.rawClient.end();break}}catch{}}},f=S("svelar.connection",()=>new ys)});var F,Ss,Y,B,Gr,Ps=w(()=>{"use strict";P();E();F=class{constructor(e){this.column=e}nullable(){return this.column.nullable=!0,this}notNullable(){return this.column.nullable=!1,this}default(e){return this.column.defaultValue=e,this}primary(){return this.column.primaryKey=!0,this}unique(){return this.column.unique=!0,this}unsigned(){return this.column.unsigned=!0,this}references(e,t){return this.column.references={table:t,column:e},new Ss(this.column)}build(){return this.column}},Ss=class{constructor(e){this.column=e}onDelete(e){return this.column.references.onDelete=e,this}onUpdate(e){return this.column.references.onUpdate=e,this}},Y=class{columns=[];indices=[];compositePrimary=null;addColumn(e,t){let s={name:e,type:t,nullable:!1,primaryKey:!1,autoIncrement:!1,unique:!1,unsigned:!1};return this.columns.push(s),new F(s)}increments(e="id"){let t={name:e,type:"INTEGER",nullable:!1,primaryKey:!0,autoIncrement:!0,unique:!1,unsigned:!0};return this.columns.push(t),new F(t)}bigIncrements(e="id"){let t={name:e,type:"BIGINT",nullable:!1,primaryKey:!0,autoIncrement:!0,unique:!1,unsigned:!0};return this.columns.push(t),new F(t)}string(e,t=255){return this.addColumn(e,`VARCHAR(${t})`)}text(e){return this.addColumn(e,"TEXT")}integer(e){return this.addColumn(e,"INTEGER")}bigInteger(e){return this.addColumn(e,"BIGINT")}float(e){return this.addColumn(e,"FLOAT")}decimal(e,t=8,s=2){return this.addColumn(e,`DECIMAL(${t},${s})`)}boolean(e){return this.addColumn(e,"BOOLEAN")}date(e){return this.addColumn(e,"DATE")}datetime(e){return this.addColumn(e,"DATETIME")}timestamp(e){return this.addColumn(e,"TIMESTAMP")}timestamps(){this.timestamp("created_at").nullable(),this.timestamp("updated_at").nullable()}json(e){return this.addColumn(e,"JSON")}blob(e){return this.addColumn(e,"BLOB")}enum(e,t){return this.addColumn(e,`ENUM(${t.map(s=>`'${s}'`).join(",")})`)}uuid(e="id"){return this.addColumn(e,"UUID")}ulid(e="id"){return this.addColumn(e,"ULID")}jsonb(e){return this.addColumn(e,"JSONB")}primary(e){this.compositePrimary=e}index(e,t){let s=Array.isArray(e)?e:[e];this.indices.push({columns:s,unique:!1,name:t})}uniqueIndex(e,t){let s=Array.isArray(e)?e:[e];this.indices.push({columns:s,unique:!0,name:t})}foreign(e){let t=this.columns.find(s=>s.name===e);if(!t)throw new Error(`Column "${e}" must be defined before adding a foreign key.`);return new F(t)}toSQL(e,t){let s=[],r=[];for(let i of this.columns)r.push(this.columnToSQL(i,t));this.compositePrimary&&r.push(`PRIMARY KEY (${this.compositePrimary.join(", ")})`);for(let i of this.columns)if(i.references){let a=`FOREIGN KEY (${i.name}) REFERENCES ${i.references.table}(${i.references.column})`;i.references.onDelete&&(a+=` ON DELETE ${i.references.onDelete}`),i.references.onUpdate&&(a+=` ON UPDATE ${i.references.onUpdate}`),r.push(a)}s.push(`CREATE TABLE ${e} (
2
+ var ha=Object.defineProperty;var Qe=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var C=(o,e)=>()=>(o&&(e=o(o=0)),e);var L=(o,e)=>{for(var t in e)ha(o,t,{get:e[t],enumerable:!0})};function P(o,e){let t=Symbol.for(o),s=globalThis;return s[t]||(s[t]=e()),s[t]}var E=C(()=>{"use strict"});var R={};L(R,{Connection:()=>f});var ws,f,S=C(()=>{"use strict";E();ws=class{connections=new Map;config=null;defaultName="default";configure(e){this.config=e,this.defaultName=e.default}async connection(e){let t=e??this.defaultName;if(this.connections.has(t))return this.connections.get(t).drizzle;if(!this.config)throw new Error("Database not configured. Call Connection.configure() first, or register DatabaseServiceProvider.");let s=this.config.connections[t];if(!s)throw new Error(`Database connection "${t}" is not defined in configuration.`);let r=await this.createConnection(s);return this.connections.set(t,r),r.drizzle}async rawClient(e){let t=e??this.defaultName;return await this.connection(t),this.connections.get(t).rawClient}async raw(e,t=[],s){let r=await this.connection(s),i=this.getConfig(s);switch(i.driver){case"sqlite":{let a=await this.rawClient(s),n=t.map(m=>typeof m=="boolean"?m?1:0:m instanceof Date?m.toISOString():m),l=a.prepare(e),c=e.trimStart().toUpperCase();return c.startsWith("SELECT")||c.startsWith("PRAGMA")||c.startsWith("WITH")?l.all(...n):l.run(...n)}case"postgres":return(await this.rawClient(s))(e,...t);case"mysql":{let a=await this.rawClient(s),[n]=await a.execute(e,t);return n}default:throw new Error(`Unsupported driver: ${i.driver}`)}}getDriver(e){return this.getConfig(e).driver}getConfig(e){let t=e??this.defaultName;if(!this.config)throw new Error("Database not configured.");let s=this.config.connections[t];if(!s)throw new Error(`Database connection "${t}" is not defined.`);return s}async disconnect(e){if(e){let t=this.connections.get(e);t&&(await this.closeConnection(t),this.connections.delete(e))}else{for(let[t,s]of this.connections)await this.closeConnection(s);this.connections.clear()}}isConnected(e){return this.connections.has(e??this.defaultName)}async transaction(e,t){let s=this.getConfig(t),r=await this.rawClient(t);switch(s.driver){case"sqlite":{r.exec("BEGIN");try{let i=await e();return r.exec("COMMIT"),i}catch(i){throw r.exec("ROLLBACK"),i}}case"postgres":{await r`BEGIN`;try{let i=await e();return await r`COMMIT`,i}catch(i){throw await r`ROLLBACK`,i}}case"mysql":{let i=await r.getConnection();await i.beginTransaction();try{let a=await e();return await i.commit(),i.release(),a}catch(a){throw await i.rollback(),i.release(),a}}default:throw new Error(`Unsupported driver: ${s.driver}`)}}async createConnection(e){switch(e.driver){case"sqlite":return this.createSQLiteConnection(e);case"postgres":return this.createPostgresConnection(e);case"mysql":return this.createMySQLConnection(e);default:throw new Error(`Unsupported database driver: ${e.driver}`)}}async createSQLiteConnection(e){let t=e.filename??e.database??":memory:";try{let s=(await import("better-sqlite3")).default,{drizzle:r}=await import("drizzle-orm/better-sqlite3"),i=new s(t);return i.pragma("journal_mode = WAL"),i.pragma("foreign_keys = ON"),{drizzle:r(i),config:e,rawClient:i}}catch(s){let r;try{r=(await new Function("mod","return import(mod)")("node:sqlite")).DatabaseSync}catch{throw new Error(`No SQLite driver available. Install better-sqlite3 (npm install better-sqlite3) or use Node.js v22+ which includes built-in SQLite support. Original error: ${s instanceof Error?s.message:String(s)}`)}let i=new r(t);i.exec("PRAGMA journal_mode = WAL"),i.exec("PRAGMA foreign_keys = ON");let a={prepare(l){let c=i.prepare(l);return{all(...m){return c.all(...m)},run(...m){return c.run(...m)},get(...m){return c.get(...m)}}},exec(l){i.exec(l)},pragma(l){return i.prepare(`PRAGMA ${l}`).all()},close(){i.close()}},n;try{let{drizzle:l}=await import("drizzle-orm/better-sqlite3");n=l(a)}catch{n=a}return{drizzle:n,config:e,rawClient:a}}}async createPostgresConnection(e){let t=(await import("postgres")).default,{drizzle:s}=await import("drizzle-orm/postgres-js"),r=e.url??`postgres://${e.user}:${e.password}@${e.host??"localhost"}:${e.port??5432}/${e.database}`,i=t(r);return{drizzle:s(i),config:e,rawClient:i}}async createMySQLConnection(e){let t=await import("mysql2/promise"),{drizzle:s}=await import("drizzle-orm/mysql2"),r=t.createPool({host:e.host??"localhost",port:e.port??3306,database:e.database,user:e.user,password:e.password,uri:e.url});return{drizzle:s(r),config:e,rawClient:r}}async closeConnection(e){try{switch(e.config.driver){case"sqlite":e.rawClient.close();break;case"postgres":await e.rawClient.end();break;case"mysql":await e.rawClient.end();break}}catch{}}},f=P("svelar.connection",()=>new ws)});var F,Rs,Y,B,ei,Ts=C(()=>{"use strict";S();E();F=class{constructor(e){this.column=e}nullable(){return this.column.nullable=!0,this}notNullable(){return this.column.nullable=!1,this}default(e){return this.column.defaultValue=e,this}primary(){return this.column.primaryKey=!0,this}unique(){return this.column.unique=!0,this}unsigned(){return this.column.unsigned=!0,this}references(e,t){return this.column.references={table:t,column:e},new Rs(this.column)}build(){return this.column}},Rs=class{constructor(e){this.column=e}onDelete(e){return this.column.references.onDelete=e,this}onUpdate(e){return this.column.references.onUpdate=e,this}},Y=class{columns=[];indices=[];compositePrimary=null;addColumn(e,t){let s={name:e,type:t,nullable:!1,primaryKey:!1,autoIncrement:!1,unique:!1,unsigned:!1};return this.columns.push(s),new F(s)}increments(e="id"){let t={name:e,type:"INTEGER",nullable:!1,primaryKey:!0,autoIncrement:!0,unique:!1,unsigned:!0};return this.columns.push(t),new F(t)}bigIncrements(e="id"){let t={name:e,type:"BIGINT",nullable:!1,primaryKey:!0,autoIncrement:!0,unique:!1,unsigned:!0};return this.columns.push(t),new F(t)}string(e,t=255){return this.addColumn(e,`VARCHAR(${t})`)}text(e){return this.addColumn(e,"TEXT")}integer(e){return this.addColumn(e,"INTEGER")}bigInteger(e){return this.addColumn(e,"BIGINT")}float(e){return this.addColumn(e,"FLOAT")}decimal(e,t=8,s=2){return this.addColumn(e,`DECIMAL(${t},${s})`)}boolean(e){return this.addColumn(e,"BOOLEAN")}date(e){return this.addColumn(e,"DATE")}datetime(e){return this.addColumn(e,"DATETIME")}timestamp(e){return this.addColumn(e,"TIMESTAMP")}timestamps(){this.timestamp("created_at").nullable(),this.timestamp("updated_at").nullable()}json(e){return this.addColumn(e,"JSON")}blob(e){return this.addColumn(e,"BLOB")}enum(e,t){return this.addColumn(e,`ENUM(${t.map(s=>`'${s}'`).join(",")})`)}uuid(e="id"){return this.addColumn(e,"UUID")}ulid(e="id"){return this.addColumn(e,"ULID")}jsonb(e){return this.addColumn(e,"JSONB")}primary(e){this.compositePrimary=e}index(e,t){let s=Array.isArray(e)?e:[e];this.indices.push({columns:s,unique:!1,name:t})}uniqueIndex(e,t){let s=Array.isArray(e)?e:[e];this.indices.push({columns:s,unique:!0,name:t})}foreign(e){let t=this.columns.find(s=>s.name===e);if(!t)throw new Error(`Column "${e}" must be defined before adding a foreign key.`);return new F(t)}toSQL(e,t){let s=[],r=[];for(let i of this.columns)r.push(this.columnToSQL(i,t));this.compositePrimary&&r.push(`PRIMARY KEY (${this.compositePrimary.join(", ")})`);for(let i of this.columns)if(i.references){let a=`FOREIGN KEY (${i.name}) REFERENCES ${i.references.table}(${i.references.column})`;i.references.onDelete&&(a+=` ON DELETE ${i.references.onDelete}`),i.references.onUpdate&&(a+=` ON UPDATE ${i.references.onUpdate}`),r.push(a)}s.push(`CREATE TABLE ${e} (
3
3
  ${r.join(`,
4
4
  `)}
5
- )`);for(let i of this.indices){let a=i.name??`idx_${e}_${i.columns.join("_")}`,n=i.unique?"UNIQUE ":"";s.push(`CREATE ${n}INDEX ${a} ON ${e} (${i.columns.join(", ")})`)}return s}columnToSQL(e,t){let s=e.name,r=e.type;if(t==="sqlite"?r=this.mapSQLiteType(r,e):t==="postgres"?r=this.mapPostgresType(r,e):t==="mysql"&&(r=this.mapMySQLType(r,e)),s+=` ${r}`,e.primaryKey&&!this.compositePrimary&&(s+=" PRIMARY KEY",e.autoIncrement&&(t==="sqlite"?s+=" AUTOINCREMENT":t==="postgres"||t==="mysql"&&(s+=" AUTO_INCREMENT"))),!e.nullable&&!e.primaryKey&&(s+=" NOT NULL"),e.unique&&!e.primaryKey&&(s+=" UNIQUE"),e.defaultValue!==void 0){let i=typeof e.defaultValue=="string"?`'${e.defaultValue}'`:e.defaultValue===null?"NULL":e.defaultValue;s+=` DEFAULT ${i}`}return s}mapSQLiteType(e,t){return e==="BOOLEAN"?"INTEGER":e==="UUID"||e==="ULID"||e.startsWith("ENUM")||e==="JSON"||e==="JSONB"?"TEXT":e==="BIGINT"&&t.autoIncrement?"INTEGER":e}mapPostgresType(e,t){return t.autoIncrement&&e==="INTEGER"?"SERIAL":t.autoIncrement&&e==="BIGINT"?"BIGSERIAL":e==="DATETIME"?"TIMESTAMP":e==="BLOB"?"BYTEA":e.startsWith("ENUM")?"TEXT":e==="UUID"?"UUID":e==="ULID"?"VARCHAR(26)":e==="JSON"||e==="JSONB"?"JSONB":e}mapMySQLType(e,t){return e==="BOOLEAN"?"TINYINT(1)":e==="UUID"?"CHAR(36)":e==="ULID"?"CHAR(26)":e==="JSONB"?"JSON":e==="TIMESTAMP"?"DATETIME":t.unsigned&&!e.startsWith("DECIMAL")?`${e} UNSIGNED`:e}},B=class{constructor(e){this.connectionName=e}async createTable(e,t){let s=new Y;t(s);let r=f.getDriver(this.connectionName),i=s.toSQL(e,r);for(let a of i)await f.raw(a,[],this.connectionName)}async dropTable(e){await f.raw(`DROP TABLE IF EXISTS ${e}`,[],this.connectionName)}async dropTableIfExists(e){await f.raw(`DROP TABLE IF EXISTS ${e}`,[],this.connectionName)}async renameTable(e,t){f.getDriver(this.connectionName)==="mysql"?await f.raw(`RENAME TABLE ${e} TO ${t}`,[],this.connectionName):await f.raw(`ALTER TABLE ${e} RENAME TO ${t}`,[],this.connectionName)}async hasTable(e){let t=f.getDriver(this.connectionName),s;switch(t){case"sqlite":s=await f.raw("SELECT name FROM sqlite_master WHERE type='table' AND name=?",[e],this.connectionName);break;case"postgres":s=await f.raw("SELECT tablename FROM pg_tables WHERE tablename = $1",[e],this.connectionName);break;case"mysql":s=await f.raw("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = ?",[e],this.connectionName);break;default:throw new Error(`Unsupported driver: ${t}`)}return s.length>0}async addColumn(e,t){let s=new Y;t(s);let r=f.getDriver(this.connectionName),i=s.columns;for(let a of i){let n=s.columnToSQL(a,r);await f.raw(`ALTER TABLE ${e} ADD COLUMN ${n}`,[],this.connectionName)}}async dropColumn(e,t){await f.raw(`ALTER TABLE ${e} DROP COLUMN ${t}`,[],this.connectionName)}},Gr=S("svelar.schema",()=>new B)});var Yr={};L(Yr,{Migration:()=>Te,Migrator:()=>ke});var Te,ke,Rs=w(()=>{"use strict";P();Ps();Te=class{schema=new B},ke=class{migrationsTable="svelar_migrations";connectionName;constructor(e){this.connectionName=e}async ensureMigrationsTable(){let e=new B(this.connectionName);await e.hasTable(this.migrationsTable)||await e.createTable(this.migrationsTable,s=>{s.increments("id"),s.string("migration").unique(),s.integer("batch"),s.timestamp("ran_at").default("CURRENT_TIMESTAMP")})}async run(e){await this.ensureMigrationsTable();let t=await this.getRanMigrations(),s=e.filter(a=>!t.includes(a.name));if(s.length===0)return[];let r=await this.getNextBatch(),i=[];for(let a of s)await a.migration.up(),await f.raw(`INSERT INTO ${this.migrationsTable} (migration, batch) VALUES (?, ?)`,[a.name,r],this.connectionName),i.push(a.name);return i}async rollback(e){await this.ensureMigrationsTable();let t=await this.getLastBatch();if(t===0)return[];let s=await f.raw(`SELECT migration FROM ${this.migrationsTable} WHERE batch = ? ORDER BY id DESC`,[t],this.connectionName),r=[];for(let i of s){let a=i.migration,n=e.find(l=>l.name===a);n&&(await n.migration.down(),await f.raw(`DELETE FROM ${this.migrationsTable} WHERE migration = ?`,[a],this.connectionName),r.push(a))}return r}async reset(e){let t=[];for(;;){let s=await this.rollback(e);if(s.length===0)break;t.push(...s)}return t}async refresh(e){let t=await this.reset(e),s=await this.run(e);return{reset:t,migrated:s}}async fresh(e){let t=await this.dropAllTables(),s=await this.run(e);return{dropped:t,migrated:s}}async dropAllTables(){let e=f.getDriver(this.connectionName),t=[];switch(e){case"sqlite":{t=(await f.raw("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",[],this.connectionName)).map(r=>r.name),await f.raw("PRAGMA foreign_keys = OFF",[],this.connectionName);for(let r of t)await f.raw(`DROP TABLE IF EXISTS "${r}"`,[],this.connectionName);await f.raw("PRAGMA foreign_keys = ON",[],this.connectionName);break}case"mysql":{t=(await f.raw("SHOW TABLES",[],this.connectionName)).map(r=>Object.values(r)[0]),await f.raw("SET FOREIGN_KEY_CHECKS = 0",[],this.connectionName);for(let r of t)await f.raw(`DROP TABLE IF EXISTS \`${r}\``,[],this.connectionName);await f.raw("SET FOREIGN_KEY_CHECKS = 1",[],this.connectionName);break}case"postgres":{t=(await f.raw("SELECT tablename FROM pg_tables WHERE schemaname = 'public'",[],this.connectionName)).map(r=>r.tablename);for(let r of t)await f.raw(`DROP TABLE IF EXISTS "${r}" CASCADE`,[],this.connectionName);break}default:throw new Error(`Unsupported driver for fresh: ${e}`)}return t}async getRanMigrations(){try{return(await f.raw(`SELECT migration FROM ${this.migrationsTable} ORDER BY batch, id`,[],this.connectionName)).map(t=>t.migration)}catch{return[]}}async status(e){let t=await this.getRanMigrations(),s=new Map;try{let r=await f.raw(`SELECT migration, batch FROM ${this.migrationsTable}`,[],this.connectionName);for(let i of r)s.set(i.migration,i.batch)}catch{}return e.map(r=>({name:r.name,ran:t.includes(r.name),batch:s.get(r.name)??null}))}async getNextBatch(){return await this.getLastBatch()+1}async getLastBatch(){try{return(await f.raw(`SELECT MAX(batch) as max_batch FROM ${this.migrationsTable}`,[],this.connectionName))[0]?.max_batch??0}catch{return 0}}}});var Rt={};L(Rt,{SchedulerLock:()=>$e});import{hostname as Jn}from"os";async function Ee(){let{Connection:o}=await Promise.resolve().then(()=>(P(),R));return o}async function Vn(){return(await Ee()).getDriver()}var ei,W,$e,Ae=w(()=>{"use strict";ei=!1,W=`${Jn()}:${process.pid}:${Math.random().toString(36).slice(2,10)}`;$e=class{static getOwnerId(){return W}static async ensureTable(){if(ei)return;let e=await Ee();switch(e.getDriver()){case"sqlite":await e.raw(`CREATE TABLE IF NOT EXISTS scheduler_locks (
5
+ )`);for(let i of this.indices){let a=i.name??`idx_${e}_${i.columns.join("_")}`,n=i.unique?"UNIQUE ":"";s.push(`CREATE ${n}INDEX ${a} ON ${e} (${i.columns.join(", ")})`)}return s}columnToSQL(e,t){let s=e.name,r=e.type;if(t==="sqlite"?r=this.mapSQLiteType(r,e):t==="postgres"?r=this.mapPostgresType(r,e):t==="mysql"&&(r=this.mapMySQLType(r,e)),s+=` ${r}`,e.primaryKey&&!this.compositePrimary&&(s+=" PRIMARY KEY",e.autoIncrement&&(t==="sqlite"?s+=" AUTOINCREMENT":t==="postgres"||t==="mysql"&&(s+=" AUTO_INCREMENT"))),!e.nullable&&!e.primaryKey&&(s+=" NOT NULL"),e.unique&&!e.primaryKey&&(s+=" UNIQUE"),e.defaultValue!==void 0){let i=typeof e.defaultValue=="string"?`'${e.defaultValue}'`:e.defaultValue===null?"NULL":e.defaultValue;s+=` DEFAULT ${i}`}return s}mapSQLiteType(e,t){return e==="BOOLEAN"?"INTEGER":e==="UUID"||e==="ULID"||e.startsWith("ENUM")||e==="JSON"||e==="JSONB"?"TEXT":e==="BIGINT"&&t.autoIncrement?"INTEGER":e}mapPostgresType(e,t){return t.autoIncrement&&e==="INTEGER"?"SERIAL":t.autoIncrement&&e==="BIGINT"?"BIGSERIAL":e==="DATETIME"?"TIMESTAMP":e==="BLOB"?"BYTEA":e.startsWith("ENUM")?"TEXT":e==="UUID"?"UUID":e==="ULID"?"VARCHAR(26)":e==="JSON"||e==="JSONB"?"JSONB":e}mapMySQLType(e,t){return e==="BOOLEAN"?"TINYINT(1)":e==="UUID"?"CHAR(36)":e==="ULID"?"CHAR(26)":e==="JSONB"?"JSON":e==="TIMESTAMP"?"DATETIME":t.unsigned&&!e.startsWith("DECIMAL")?`${e} UNSIGNED`:e}},B=class{constructor(e){this.connectionName=e}async createTable(e,t){let s=new Y;t(s);let r=f.getDriver(this.connectionName),i=s.toSQL(e,r);for(let a of i)await f.raw(a,[],this.connectionName)}async dropTable(e){await f.raw(`DROP TABLE IF EXISTS ${e}`,[],this.connectionName)}async dropTableIfExists(e){await f.raw(`DROP TABLE IF EXISTS ${e}`,[],this.connectionName)}async renameTable(e,t){f.getDriver(this.connectionName)==="mysql"?await f.raw(`RENAME TABLE ${e} TO ${t}`,[],this.connectionName):await f.raw(`ALTER TABLE ${e} RENAME TO ${t}`,[],this.connectionName)}async hasTable(e){let t=f.getDriver(this.connectionName),s;switch(t){case"sqlite":s=await f.raw("SELECT name FROM sqlite_master WHERE type='table' AND name=?",[e],this.connectionName);break;case"postgres":s=await f.raw("SELECT tablename FROM pg_tables WHERE tablename = $1",[e],this.connectionName);break;case"mysql":s=await f.raw("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = ?",[e],this.connectionName);break;default:throw new Error(`Unsupported driver: ${t}`)}return s.length>0}async addColumn(e,t){let s=new Y;t(s);let r=f.getDriver(this.connectionName),i=s.columns;for(let a of i){let n=s.columnToSQL(a,r);await f.raw(`ALTER TABLE ${e} ADD COLUMN ${n}`,[],this.connectionName)}}async dropColumn(e,t){await f.raw(`ALTER TABLE ${e} DROP COLUMN ${t}`,[],this.connectionName)}},ei=P("svelar.schema",()=>new B)});var ti={};L(ti,{Migration:()=>Te,Migrator:()=>ke});var Te,ke,ks=C(()=>{"use strict";S();Ts();Te=class{schema=new B},ke=class{migrationsTable="svelar_migrations";connectionName;constructor(e){this.connectionName=e}async ensureMigrationsTable(){let e=new B(this.connectionName);await e.hasTable(this.migrationsTable)||await e.createTable(this.migrationsTable,s=>{s.increments("id"),s.string("migration").unique(),s.integer("batch"),s.timestamp("ran_at").default("CURRENT_TIMESTAMP")})}async run(e){await this.ensureMigrationsTable();let t=await this.getRanMigrations(),s=e.filter(a=>!t.includes(a.name));if(s.length===0)return[];let r=await this.getNextBatch(),i=[];for(let a of s)await a.migration.up(),await f.raw(`INSERT INTO ${this.migrationsTable} (migration, batch) VALUES (?, ?)`,[a.name,r],this.connectionName),i.push(a.name);return i}async rollback(e){await this.ensureMigrationsTable();let t=await this.getLastBatch();if(t===0)return[];let s=await f.raw(`SELECT migration FROM ${this.migrationsTable} WHERE batch = ? ORDER BY id DESC`,[t],this.connectionName),r=[];for(let i of s){let a=i.migration,n=e.find(l=>l.name===a);n&&(await n.migration.down(),await f.raw(`DELETE FROM ${this.migrationsTable} WHERE migration = ?`,[a],this.connectionName),r.push(a))}return r}async reset(e){let t=[];for(;;){let s=await this.rollback(e);if(s.length===0)break;t.push(...s)}return t}async refresh(e){let t=await this.reset(e),s=await this.run(e);return{reset:t,migrated:s}}async fresh(e){let t=await this.dropAllTables(),s=await this.run(e);return{dropped:t,migrated:s}}async dropAllTables(){let e=f.getDriver(this.connectionName),t=[];switch(e){case"sqlite":{t=(await f.raw("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",[],this.connectionName)).map(r=>r.name),await f.raw("PRAGMA foreign_keys = OFF",[],this.connectionName);for(let r of t)await f.raw(`DROP TABLE IF EXISTS "${r}"`,[],this.connectionName);await f.raw("PRAGMA foreign_keys = ON",[],this.connectionName);break}case"mysql":{t=(await f.raw("SHOW TABLES",[],this.connectionName)).map(r=>Object.values(r)[0]),await f.raw("SET FOREIGN_KEY_CHECKS = 0",[],this.connectionName);for(let r of t)await f.raw(`DROP TABLE IF EXISTS \`${r}\``,[],this.connectionName);await f.raw("SET FOREIGN_KEY_CHECKS = 1",[],this.connectionName);break}case"postgres":{t=(await f.raw("SELECT tablename FROM pg_tables WHERE schemaname = 'public'",[],this.connectionName)).map(r=>r.tablename);for(let r of t)await f.raw(`DROP TABLE IF EXISTS "${r}" CASCADE`,[],this.connectionName);break}default:throw new Error(`Unsupported driver for fresh: ${e}`)}return t}async getRanMigrations(){try{return(await f.raw(`SELECT migration FROM ${this.migrationsTable} ORDER BY batch, id`,[],this.connectionName)).map(t=>t.migration)}catch{return[]}}async status(e){let t=await this.getRanMigrations(),s=new Map;try{let r=await f.raw(`SELECT migration, batch FROM ${this.migrationsTable}`,[],this.connectionName);for(let i of r)s.set(i.migration,i.batch)}catch{}return e.map(r=>({name:r.name,ran:t.includes(r.name),batch:s.get(r.name)??null}))}async getNextBatch(){return await this.getLastBatch()+1}async getLastBatch(){try{return(await f.raw(`SELECT MAX(batch) as max_batch FROM ${this.migrationsTable}`,[],this.connectionName))[0]?.max_batch??0}catch{return 0}}}});var kt={};L(kt,{SchedulerLock:()=>$e});import{hostname as no}from"os";async function Ee(){let{Connection:o}=await Promise.resolve().then(()=>(S(),R));return o}async function oo(){return(await Ee()).getDriver()}var ii,W,$e,Ae=C(()=>{"use strict";ii=!1,W=`${no()}:${process.pid}:${Math.random().toString(36).slice(2,10)}`;$e=class{static getOwnerId(){return W}static async ensureTable(){if(ii)return;let e=await Ee();switch(e.getDriver()){case"sqlite":await e.raw(`CREATE TABLE IF NOT EXISTS scheduler_locks (
6
6
  task_key TEXT PRIMARY KEY,
7
7
  owner TEXT NOT NULL,
8
8
  expires_at TEXT NOT NULL
@@ -14,7 +14,7 @@ var da=Object.defineProperty;var Qe=(o=>typeof require<"u"?require:typeof Proxy<
14
14
  task_key VARCHAR(255) PRIMARY KEY,
15
15
  owner VARCHAR(255) NOT NULL,
16
16
  expires_at DATETIME NOT NULL
17
- ) ENGINE=InnoDB`);break}ei=!0}static async acquire(e,t=5){await this.ensureTable();let s=await Ee(),r=await Vn(),i=new Date().toISOString(),a=new Date(Date.now()+t*6e4).toISOString();try{await s.transaction(async()=>{switch(await s.raw("DELETE FROM scheduler_locks WHERE task_key = ? AND expires_at < ?",[e,i]),r){case"sqlite":await s.raw("INSERT OR IGNORE INTO scheduler_locks (task_key, owner, expires_at) VALUES (?, ?, ?)",[e,W,a]);break;case"postgres":await s.raw("INSERT INTO scheduler_locks (task_key, owner, expires_at) VALUES ($1, $2, $3) ON CONFLICT (task_key) DO NOTHING",[e,W,a]);break;case"mysql":await s.raw("INSERT IGNORE INTO scheduler_locks (task_key, owner, expires_at) VALUES (?, ?, ?)",[e,W,a]);break}});let n=await s.raw("SELECT owner FROM scheduler_locks WHERE task_key = ?",[e]);return n.length>0&&n[0].owner===W}catch{return!1}}static async release(e){try{await(await Ee()).raw("DELETE FROM scheduler_locks WHERE task_key = ? AND owner = ?",[e,W])}catch{}}static async releaseAll(){try{await(await Ee()).raw("DELETE FROM scheduler_locks WHERE owner = ?",[W])}catch{}}}});var si={};L(si,{ScheduledTask:()=>Tt,Scheduler:()=>Es,SchedulerLock:()=>$e,cronMatches:()=>ks,parseCron:()=>ti,task:()=>Qn});function De(o,e,t){if(o==="*")return null;let s=new Set;for(let r of o.split(",")){let[i,a]=r.split("/"),n=a?parseInt(a,10):1;if(i==="*")for(let l=e;l<=t;l+=n)s.add(l);else if(i.includes("-")){let[l,c]=i.split("-"),m=parseInt(l,10),p=parseInt(c,10);for(let h=m;h<=p;h+=n)s.add(h)}else s.add(parseInt(i,10))}return[...s].sort((r,i)=>r-i)}function ti(o){let e=o.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron expression: "${o}". Expected 5 fields.`);return{minute:De(e[0],0,59),hour:De(e[1],0,23),dayOfMonth:De(e[2],1,31),month:De(e[3],1,12),dayOfWeek:De(e[4],0,6)}}function ks(o,e){let t=ti(o),s=e.getMinutes(),r=e.getHours(),i=e.getDate(),a=e.getMonth()+1,n=e.getDay();return!(t.minute&&!t.minute.includes(s)||t.hour&&!t.hour.includes(r)||t.dayOfMonth&&!t.dayOfMonth.includes(i)||t.month&&!t.month.includes(a)||t.dayOfWeek&&!t.dayOfWeek.includes(n))}function Qn(o,e,t){class s extends Tt{name=o;schedule(){return t&&t(this),this}async handle(){return e()}}return new s}var Tt,Es,ri=w(()=>{"use strict";Ae();Tt=class{name=this.constructor.name;_running=!1;withoutOverlapping=!1;_lockTtlMinutes=5;_expression="* * * * *";schedule(){return this}onSuccess(){}onFailure(e){console.error(`[Scheduler] Task "${this.name}" failed:`,e.message)}everyMinute(){return this._expression="* * * * *",this}everyMinutes(e){return this._expression=`*/${e} * * * *`,this}everyFiveMinutes(){return this.everyMinutes(5)}everyTenMinutes(){return this.everyMinutes(10)}everyFifteenMinutes(){return this.everyMinutes(15)}everyThirtyMinutes(){return this.everyMinutes(30)}hourly(){return this._expression="0 * * * *",this}hourlyAt(e){return this._expression=`${e} * * * *`,this}daily(){return this._expression="0 0 * * *",this}dailyAt(e){let[t,s]=e.split(":").map(Number);return this._expression=`${s??0} ${t} * * *`,this}twiceDaily(e=1,t=13){return this._expression=`0 ${e},${t} * * *`,this}weekly(){return this._expression="0 0 * * 0",this}weeklyOn(e,t="00:00"){let[s,r]=t.split(":").map(Number);return this._expression=`${r??0} ${s} * * ${e}`,this}weekdays(){return this._expression=`${this._expression.split(" ").slice(0,4).join(" ")} 1-5`,this}weekends(){return this._expression=`${this._expression.split(" ").slice(0,4).join(" ")} 0,6`,this}monthly(){return this._expression="0 0 1 * *",this}monthlyOn(e,t="00:00"){let[s,r]=t.split(":").map(Number);return this._expression=`${r??0} ${s} ${e} * *`,this}quarterly(){return this._expression="0 0 1 1,4,7,10 *",this}yearly(){return this._expression="0 0 1 1 *",this}cron(e){return this._expression=e,this}preventOverlap(){return this.withoutOverlapping=!0,this}lockExpiresAfter(e){return this._lockTtlMinutes=e,this}getExpression(){return this.schedule(),this._expression}isRunning(){return this._running}async executeTask(){if(this.withoutOverlapping&&this._running)return{task:this.name,success:!0,duration:0,timestamp:new Date};let e=!1;if(this.withoutOverlapping)try{let{SchedulerLock:s}=await Promise.resolve().then(()=>(Ae(),Rt));if(e=await s.acquire(this.name,this._lockTtlMinutes),!e)return{task:this.name,success:!0,duration:0,timestamp:new Date}}catch{}this._running=!0;let t=Date.now();try{await this.handle();let s=Date.now()-t;return await this.onSuccess(),{task:this.name,success:!0,duration:s,timestamp:new Date}}catch(s){let r=Date.now()-t;return await this.onFailure(s),{task:this.name,success:!1,duration:r,error:s.message,timestamp:new Date}}finally{if(this._running=!1,e)try{let{SchedulerLock:s}=await Promise.resolve().then(()=>(Ae(),Rt));await s.release(this.name)}catch{}}}},Es=class{tasks=[];timer=null;history=[];maxHistory=100;_persistToDb=!1;persistToDatabase(){return this._persistToDb=!0,this}register(e){return this.tasks.push(e),this}registerMany(e){for(let t of e)this.register(t);return this}async run(e){let t=e??new Date,s=[];for(let r of this.tasks){let i=r.getExpression();if(ks(i,t)){let a=await r.executeTask();s.push(a),this.addToHistory(a)}}return s}start(){if(this.timer)return;this.run().catch(s=>console.error("[Scheduler] Error:",s));let t=6e4-Date.now()%6e4;this.timer=setTimeout(()=>{this.run().catch(s=>console.error("[Scheduler] Error:",s)),this.timer=setInterval(()=>{this.run().catch(s=>console.error("[Scheduler] Error:",s))},6e4)},t),console.log(`[Scheduler] Started with ${this.tasks.length} task(s). Next tick in ${Math.round(t/1e3)}s.`)}async stop(){this.timer&&(clearTimeout(this.timer),clearInterval(this.timer),this.timer=null);try{let{SchedulerLock:e}=await Promise.resolve().then(()=>(Ae(),Rt));await e.releaseAll()}catch{}console.log("[Scheduler] Stopped.")}getTasks(){return[...this.tasks]}getHistory(){return[...this.history]}dueTasks(e){let t=e??new Date;return this.tasks.filter(s=>ks(s.getExpression(),t))}remove(e){let t=this.tasks.findIndex(s=>s.name===e);return t!==-1?(this.tasks.splice(t,1),!0):!1}clear(){this.tasks=[]}addToHistory(e){this.history.push(e),this.history.length>this.maxHistory&&this.history.shift(),this._persistToDb&&this.persistResult(e).catch(()=>{})}_historyTableEnsured=!1;async ensureHistoryTable(){if(this._historyTableEnsured)return;let{Connection:e}=await Promise.resolve().then(()=>(P(),R));switch(e.getDriver()){case"sqlite":await e.raw(`CREATE TABLE IF NOT EXISTS scheduled_task_runs (
17
+ ) ENGINE=InnoDB`);break}ii=!0}static async acquire(e,t=5){await this.ensureTable();let s=await Ee(),r=await oo(),i=new Date().toISOString(),a=new Date(Date.now()+t*6e4).toISOString();try{await s.transaction(async()=>{switch(await s.raw("DELETE FROM scheduler_locks WHERE task_key = ? AND expires_at < ?",[e,i]),r){case"sqlite":await s.raw("INSERT OR IGNORE INTO scheduler_locks (task_key, owner, expires_at) VALUES (?, ?, ?)",[e,W,a]);break;case"postgres":await s.raw("INSERT INTO scheduler_locks (task_key, owner, expires_at) VALUES ($1, $2, $3) ON CONFLICT (task_key) DO NOTHING",[e,W,a]);break;case"mysql":await s.raw("INSERT IGNORE INTO scheduler_locks (task_key, owner, expires_at) VALUES (?, ?, ?)",[e,W,a]);break}});let n=await s.raw("SELECT owner FROM scheduler_locks WHERE task_key = ?",[e]);return n.length>0&&n[0].owner===W}catch{return!1}}static async release(e){try{await(await Ee()).raw("DELETE FROM scheduler_locks WHERE task_key = ? AND owner = ?",[e,W])}catch{}}static async releaseAll(){try{await(await Ee()).raw("DELETE FROM scheduler_locks WHERE owner = ?",[W])}catch{}}}});var ni={};L(ni,{ScheduledTask:()=>Et,Scheduler:()=>As,SchedulerLock:()=>$e,cronMatches:()=>$s,parseCron:()=>ai,task:()=>lo});function De(o,e,t){if(o==="*")return null;let s=new Set;for(let r of o.split(",")){let[i,a]=r.split("/"),n=a?parseInt(a,10):1;if(i==="*")for(let l=e;l<=t;l+=n)s.add(l);else if(i.includes("-")){let[l,c]=i.split("-"),m=parseInt(l,10),p=parseInt(c,10);for(let h=m;h<=p;h+=n)s.add(h)}else s.add(parseInt(i,10))}return[...s].sort((r,i)=>r-i)}function ai(o){let e=o.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron expression: "${o}". Expected 5 fields.`);return{minute:De(e[0],0,59),hour:De(e[1],0,23),dayOfMonth:De(e[2],1,31),month:De(e[3],1,12),dayOfWeek:De(e[4],0,6)}}function $s(o,e){let t=ai(o),s=e.getMinutes(),r=e.getHours(),i=e.getDate(),a=e.getMonth()+1,n=e.getDay();return!(t.minute&&!t.minute.includes(s)||t.hour&&!t.hour.includes(r)||t.dayOfMonth&&!t.dayOfMonth.includes(i)||t.month&&!t.month.includes(a)||t.dayOfWeek&&!t.dayOfWeek.includes(n))}function lo(o,e,t){class s extends Et{name=o;schedule(){return t&&t(this),this}async handle(){return e()}}return new s}var Et,As,oi=C(()=>{"use strict";Ae();Et=class{name=this.constructor.name;_running=!1;withoutOverlapping=!1;_lockTtlMinutes=5;_expression="* * * * *";schedule(){return this}onSuccess(){}onFailure(e){console.error(`[Scheduler] Task "${this.name}" failed:`,e.message)}everyMinute(){return this._expression="* * * * *",this}everyMinutes(e){return this._expression=`*/${e} * * * *`,this}everyFiveMinutes(){return this.everyMinutes(5)}everyTenMinutes(){return this.everyMinutes(10)}everyFifteenMinutes(){return this.everyMinutes(15)}everyThirtyMinutes(){return this.everyMinutes(30)}hourly(){return this._expression="0 * * * *",this}hourlyAt(e){return this._expression=`${e} * * * *`,this}daily(){return this._expression="0 0 * * *",this}dailyAt(e){let[t,s]=e.split(":").map(Number);return this._expression=`${s??0} ${t} * * *`,this}twiceDaily(e=1,t=13){return this._expression=`0 ${e},${t} * * *`,this}weekly(){return this._expression="0 0 * * 0",this}weeklyOn(e,t="00:00"){let[s,r]=t.split(":").map(Number);return this._expression=`${r??0} ${s} * * ${e}`,this}weekdays(){return this._expression=`${this._expression.split(" ").slice(0,4).join(" ")} 1-5`,this}weekends(){return this._expression=`${this._expression.split(" ").slice(0,4).join(" ")} 0,6`,this}monthly(){return this._expression="0 0 1 * *",this}monthlyOn(e,t="00:00"){let[s,r]=t.split(":").map(Number);return this._expression=`${r??0} ${s} ${e} * *`,this}quarterly(){return this._expression="0 0 1 1,4,7,10 *",this}yearly(){return this._expression="0 0 1 1 *",this}cron(e){return this._expression=e,this}preventOverlap(){return this.withoutOverlapping=!0,this}lockExpiresAfter(e){return this._lockTtlMinutes=e,this}getExpression(){return this.schedule(),this._expression}isRunning(){return this._running}async executeTask(){if(this.withoutOverlapping&&this._running)return{task:this.name,success:!0,duration:0,timestamp:new Date};let e=!1;if(this.withoutOverlapping)try{let{SchedulerLock:s}=await Promise.resolve().then(()=>(Ae(),kt));if(e=await s.acquire(this.name,this._lockTtlMinutes),!e)return{task:this.name,success:!0,duration:0,timestamp:new Date}}catch{}this._running=!0;let t=Date.now();try{await this.handle();let s=Date.now()-t;return await this.onSuccess(),{task:this.name,success:!0,duration:s,timestamp:new Date}}catch(s){let r=Date.now()-t;return await this.onFailure(s),{task:this.name,success:!1,duration:r,error:s.message,timestamp:new Date}}finally{if(this._running=!1,e)try{let{SchedulerLock:s}=await Promise.resolve().then(()=>(Ae(),kt));await s.release(this.name)}catch{}}}},As=class{tasks=[];timer=null;history=[];maxHistory=100;_persistToDb=!1;persistToDatabase(){return this._persistToDb=!0,this}register(e){return this.tasks.push(e),this}registerMany(e){for(let t of e)this.register(t);return this}async run(e){let t=e??new Date,s=[];for(let r of this.tasks){let i=r.getExpression();if($s(i,t)){let a=await r.executeTask();s.push(a),this.addToHistory(a)}}return s}start(){if(this.timer)return;this.run().catch(s=>console.error("[Scheduler] Error:",s));let t=6e4-Date.now()%6e4;this.timer=setTimeout(()=>{this.run().catch(s=>console.error("[Scheduler] Error:",s)),this.timer=setInterval(()=>{this.run().catch(s=>console.error("[Scheduler] Error:",s))},6e4)},t),console.log(`[Scheduler] Started with ${this.tasks.length} task(s). Next tick in ${Math.round(t/1e3)}s.`)}async stop(){this.timer&&(clearTimeout(this.timer),clearInterval(this.timer),this.timer=null);try{let{SchedulerLock:e}=await Promise.resolve().then(()=>(Ae(),kt));await e.releaseAll()}catch{}console.log("[Scheduler] Stopped.")}getTasks(){return[...this.tasks]}getHistory(){return[...this.history]}dueTasks(e){let t=e??new Date;return this.tasks.filter(s=>$s(s.getExpression(),t))}remove(e){let t=this.tasks.findIndex(s=>s.name===e);return t!==-1?(this.tasks.splice(t,1),!0):!1}clear(){this.tasks=[]}addToHistory(e){this.history.push(e),this.history.length>this.maxHistory&&this.history.shift(),this._persistToDb&&this.persistResult(e).catch(()=>{})}_historyTableEnsured=!1;async ensureHistoryTable(){if(this._historyTableEnsured)return;let{Connection:e}=await Promise.resolve().then(()=>(S(),R));switch(e.getDriver()){case"sqlite":await e.raw(`CREATE TABLE IF NOT EXISTS scheduled_task_runs (
18
18
  id INTEGER PRIMARY KEY AUTOINCREMENT,
19
19
  task TEXT NOT NULL,
20
20
  success INTEGER NOT NULL,
@@ -35,11 +35,11 @@ var da=Object.defineProperty;var Qe=(o=>typeof require<"u"?require:typeof Proxy<
35
35
  duration INT NOT NULL,
36
36
  error TEXT,
37
37
  ran_at DATETIME NOT NULL
38
- ) ENGINE=InnoDB`);break}this._historyTableEnsured=!0}async persistResult(e){try{await this.ensureHistoryTable();let{Connection:t}=await Promise.resolve().then(()=>(P(),R));await t.raw("INSERT INTO scheduled_task_runs (task, success, duration, error, ran_at) VALUES (?, ?, ?, ?, ?)",[e.task,e.success,e.duration,e.error||null,e.timestamp.toISOString()])}catch{}}}});var Le={};L(Le,{Job:()=>X,Queue:()=>Ns});var X,Et,As,Z,$t,Ds,Ls,_s,Ms,Ns,ee=w(()=>{"use strict";E();X=class{attempts=0;maxAttempts=3;retryDelay=60;queue="default";failed(e){console.error(`[Queue] Job ${this.constructor.name} permanently failed:`,e.message)}retrying(e){}serialize(){let e={};for(let[t,s]of Object.entries(this))typeof s!="function"&&(e[t]=s);return JSON.stringify(e)}restore(e){for(let[t,s]of Object.entries(e))t!=="attempts"&&t!=="maxAttempts"&&t!=="retryDelay"&&t!=="queue"&&(this[t]=s)}},Et=class{async push(e){try{e.job.attempts=1,await e.job.handle()}catch(t){if(e.attempts+1<e.maxAttempts)return e.attempts++,e.job.attempts=e.attempts+1,e.job.retrying(e.job.attempts),this.push(e);e.job.failed(t)}}async pop(){return null}async size(){return 0}async clear(){}},As=class{queues=new Map;async push(e){let t=e.queue;this.queues.has(t)||this.queues.set(t,[]),this.queues.get(t).push(e)}async pop(e="default"){let t=this.queues.get(e)??[],s=Date.now(),r=t.findIndex(i=>i.availableAt<=s);return r===-1?null:t.splice(r,1)[0]}async size(e="default"){return this.queues.get(e)?.length??0}async clear(e){e?this.queues.delete(e):this.queues.clear()}},Z=class{constructor(e,t){this.table=e;this.registry=t}async getConnection(){let{Connection:e}=await Promise.resolve().then(()=>(P(),R));return e}async push(e){await(await this.getConnection()).raw(`INSERT INTO ${this.table} (id, queue, payload, attempts, max_attempts, available_at, created_at)
38
+ ) ENGINE=InnoDB`);break}this._historyTableEnsured=!0}async persistResult(e){try{await this.ensureHistoryTable();let{Connection:t}=await Promise.resolve().then(()=>(S(),R));await t.raw("INSERT INTO scheduled_task_runs (task, success, duration, error, ran_at) VALUES (?, ?, ?, ?, ?)",[e.task,e.success,e.duration,e.error||null,e.timestamp.toISOString()])}catch{}}}});var Le={};L(Le,{Job:()=>X,Queue:()=>js});var X,At,Ls,Z,Dt,_s,Ms,Ns,Is,js,ee=C(()=>{"use strict";E();X=class{attempts=0;maxAttempts=3;retryDelay=60;queue="default";failed(e){console.error(`[Queue] Job ${this.constructor.name} permanently failed:`,e.message)}retrying(e){}serialize(){let e={};for(let[t,s]of Object.entries(this))typeof s!="function"&&(e[t]=s);return JSON.stringify(e)}restore(e){for(let[t,s]of Object.entries(e))t!=="attempts"&&t!=="maxAttempts"&&t!=="retryDelay"&&t!=="queue"&&(this[t]=s)}},At=class{async push(e){try{e.job.attempts=1,await e.job.handle()}catch(t){if(e.attempts+1<e.maxAttempts)return e.attempts++,e.job.attempts=e.attempts+1,e.job.retrying(e.job.attempts),this.push(e);e.job.failed(t)}}async pop(){return null}async size(){return 0}async clear(){}},Ls=class{queues=new Map;async push(e){let t=e.queue;this.queues.has(t)||this.queues.set(t,[]),this.queues.get(t).push(e)}async pop(e="default"){let t=this.queues.get(e)??[],s=Date.now(),r=t.findIndex(i=>i.availableAt<=s);return r===-1?null:t.splice(r,1)[0]}async size(e="default"){return this.queues.get(e)?.length??0}async clear(e){e?this.queues.delete(e):this.queues.clear()}},Z=class{constructor(e,t){this.table=e;this.registry=t}async getConnection(){let{Connection:e}=await Promise.resolve().then(()=>(S(),R));return e}async push(e){await(await this.getConnection()).raw(`INSERT INTO ${this.table} (id, queue, payload, attempts, max_attempts, available_at, created_at)
39
39
  VALUES (?, ?, ?, ?, ?, ?, ?)`,[e.id,e.queue,JSON.stringify({jobClass:e.jobClass,payload:e.payload}),e.attempts,e.maxAttempts,Math.floor(e.availableAt/1e3),Math.floor(e.createdAt/1e3)])}async pop(e="default"){let t=await this.getConnection(),s=Math.floor(Date.now()/1e3),r=await t.raw(`SELECT * FROM ${this.table}
40
40
  WHERE queue = ? AND available_at <= ? AND reserved_at IS NULL
41
- ORDER BY created_at ASC LIMIT 1`,[e,s]);if(!r||r.length===0)return null;let i=r[0];await t.raw(`UPDATE ${this.table} SET reserved_at = ?, attempts = attempts + 1 WHERE id = ?`,[s,i.id]);let a=JSON.parse(i.payload),n=this.registry.resolve(a.jobClass,a.payload);return{id:i.id,jobClass:a.jobClass,payload:a.payload,queue:i.queue,attempts:i.attempts+1,maxAttempts:i.max_attempts,availableAt:i.available_at*1e3,createdAt:i.created_at*1e3,job:n}}async size(e="default"){return(await(await this.getConnection()).raw(`SELECT COUNT(*) as count FROM ${this.table} WHERE queue = ? AND reserved_at IS NULL`,[e]))?.[0]?.count??0}async clear(e){let t=await this.getConnection();e?await t.raw(`DELETE FROM ${this.table} WHERE queue = ?`,[e]):await t.raw(`DELETE FROM ${this.table}`,[])}async delete(e){await(await this.getConnection()).raw(`DELETE FROM ${this.table} WHERE id = ?`,[e])}async release(e,t=0){let s=await this.getConnection(),r=Math.floor(Date.now()/1e3)+t;await s.raw(`UPDATE ${this.table} SET reserved_at = NULL, available_at = ? WHERE id = ?`,[r,e])}},$t=class{queues=new Map;config;registry;_bullmq=null;constructor(e,t){this.config=e,this.registry=t}async getBullMQ(){if(this._bullmq)return this._bullmq;try{return this._bullmq=await Function('return import("bullmq")')(),this._bullmq}catch{throw new Error("bullmq is required for the Redis queue driver. Install it with: npm install bullmq")}}getRedisConnection(){if(this.config.url){let e=new URL(this.config.url);return{host:e.hostname||"localhost",port:parseInt(e.port)||6379,password:e.password||this.config.password||void 0,db:parseInt(e.pathname?.slice(1)||"0")||this.config.db||0}}return{host:this.config.host??"localhost",port:this.config.port??6379,password:this.config.password,db:this.config.db??0}}async getQueue(e){if(this.queues.has(e))return this.queues.get(e);let t=await this.getBullMQ(),s=this.getRedisConnection(),r=this.config.prefix??"svelar",i=new t.Queue(e,{connection:s,prefix:r,defaultJobOptions:{removeOnComplete:this.config.defaultJobOptions?.removeOnComplete??100,removeOnFail:this.config.defaultJobOptions?.removeOnFail??500}});return this.queues.set(e,i),i}async push(e){let t=await this.getQueue(e.queue),s=Math.max(0,e.availableAt-Date.now());await t.add(e.jobClass,{jobClass:e.jobClass,payload:e.payload},{jobId:e.id,delay:s>0?s:void 0,attempts:e.maxAttempts,backoff:{type:"fixed",delay:(e.job.retryDelay??60)*1e3}})}async pop(e){return null}async size(e="default"){let s=await(await this.getQueue(e)).getJobCounts("waiting","delayed","active");return s.waiting+s.delayed+s.active}async clear(e){if(e)await(await this.getQueue(e)).obliterate({force:!0});else for(let t of this.queues.values())await t.obliterate({force:!0})}async createWorker(e,t,s,r){let i=await this.getBullMQ(),a=this.getRedisConnection(),n=this.config.prefix??"svelar",l=new i.Worker(e,async c=>{let m=c.data,p=t.resolve(m.jobClass,m.payload);p.attempts=c.attemptsMade+1,await p.handle()},{connection:a,prefix:n,concurrency:r?.concurrency??1});return l.on("failed",async(c,m)=>{let p=c?.data;if(p)try{let h=t.resolve(p.jobClass,p.payload);c.attemptsMade>=(c.opts?.attempts??3)&&(h.failed(m),await s.store({id:c.id,jobClass:p.jobClass,payload:p.payload,queue:e,attempts:c.attemptsMade,maxAttempts:c.opts?.attempts??3,availableAt:Date.now(),createdAt:c.timestamp??Date.now(),job:h},m))}catch{console.error("[Queue] Failed to resolve job for failure handler:",m.message)}}),l}},Ds=class{table="svelar_failed_jobs";async getConnection(){let{Connection:e}=await Promise.resolve().then(()=>(P(),R));return e}async store(e,t){try{await(await this.getConnection()).raw(`INSERT INTO ${this.table} (id, queue, job_class, payload, exception, failed_at)
42
- VALUES (?, ?, ?, ?, ?, ?)`,[crypto.randomUUID(),e.queue,e.jobClass,e.payload,t.stack??t.message,Math.floor(Date.now()/1e3)])}catch{console.error("[Queue] Could not persist failed job (run migration to create svelar_failed_jobs table)")}}async all(){return(await(await this.getConnection()).raw(`SELECT * FROM ${this.table} ORDER BY failed_at DESC`,[])??[]).map(s=>({id:s.id,queue:s.queue,jobClass:s.job_class,payload:s.payload,exception:s.exception,failedAt:s.failed_at}))}async find(e){let s=await(await this.getConnection()).raw(`SELECT * FROM ${this.table} WHERE id = ? LIMIT 1`,[e]);if(!s||s.length===0)return null;let r=s[0];return{id:r.id,queue:r.queue,jobClass:r.job_class,payload:r.payload,exception:r.exception,failedAt:r.failed_at}}async forget(e){return await(await this.getConnection()).raw(`DELETE FROM ${this.table} WHERE id = ?`,[e]),!0}async flush(){let e=await this.getConnection(),s=(await e.raw(`SELECT COUNT(*) as count FROM ${this.table}`,[]))?.[0]?.count??0;return await e.raw(`DELETE FROM ${this.table}`,[]),s}},Ls=class{jobs=new Map;register(e){this.jobs.set(e.name,e)}registerAll(e){for(let t of e)this.register(t)}resolve(e,t){let s=this.jobs.get(e);if(!s)throw new Error(`Job class "${e}" is not registered. Call Queue.register(${e}) in your app bootstrap. Registered jobs: [${[...this.jobs.keys()].join(", ")}]`);let r=Object.create(s.prototype);r.attempts=0,r.maxAttempts=3,r.retryDelay=60,r.queue="default";try{let i=JSON.parse(t);r.restore(i)}catch{}return r}has(e){return this.jobs.has(e)}},_s=class{config={default:"sync",connections:{sync:{driver:"sync"}}};drivers=new Map;processing=!1;jobRegistry=new Ls;failedStore=new Ds;_activeWorker=null;configure(e){this.config=e,this.drivers.clear()}register(e){this.jobRegistry.register(e)}registerAll(e){this.jobRegistry.registerAll(e)}async dispatch(e,t){let s=this.config.default,r=this.config.connections[s],i=this.resolveDriver(s);t?.queue&&(e.queue=t.queue),t?.maxAttempts!==void 0&&(e.maxAttempts=t.maxAttempts);let a={id:crypto.randomUUID(),jobClass:e.constructor.name,payload:e.serialize(),queue:e.queue??r?.queue??"default",attempts:0,maxAttempts:e.maxAttempts,availableAt:Date.now()+(t?.delay??0)*1e3,createdAt:Date.now(),job:e};await i.push(a)}async dispatchSync(e){let t=new Et,s={id:crypto.randomUUID(),jobClass:e.constructor.name,payload:e.serialize(),queue:e.queue,attempts:0,maxAttempts:e.maxAttempts,availableAt:Date.now(),createdAt:Date.now(),job:e};await t.push(s)}async chain(e,t){if(e.length===0)return;let s=new Ms(e);t?.queue&&(s.queue=t.queue),t?.maxAttempts!==void 0&&(s.maxAttempts=t.maxAttempts),await this.dispatch(s,t)}async work(e){let t=this.config.default,s=this.resolveDriver(t),r=e?.queue??"default";if(s instanceof $t){let l=await s.createWorker(r,this.jobRegistry,this.failedStore,{concurrency:e?.concurrency??1});return this.processing=!0,this._activeWorker=l,await new Promise(c=>{let m=()=>{this.processing?setTimeout(m,500):l.close().then(c).catch(c)};m()}),0}let i=e?.maxJobs??1/0,a=(e?.sleep??1)*1e3,n=0;for(this.processing=!0;this.processing&&n<i;){let l=await s.pop(r);if(!l){if(i===1/0){await new Promise(c=>setTimeout(c,a));continue}break}l.attempts++,l.job.attempts=l.attempts;try{await l.job.handle(),n++,s instanceof Z&&await s.delete(l.id)}catch(c){if(l.attempts<l.maxAttempts){l.job.retrying(l.attempts);let m=l.job.retryDelay??60;s instanceof Z?await s.release(l.id,m):(l.availableAt=Date.now()+m*1e3,await s.push(l))}else l.job.failed(c),await this.failedStore.store(l,c),s instanceof Z&&await s.delete(l.id)}}return n}async stop(){this.processing=!1,this._activeWorker&&(await this._activeWorker.close(),this._activeWorker=null)}async size(e){return this.resolveDriver(this.config.default).size(e)}async clear(e){return this.resolveDriver(this.config.default).clear(e)}async failed(){return this.failedStore.all()}async retry(e){let t=await this.failedStore.find(e);if(!t)return!1;let s=this.jobRegistry.resolve(t.jobClass,t.payload);return s.queue=t.queue,await this.dispatch(s,{queue:t.queue}),await this.failedStore.forget(e),!0}async retryAll(){let e=await this.failedStore.all(),t=0;for(let s of e)try{let r=this.jobRegistry.resolve(s.jobClass,s.payload);r.queue=s.queue,await this.dispatch(r,{queue:s.queue}),await this.failedStore.forget(s.id),t++}catch{}return t}async forgetFailed(e){return this.failedStore.forget(e)}async flushFailed(){return this.failedStore.flush()}resolveDriver(e){if(this.drivers.has(e))return this.drivers.get(e);let t=this.config.connections[e];if(!t)throw new Error(`Queue connection "${e}" is not defined.`);let s;switch(t.driver){case"sync":s=new Et;break;case"memory":s=new As;break;case"database":s=new Z(t.table??"svelar_jobs",this.jobRegistry);break;case"redis":s=new $t(t,this.jobRegistry);break;default:throw new Error(`Unknown queue driver: ${t.driver}`)}return this.drivers.set(e,s),s}},Ms=class extends X{remainingJobs;constructor(e){super(),this.remainingJobs=[...e],this.maxAttempts=1}async handle(){for(let e of this.remainingJobs){let t=null,s=!1;for(let r=1;r<=e.maxAttempts;r++){e.attempts=r;try{await e.handle(),s=!0;break}catch(i){t=i,r<e.maxAttempts&&(e.retrying(r),e.retryDelay>0&&await new Promise(a=>setTimeout(a,e.retryDelay*1e3)))}}if(!s&&t)throw e.failed(t),new Error(`Chain stopped: ${e.constructor.name} failed after ${e.maxAttempts} attempt(s). Remaining jobs: [${this.remainingJobs.slice(this.remainingJobs.indexOf(e)+1).map(r=>r.constructor.name).join(", ")}]`)}}serialize(){return JSON.stringify({jobs:this.remainingJobs.map(e=>({jobClass:e.constructor.name,payload:e.serialize()}))})}},Ns=S("svelar.queue",()=>new _s)});var j,Is=w(()=>{"use strict";P();j=class o{tableName;selectColumns=["*"];whereClauses=[];joinClauses=[];orderClauses=[];groupByColumns=[];havingClauses=[];limitValue=null;offsetValue=null;eagerLoads=[];isDistinct=!1;connectionName;cteClauses=[];unionClauses=[];modelClass;constructor(e,t,s){this.tableName=e,this.modelClass=t,this.connectionName=s}select(...e){return this.selectColumns=e.length>0?e:["*"],this}addSelect(...e){return this.selectColumns[0]==="*"?this.selectColumns=e:this.selectColumns.push(...e),this}distinct(){return this.isDistinct=!0,this}from(e){return this.tableName=e,this}where(e,t,s){return s===void 0?this.whereClauses.push({type:"basic",column:e,operator:"=",value:t,boolean:"AND"}):this.whereClauses.push({type:"basic",column:e,operator:t,value:s,boolean:"AND"}),this}orWhere(e,t,s){return s===void 0?this.whereClauses.push({type:"basic",column:e,operator:"=",value:t,boolean:"OR"}):this.whereClauses.push({type:"basic",column:e,operator:t,value:s,boolean:"OR"}),this}whereIn(e,t){return this.whereClauses.push({type:"in",column:e,values:t,boolean:"AND"}),this}whereNotIn(e,t){return this.whereClauses.push({type:"notIn",column:e,values:t,boolean:"AND"}),this}whereNull(e){return this.whereClauses.push({type:"null",column:e,boolean:"AND"}),this}whereNotNull(e){return this.whereClauses.push({type:"notNull",column:e,boolean:"AND"}),this}whereBetween(e,t){return this.whereClauses.push({type:"between",column:e,values:t,boolean:"AND"}),this}whereRaw(e,t=[]){return this.whereClauses.push({type:"raw",raw:e,values:t,boolean:"AND"}),this}whereNested(e,t="AND"){let s=new o(this.tableName,this.modelClass,this.connectionName);if(e(s),s.whereClauses.length>0){let{whereSQL:r,whereBindings:i}=s.buildWhere(),a=r.replace(/^WHERE /,"");this.whereClauses.push({type:"raw",raw:`(${a})`,values:i,boolean:t})}return this}orWhereNested(e){return this.whereNested(e,"OR")}whereExists(e){let t=new o("__placeholder__",void 0,this.connectionName);e(t);let{sql:s,bindings:r}=t.toSQL();return this.whereClauses.push({type:"exists",subSQL:s,subBindings:r,boolean:"AND"}),this}whereNotExists(e){let t=new o("__placeholder__",void 0,this.connectionName);e(t);let{sql:s,bindings:r}=t.toSQL();return this.whereClauses.push({type:"notExists",subSQL:s,subBindings:r,boolean:"AND"}),this}whereSub(e,t,s){let r=new o("__placeholder__",void 0,this.connectionName);s(r);let{sql:i,bindings:a}=r.toSQL();return this.whereClauses.push({type:"sub",column:e,operator:t,subSQL:i,subBindings:a,boolean:"AND"}),this}orWhereRaw(e,t=[]){return this.whereClauses.push({type:"raw",raw:e,values:t,boolean:"OR"}),this}orWhereIn(e,t){return this.whereClauses.push({type:"in",column:e,values:t,boolean:"OR"}),this}orWhereNull(e){return this.whereClauses.push({type:"null",column:e,boolean:"OR"}),this}orWhereNotNull(e){return this.whereClauses.push({type:"notNull",column:e,boolean:"OR"}),this}withCTE(e,t,s=!1){let r=new o("__placeholder__",void 0,this.connectionName);t(r);let{sql:i,bindings:a}=r.toSQL();return this.cteClauses.push({name:e,sql:i,bindings:a,recursive:s}),this}withRecursiveCTE(e,t){return this.withCTE(e,t,!0)}withRawCTE(e,t,s=[],r=!1){return this.cteClauses.push({name:e,sql:t,bindings:s,recursive:r}),this}union(e){let t=new o("__placeholder__",void 0,this.connectionName);e(t);let{sql:s,bindings:r}=t.toSQL();return this.unionClauses.push({sql:s,bindings:r,all:!1}),this}unionAll(e){let t=new o("__placeholder__",void 0,this.connectionName);e(t);let{sql:s,bindings:r}=t.toSQL();return this.unionClauses.push({sql:s,bindings:r,all:!0}),this}join(e,t,s,r){return this.joinClauses.push({type:"INNER",table:e,first:t,operator:s,second:r}),this}leftJoin(e,t,s,r){return this.joinClauses.push({type:"LEFT",table:e,first:t,operator:s,second:r}),this}rightJoin(e,t,s,r){return this.joinClauses.push({type:"RIGHT",table:e,first:t,operator:s,second:r}),this}crossJoin(e){return this.joinClauses.push({type:"CROSS",table:e,first:"",operator:"",second:""}),this}orderBy(e,t="asc"){return this.orderClauses.push({column:e,direction:t}),this}latest(e="created_at"){return this.orderBy(e,"desc")}oldest(e="created_at"){return this.orderBy(e,"asc")}groupBy(...e){return this.groupByColumns.push(...e),this}having(e,t,s){return this.havingClauses.push({type:"basic",column:e,operator:t,value:s,boolean:"AND"}),this}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}take(e){return this.limit(e)}skip(e){return this.offset(e)}with(...e){return this.eagerLoads.push(...e),this}async get(){let{sql:e,bindings:t}=this.toSQL(),s=await f.raw(e,t,this.connectionName),r=this.hydrateMany(s);return this.eagerLoads.length>0&&this.modelClass&&await this.loadRelations(r),r}async first(){return this.limitValue=1,(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new Error(`No results found for query on "${this.tableName}".`);return e}async find(e,t="id"){return this.where(t,e).first()}async findOrFail(e,t="id"){return this.where(t,e).firstOrFail()}async count(e="*"){let{sql:t,bindings:s}=this.buildAggregate(`COUNT(${e})`),r=await f.raw(t,s,this.connectionName);return Number(r[0]?.aggregate??0)}async sum(e){let{sql:t,bindings:s}=this.buildAggregate(`SUM(${e})`),r=await f.raw(t,s,this.connectionName);return Number(r[0]?.aggregate??0)}async avg(e){let{sql:t,bindings:s}=this.buildAggregate(`AVG(${e})`),r=await f.raw(t,s,this.connectionName);return Number(r[0]?.aggregate??0)}async max(e){let{sql:t,bindings:s}=this.buildAggregate(`MAX(${e})`);return(await f.raw(t,s,this.connectionName))[0]?.aggregate??null}async min(e){let{sql:t,bindings:s}=this.buildAggregate(`MIN(${e})`);return(await f.raw(t,s,this.connectionName))[0]?.aggregate??null}async exists(){return await this.count()>0}async doesntExist(){return!await this.exists()}async pluck(e){return this.selectColumns=[e],(await f.raw(this.toSQL().sql,this.toSQL().bindings,this.connectionName)).map(s=>s[e])}async value(e){return this.selectColumns=[e],this.limitValue=1,(await f.raw(this.toSQL().sql,this.toSQL().bindings,this.connectionName))[0]?.[e]??null}async chunk(e,t){let s=1,r=!0;for(;r;){let i=this.clone();i.limitValue=e,i.offsetValue=(s-1)*e;let a=await i.get();if(a.length===0||await t(a,s)===!1||a.length<e)break;s++}}when(e,t){return e&&t(this),this}selectRaw(e){return this.selectColumns[0]==="*"?this.selectColumns=[e]:this.selectColumns.push(e),this}async upsert(e,t,s){let r=f.getDriver(this.connectionName),i=Object.keys(e),a=Object.values(e),n=a.map(()=>"?").join(", "),l=s??i.filter(m=>!t.includes(m)),c;if(r==="postgres"){let m=l.map(p=>`${p} = EXCLUDED.${p}`).join(", ");c=`INSERT INTO ${this.tableName} (${i.join(", ")}) VALUES (${n}) ON CONFLICT (${t.join(", ")}) DO UPDATE SET ${m}`}else if(r==="mysql"){let m=l.map(p=>`${p} = VALUES(${p})`).join(", ");c=`INSERT INTO ${this.tableName} (${i.join(", ")}) VALUES (${n}) ON DUPLICATE KEY UPDATE ${m}`}else{let m=l.map(p=>`${p} = excluded.${p}`).join(", ");c=`INSERT INTO ${this.tableName} (${i.join(", ")}) VALUES (${n}) ON CONFLICT (${t.join(", ")}) DO UPDATE SET ${m}`}return f.raw(c,a,this.connectionName)}async insertMany(e){if(e.length===0)return;let t=Object.keys(e[0]),s=[],r=[];for(let a of e){let n=t.map(l=>a[l]);s.push(...n),r.push(`(${n.map(()=>"?").join(", ")})`)}let i=`INSERT INTO ${this.tableName} (${t.join(", ")}) VALUES ${r.join(", ")}`;return f.raw(i,s,this.connectionName)}async firstOrCreate(e,t={}){for(let[a,n]of Object.entries(e))this.where(a,n);let s=await this.first();if(s)return s;let r={...e,...t},i=await new o(this.tableName,this.modelClass,this.connectionName).insertGetId(r);return new o(this.tableName,this.modelClass,this.connectionName).findOrFail(i)}async updateOrCreate(e,t){let s=new o(this.tableName,this.modelClass,this.connectionName);for(let[n,l]of Object.entries(e))s.where(n,l);let r=await s.first();if(r)return await new o(this.tableName,this.modelClass,this.connectionName).where(this.modelClass?.primaryKey??"id",r[this.modelClass?.primaryKey??"id"]).update(t),new o(this.tableName,this.modelClass,this.connectionName).findOrFail(r[this.modelClass?.primaryKey??"id"]);let i={...e,...t},a=await new o(this.tableName,this.modelClass,this.connectionName).insertGetId(i);return new o(this.tableName,this.modelClass,this.connectionName).findOrFail(a)}whereColumn(e,t,s){return s===void 0?this.whereClauses.push({type:"raw",raw:`${e} = ${t}`,values:[],boolean:"AND"}):this.whereClauses.push({type:"raw",raw:`${e} ${t} ${s}`,values:[],boolean:"AND"}),this}havingRaw(e,t=[]){return this.havingClauses.push({type:"raw",raw:e,values:t,boolean:"AND"}),this}orderByRaw(e){return this.orderClauses.push({column:e,direction:"asc"}),this.orderClauses[this.orderClauses.length-1].__raw=!0,this}selectSub(e,t){let s=new o("__placeholder__",void 0,this.connectionName);e(s);let{sql:r,bindings:i}=s.toSQL(),a=`(${r}) as ${t}`;return this.selectColumns[0]==="*"?this.selectColumns=[a]:this.selectColumns.push(a),this._selectBindings||(this._selectBindings=[]),this._selectBindings.push(...i),this}_selectBindings;async truncate(){f.getDriver(this.connectionName)==="sqlite"?(await f.raw(`DELETE FROM ${this.tableName}`,[],this.connectionName),await f.raw("DELETE FROM sqlite_sequence WHERE name = ?",[this.tableName],this.connectionName)):await f.raw(`TRUNCATE TABLE ${this.tableName}`,[],this.connectionName)}async paginate(e=1,t=15){let s=await this.clone().count(),r=Math.ceil(s/t);return this.limitValue=t,this.offsetValue=(e-1)*t,{data:await this.get(),total:s,page:e,perPage:t,lastPage:r,hasMore:e<r}}async insert(e){let t=Object.keys(e),s=Object.values(e),r=s.map(()=>"?").join(", "),i=`INSERT INTO ${this.tableName} (${t.join(", ")}) VALUES (${r})`;return f.raw(i,s,this.connectionName)}async insertGetId(e,t="id"){let s=f.getDriver(this.connectionName),r=Object.keys(e),i=Object.values(e),a=i.map(()=>"?").join(", "),n=`INSERT INTO ${this.tableName} (${r.join(", ")}) VALUES (${a})`;return s==="postgres"?(n+=` RETURNING ${t}`,(await f.raw(n,i,this.connectionName))[0]?.[t]):(await f.raw(n,i,this.connectionName),s==="sqlite"?(await f.raw("SELECT last_insert_rowid() as id",[],this.connectionName))[0]?.id:s==="mysql"?(await f.raw("SELECT LAST_INSERT_ID() as id",[],this.connectionName))[0]?.id:0)}async update(e){let t=Object.keys(e),s=Object.values(e),r=t.map(l=>`${l} = ?`).join(", "),{whereSQL:i,whereBindings:a}=this.buildWhere(),n=`UPDATE ${this.tableName} SET ${r}${i}`;return await f.raw(n,[...s,...a],this.connectionName),1}async delete(){let{whereSQL:e,whereBindings:t}=this.buildWhere(),s=`DELETE FROM ${this.tableName}${e}`;return await f.raw(s,t,this.connectionName),1}async increment(e,t=1){let{whereSQL:s,whereBindings:r}=this.buildWhere(),i=`UPDATE ${this.tableName} SET ${e} = ${e} + ?${s}`;await f.raw(i,[t,...r],this.connectionName)}async decrement(e,t=1){return this.increment(e,-t)}toSQL(){let e=[],t=[];if(this.cteClauses.length>0){let n=this.cteClauses.some(c=>c.recursive)?"WITH RECURSIVE":"WITH",l=this.cteClauses.map(c=>(t.push(...c.bindings),`${c.name} AS (${c.sql})`));e.push(`${n} ${l.join(", ")}`)}this._selectBindings?.length&&t.push(...this._selectBindings);let s=this.isDistinct?"DISTINCT ":"";e.push(`SELECT ${s}${this.selectColumns.join(", ")}`),e.push(`FROM ${this.tableName}`);for(let a of this.joinClauses)a.type==="CROSS"?e.push(`CROSS JOIN ${a.table}`):e.push(`${a.type} JOIN ${a.table} ON ${a.first} ${a.operator} ${a.second}`);let{whereSQL:r,whereBindings:i}=this.buildWhere();if(r&&(e.push(r.trim()),t.push(...i)),this.groupByColumns.length>0&&e.push(`GROUP BY ${this.groupByColumns.join(", ")}`),this.havingClauses.length>0){let a=[];for(let n of this.havingClauses)n.type==="raw"?(a.push(n.raw),n.values&&t.push(...n.values)):(a.push(`${n.column} ${n.operator} ?`),t.push(n.value));e.push(`HAVING ${a.join(" AND ")}`)}if(this.orderClauses.length>0){let a=this.orderClauses.map(n=>n.__raw?n.column:`${n.column} ${n.direction.toUpperCase()}`);e.push(`ORDER BY ${a.join(", ")}`)}if(this.limitValue!==null&&e.push(`LIMIT ${this.limitValue}`),this.offsetValue!==null&&e.push(`OFFSET ${this.offsetValue}`),this.unionClauses.length>0)for(let a of this.unionClauses)e.push(a.all?"UNION ALL":"UNION"),e.push(a.sql),t.push(...a.bindings);return{sql:e.join(" "),bindings:t}}clone(){let e=new o(this.tableName,this.modelClass,this.connectionName);return e.selectColumns=[...this.selectColumns],e.whereClauses=[...this.whereClauses],e.joinClauses=[...this.joinClauses],e.orderClauses=[...this.orderClauses],e.groupByColumns=[...this.groupByColumns],e.havingClauses=[...this.havingClauses],e.limitValue=this.limitValue,e.offsetValue=this.offsetValue,e.eagerLoads=[...this.eagerLoads],e.isDistinct=this.isDistinct,e.cteClauses=[...this.cteClauses],e.unionClauses=[...this.unionClauses],e}buildWhere(){if(this.whereClauses.length===0)return{whereSQL:"",whereBindings:[]};let e=[],t=[];for(let s=0;s<this.whereClauses.length;s++){let r=this.whereClauses[s],i=s===0?"WHERE":r.boolean;switch(r.type){case"basic":if((r.operator==="IS"||r.operator==="IS NOT")&&r.value===null){let l=(r.operator==="IS","null");e.push(`${i} ${r.column} ${r.operator} ${l}`)}else e.push(`${i} ${r.column} ${r.operator} ?`),t.push(r.value);break;case"in":let a=r.values.map(()=>"?").join(", ");e.push(`${i} ${r.column} IN (${a})`),t.push(...r.values);break;case"notIn":let n=r.values.map(()=>"?").join(", ");e.push(`${i} ${r.column} NOT IN (${n})`),t.push(...r.values);break;case"null":e.push(`${i} ${r.column} IS NULL`);break;case"notNull":e.push(`${i} ${r.column} IS NOT NULL`);break;case"between":e.push(`${i} ${r.column} BETWEEN ? AND ?`),t.push(r.values[0],r.values[1]);break;case"raw":e.push(`${i} ${r.raw}`),r.values&&t.push(...r.values);break;case"exists":e.push(`${i} EXISTS (${r.subSQL})`),r.subBindings&&t.push(...r.subBindings);break;case"notExists":e.push(`${i} NOT EXISTS (${r.subSQL})`),r.subBindings&&t.push(...r.subBindings);break;case"sub":e.push(`${i} ${r.column} ${r.operator} (${r.subSQL})`),r.subBindings&&t.push(...r.subBindings);break}}return{whereSQL:e.join(" "),whereBindings:t}}buildAggregate(e){let t=this.selectColumns;this.selectColumns=[`${e} as aggregate`];let s=this.toSQL();return this.selectColumns=t,s}hydrateMany(e){return this.modelClass?e.map(t=>this.modelClass.hydrate(t)):e}async loadRelations(e){if(!(!this.modelClass||e.length===0))for(let t of this.eagerLoads){let r=new this.modelClass()[t]?.();r&&typeof r.eagerLoad=="function"&&await r.eagerLoad(e,t)}}}});var te,se,re,ie,ae,js=w(()=>{"use strict";P();te=class{parentModel;relatedModel;constructor(e,t){this.parentModel=e,this.relatedModel=t}query(){return this.relatedModel.query()}},se=class extends te{constructor(t,s,r,i="id"){super(t,s);this.foreignKey=r;this.localKey=i}async load(t){let s=t.getAttribute(this.localKey);return this.relatedModel.query().where(this.foreignKey,s).first()}async eagerLoad(t,s){let r=t.map(n=>n.getAttribute(this.localKey)),i=await this.relatedModel.query().whereIn(this.foreignKey,r).get(),a=new Map;for(let n of i)a.set(n.getAttribute(this.foreignKey),n);for(let n of t){let l=n.getAttribute(this.localKey);n.setRelation(s,a.get(l)??null)}}async create(t){let s=this.parentModel.getAttribute(this.localKey);return this.relatedModel.create({...t,[this.foreignKey]:s})}},re=class extends te{constructor(t,s,r,i="id"){super(t,s);this.foreignKey=r;this.localKey=i}async load(t){let s=t.getAttribute(this.localKey);return this.relatedModel.query().where(this.foreignKey,s).get()}async eagerLoad(t,s){let r=t.map(n=>n.getAttribute(this.localKey)),i=await this.relatedModel.query().whereIn(this.foreignKey,r).get(),a=new Map;for(let n of i){let l=n.getAttribute(this.foreignKey);a.has(l)||a.set(l,[]),a.get(l).push(n)}for(let n of t){let l=n.getAttribute(this.localKey);n.setRelation(s,a.get(l)??[])}}async create(t){let s=this.parentModel.getAttribute(this.localKey);return this.relatedModel.create({...t,[this.foreignKey]:s})}async createMany(t){let s=[];for(let r of t)s.push(await this.create(r));return s}},ie=class extends te{constructor(t,s,r,i="id"){super(t,s);this.foreignKey=r;this.ownerKey=i}async load(t){let s=t.getAttribute(this.foreignKey);return s==null?null:this.relatedModel.query().where(this.ownerKey,s).first()}async eagerLoad(t,s){let r=t.map(n=>n.getAttribute(this.foreignKey)).filter(n=>n!=null);if(r.length===0){for(let n of t)n.setRelation(s,null);return}let i=await this.relatedModel.query().whereIn(this.ownerKey,r).get(),a=new Map;for(let n of i)a.set(n.getAttribute(this.ownerKey),n);for(let n of t){let l=n.getAttribute(this.foreignKey);n.setRelation(s,a.get(l)??null)}}associate(t){return this.parentModel.setAttribute(this.foreignKey,t.getAttribute(this.ownerKey)),this.parentModel}dissociate(){return this.parentModel.setAttribute(this.foreignKey,null),this.parentModel}},ae=class extends te{constructor(t,s,r,i,a,n="id",l="id"){super(t,s);this.pivotTable=r;this.foreignPivotKey=i;this.relatedPivotKey=a;this.parentKey=n;this.relatedKey=l}async load(t){let s=t.getAttribute(this.parentKey),r=this.relatedModel.tableName,a=(await f.raw(`SELECT ${this.relatedPivotKey} FROM ${this.pivotTable} WHERE ${this.foreignPivotKey} = ?`,[s])).map(n=>n[this.relatedPivotKey]);return a.length===0?[]:this.relatedModel.query().whereIn(this.relatedKey,a).get()}async eagerLoad(t,s){let r=t.map(p=>p.getAttribute(this.parentKey));if(r.length===0){for(let p of t)p.setRelation(s,[]);return}let i=r.map(()=>"?").join(", "),a=await f.raw(`SELECT * FROM ${this.pivotTable} WHERE ${this.foreignPivotKey} IN (${i})`,r),n=[...new Set(a.map(p=>p[this.relatedPivotKey]))],l=n.length>0?await this.relatedModel.query().whereIn(this.relatedKey,n).get():[],c=new Map;for(let p of l)c.set(p.getAttribute(this.relatedKey),p);let m=new Map;for(let p of a){let h=p[this.foreignPivotKey],u=p[this.relatedPivotKey],b=c.get(u);b&&(m.has(h)||m.set(h,[]),m.get(h).push(b))}for(let p of t){let h=p.getAttribute(this.parentKey);p.setRelation(s,m.get(h)??[])}}async attach(t,s){let r=this.parentModel.getAttribute(this.parentKey),i={[this.foreignPivotKey]:r,[this.relatedPivotKey]:t,...s},a=Object.keys(i),n=Object.values(i),l=n.map(()=>"?").join(", ");await f.raw(`INSERT INTO ${this.pivotTable} (${a.join(", ")}) VALUES (${l})`,n)}async detach(t){let s=this.parentModel.getAttribute(this.parentKey);t?await f.raw(`DELETE FROM ${this.pivotTable} WHERE ${this.foreignPivotKey} = ? AND ${this.relatedPivotKey} = ?`,[s,t]):await f.raw(`DELETE FROM ${this.pivotTable} WHERE ${this.foreignPivotKey} = ?`,[s])}async sync(t){await this.detach();for(let s of t)await this.attach(s)}async toggle(t){let s=this.parentModel.getAttribute(this.parentKey);for(let r of t)(await f.raw(`SELECT 1 FROM ${this.pivotTable} WHERE ${this.foreignPivotKey} = ? AND ${this.relatedPivotKey} = ? LIMIT 1`,[s,r])).length>0?await this.detach(r):await this.attach(r)}}});var ii=w(()=>{"use strict"});var _e,Os=w(()=>{"use strict";_e=class{app;constructor(e){this.app=e}boot(){}}});var ai=w(()=>{"use strict";Os();Mt()});var Me,ne,Mt=w(()=>{"use strict";E();ii();ai();Me=class{listeners=new Map;wildcardListeners=[];onceListeners=new Map;listen(e,t){let s=typeof e=="string"?e:e.name;return this.listeners.has(s)||this.listeners.set(s,[]),this.listeners.get(s).push(t),()=>{let r=this.listeners.get(s);if(r){let i=r.indexOf(t);i>=0&&r.splice(i,1)}}}once(e,t){let s=typeof e=="string"?e:e.name;return this.onceListeners.has(s)||this.onceListeners.set(s,[]),this.onceListeners.get(s).push(t),()=>{let r=this.onceListeners.get(s);if(r){let i=r.indexOf(t);i>=0&&r.splice(i,1)}}}onAny(e){return this.wildcardListeners.push(e),()=>{let t=this.wildcardListeners.indexOf(e);t>=0&&this.wildcardListeners.splice(t,1)}}async dispatch(e){let t=e.constructor.name,s=this.listeners.get(t)??[];for(let i of s)await i(e);let r=this.onceListeners.get(t)??[];for(let i of r)await i(e);this.onceListeners.delete(t);for(let i of this.wildcardListeners)await i(t,e)}async emit(e,t){let s=this.listeners.get(e)??[];for(let i of s)await i(t);let r=this.onceListeners.get(e)??[];for(let i of r)await i(t);this.onceListeners.delete(e);for(let i of this.wildcardListeners)await i(e,t)}subscribe(e){e.subscribe(this)}forget(e){let t=typeof e=="string"?e:e.name;this.listeners.delete(t),this.onceListeners.delete(t)}flush(){this.listeners.clear(),this.onceListeners.clear(),this.wildcardListeners=[]}hasListeners(e){let t=typeof e=="string"?e:e.name;return(this.listeners.get(t)?.length??0)>0||(this.onceListeners.get(t)?.length??0)>0||this.wildcardListeners.length>0}listenerCount(e){let t=typeof e=="string"?e:e.name;return(this.listeners.get(t)?.length??0)+(this.onceListeners.get(t)?.length??0)}},ne=S("svelar.event",()=>new Me)});var Nt,ni=w(()=>{"use strict";Is();js();Mt();Nt=class o{static table;static primaryKey="id";static incrementing=!0;static timestamps=!0;static createdAt="created_at";static updatedAt="updated_at";static casts={};static fillable=[];static hidden=[];static connection=void 0;static hooks=new Map;static observers=new Map;static events=[];attributes={};originalAttributes={};relations={};exists=!1;constructor(e){return e&&this.fill(e),new Proxy(this,{get(t,s,r){return typeof s=="symbol"||s in t||typeof s!="string"||["table","primaryKey","incrementing","timestamps","casts","fillable","hidden","connection"].includes(s)?Reflect.get(t,s,r):typeof t[s]=="function"?t[s].bind(t):t.getAttribute(s)},set(t,s,r){return typeof s=="symbol"||s in t?Reflect.set(t,s,r):(t.setAttribute(s,r),!0)}})}static query(){let e=new this,t=this;return new j(t.table,this,t.connection)}static async find(e){let t=this;return this.query().find(e,t.primaryKey)}static async findOrFail(e){let t=this;return this.query().findOrFail(e,t.primaryKey)}static async all(){return this.query().get()}static async first(){return this.query().first()}static async firstOrFail(){return this.query().firstOrFail()}static where(e,t,s){return this.query().where(e,t,s)}static whereIn(e,t){return this.query().whereIn(e,t)}static whereNull(e){return this.query().whereNull(e)}static whereNotNull(e){return this.query().whereNotNull(e)}static orderBy(e,t){return this.query().orderBy(e,t)}static latest(e){return this.query().latest(e)}static oldest(e){return this.query().oldest(e)}static with(...e){return this.query().with(...e)}static async count(){return this.query().count()}static async create(e){let t=new this,s=this;if(t.fill(e),await t.fireHook("creating"),await t.fireHook("saving"),s.timestamps){let n=new Date().toISOString();t.setAttribute(s.createdAt,n),t.setAttribute(s.updatedAt,n)}let r=t.getInsertableAttributes(),a=await new j(s.table,this,s.connection).insertGetId(r,s.primaryKey);return s.incrementing&&a&&t.setAttribute(s.primaryKey,a),t.syncOriginal(),t.exists=!0,await t.fireHook("created"),await t.fireHook("saved"),t}async save(){let e=this.constructor;if(this.exists){await this.fireHook("updating"),await this.fireHook("saving"),e.timestamps&&this.setAttribute(e.updatedAt,new Date().toISOString());let t=this.getDirty();if(Object.keys(t).length>0){let s=this.getAttribute(e.primaryKey);await new j(e.table,this.constructor,e.connection).where(e.primaryKey,s).update(t)}this.syncOriginal(),await this.fireHook("updated"),await this.fireHook("saved")}else{if(await this.fireHook("creating"),await this.fireHook("saving"),e.timestamps){let i=new Date().toISOString();this.getAttribute(e.createdAt)||this.setAttribute(e.createdAt,i),this.setAttribute(e.updatedAt,i)}let t=this.getInsertableAttributes(),r=await new j(e.table,this.constructor,e.connection).insertGetId(t,e.primaryKey);e.incrementing&&r&&this.setAttribute(e.primaryKey,r),this.syncOriginal(),this.exists=!0,await this.fireHook("created"),await this.fireHook("saved")}}async update(e){this.fill(e),await this.save()}async delete(){let e=this.constructor;await this.fireHook("deleting");let t=this.getAttribute(e.primaryKey);await new j(e.table,this.constructor,e.connection).where(e.primaryKey,t).delete(),this.exists=!1,await this.fireHook("deleted")}async refresh(){let e=this.constructor,t=this.getAttribute(e.primaryKey),s=await this.constructor.find(t);s&&(this.attributes={...s.attributes},this.syncOriginal())}getAttribute(e){let t=this.constructor,s=this.attributes[e],r=t.casts[e];if(r&&s!==void 0&&s!==null)switch(r){case"number":return Number(s);case"boolean":return!!s;case"string":return String(s);case"date":return new Date(s);case"json":return typeof s=="string"?JSON.parse(s):s}return s}setAttribute(e,t){this.constructor.casts[e]==="json"&&typeof t!="string"?this.attributes[e]=JSON.stringify(t):this.attributes[e]=t}fill(e){let t=this.constructor;for(let[s,r]of Object.entries(e))t.fillable.length>0&&!t.fillable.includes(s)||this.setAttribute(s,r)}getAttributes(){return{...this.attributes}}getOriginal(e){return e?this.originalAttributes[e]:{...this.originalAttributes}}getDirty(){let e={};for(let[t,s]of Object.entries(this.attributes))s!==this.originalAttributes[t]&&(e[t]=s);return e}isDirty(...e){let t=this.getDirty();return e.length===0?Object.keys(t).length>0:e.some(s=>s in t)}isClean(...e){return!this.isDirty(...e)}wasChanged(...e){return this.isDirty(...e)}hasOne(e,t,s){return new se(this,e,t,s??this.constructor.primaryKey)}hasMany(e,t,s){return new re(this,e,t,s??this.constructor.primaryKey)}belongsTo(e,t,s){return new ie(this,e,t,s??e.primaryKey)}belongsToMany(e,t,s,r,i,a){return new ae(this,e,t,s,r,i??this.constructor.primaryKey,a??e.primaryKey)}setRelation(e,t){this.relations[e]=t}getRelation(e){return this.relations[e]}relationLoaded(e){return e in this.relations}toJSON(){let e=this.constructor,t={};for(let[s,r]of Object.entries(this.attributes))e.hidden.includes(s)||(t[s]=this.getAttribute(s));for(let[s,r]of Object.entries(this.relations))Array.isArray(r)?t[s]=r.map(i=>i instanceof o?i.toJSON():i):r instanceof o?t[s]=r.toJSON():t[s]=r;return t}toObject(){return this.toJSON()}static hydrate(e){let t=new this;return t.attributes={...e},t.syncOriginal(),t.exists=!0,t}static boot(e){this.hooks.set(this.name,e)}static observe(e){let t=this.observers.get(this.name)??[];t.push(e),this.observers.set(this.name,t)}static removeObservers(){this.observers.delete(this.name)}async fireHook(e){let t=this.constructor,s=o.hooks.get(t.name);s?.[e]&&await s[e](this),typeof this[e]=="function"&&await this[e]();let r=o.observers.get(t.name)??[];for(let a of r){let n=a[e];typeof n=="function"&&await n.call(a,this)}let i=t.name.toLowerCase();await ne.emit(`${i}.${e}`,this)}async fireEvent(e){let t=this.constructor;if(!t.events.includes(e))throw new Error(`Event "${e}" is not declared in ${t.name}.events. Add it to: static events = ['${e}', ...];`);let s=o.observers.get(t.name)??[];for(let i of s){let a=i[e];typeof a=="function"&&await a.call(i,this)}let r=t.name.toLowerCase();await ne.emit(`${r}.${e}`,this)}syncOriginal(){this.originalAttributes={...this.attributes}}getInsertableAttributes(){let e=this.constructor,t={...this.attributes};return e.incrementing&&t[e.primaryKey]===void 0&&delete t[e.primaryKey],t}static get tableName(){return this.table}}});var It,oi=w(()=>{"use strict";It=class{async call(e){await new e().run()}}});var J,li,qs=w(()=>{"use strict";E();J=class{bindings=new Map;aliases=new Map;resolved=new Set;bind(e,t){this.bindings.set(e,{factory:t,singleton:!1,tags:[]})}singleton(e,t){this.bindings.set(e,{factory:t,singleton:!0,tags:[]})}instance(e,t){this.bindings.set(e,{factory:()=>t,singleton:!0,instance:t,tags:[]})}alias(e,t){this.aliases.set(e,t)}async make(e){let t=this.resolveAlias(e),s=this.bindings.get(t);if(!s)throw new Error(`No binding found for "${e}" in the container.`);if(s.singleton&&s.instance!==void 0)return s.instance;let r=await s.factory(this);return s.singleton&&(s.instance=r),this.resolved.add(t),r}makeSync(e){let t=this.resolveAlias(e),s=this.bindings.get(t);if(!s)throw new Error(`No binding found for "${e}" in the container.`);if(s.singleton&&s.instance!==void 0)return s.instance;let r=s.factory(this);if(r instanceof Promise)throw new Error(`Binding "${e}" has an async factory. Use container.make() instead of container.makeSync().`);return s.singleton&&(s.instance=r),this.resolved.add(t),r}has(e){let t=this.resolveAlias(e);return this.bindings.has(t)}isResolved(e){return this.resolved.has(this.resolveAlias(e))}tag(e,t){for(let s of e){let r=this.bindings.get(s);r&&r.tags.push(t)}}async tagged(e){let t=[];for(let[s,r]of this.bindings)r.tags.includes(e)&&t.push(await this.make(s));return t}flush(){for(let e of this.bindings.values())e.singleton&&(e.instance=void 0);this.resolved.clear()}forget(e){this.bindings.delete(e),this.resolved.delete(e)}getBindings(){return[...this.bindings.keys()]}resolveAlias(e){return this.aliases.get(e)??e}},li=S("svelar.container",()=>new J)});var jt,ci=w(()=>{"use strict";qs();jt=class{container;providers=[];booted=!1;constructor(e){this.container=e??new J,this.container.instance("app",this),this.container.instance("container",this.container)}register(e){let t=new e(this.container);return this.providers.push(t),this}async bootstrap(){if(this.booted)return this;for(let e of this.providers)await e.register();for(let e of this.providers)await e.boot();return this.booted=!0,this}isBooted(){return this.booted}async make(e){return this.container.make(e)}getProviders(){return[...this.providers]}}});var $,H,Ot,oe,qt,le,ce,Ut,de,ue=w(()=>{"use strict";$=class{},H=class{middleware=[];namedMiddleware=new Map;use(e){return typeof e=="function"&&"prototype"in e&&typeof e.prototype?.handle=="function"?this.middleware.push(new e):this.middleware.push(e),this}register(e,t){return typeof t=="function"&&"prototype"in t&&typeof t.prototype?.handle=="function"?this.namedMiddleware.set(e,new t):this.namedMiddleware.set(e,t),this}get(e){return this.namedMiddleware.get(e)}async execute(e,t,s){let r=[...this.middleware];if(s)for(let a of s){let n=this.namedMiddleware.get(a);n&&r.push(n)}let i=t;for(let a=r.length-1;a>=0;a--){let n=r[a],l=i;typeof n.handle=="function"?i=()=>n.handle(e,l):i=()=>n(e,l)}return i()}count(){return this.middleware.length}},Ot=class extends ${constructor(t={}){super();this.options=t}async handle(t,s){let r=await s();if(!r)return;let i=Array.isArray(this.options.origin)?this.options.origin.join(", "):this.options.origin??"*";return r.headers.set("Access-Control-Allow-Origin",i),r.headers.set("Access-Control-Allow-Methods",(this.options.methods??["GET","POST","PUT","DELETE","PATCH","OPTIONS"]).join(", ")),r.headers.set("Access-Control-Allow-Headers",(this.options.headers??["Content-Type","Authorization"]).join(", ")),this.options.credentials&&r.headers.set("Access-Control-Allow-Credentials","true"),this.options.maxAge&&r.headers.set("Access-Control-Max-Age",String(this.options.maxAge)),t.event.request.method==="OPTIONS"?new Response(null,{status:204,headers:r.headers}):r}},oe=class extends ${requests=new Map;maxRequests;windowMs;constructor(e={}){super(),this.maxRequests=e.maxRequests??60,this.windowMs=e.windowMs??6e4}async handle(e,t){let s=e.event.request.headers.get("x-forwarded-for")??e.event.getClientAddress?.()??"unknown",r=Date.now(),i=this.requests.get(s);if(i&&r<i.resetAt){if(i.count>=this.maxRequests)return new Response(JSON.stringify({error:"Too many requests"}),{status:429,headers:{"Content-Type":"application/json","Retry-After":String(Math.ceil((i.resetAt-r)/1e3))}});i.count++}else this.requests.set(s,{count:1,resetAt:r+this.windowMs});return t()}},qt=class extends ${async handle(e,t){let s=Date.now(),r=e.event.request.method,i=e.event.url.pathname,a=await t(),n=Date.now()-s,l=a instanceof Response?a.status:200;return console.log(`[${new Date().toISOString()}] ${r} ${i} \u2192 ${l} (${n}ms)`),a}},le=class extends ${cookieName;headerName;fieldName;excludePaths;onlyPaths;constructor(e={}){super(),this.cookieName=e.cookieName??"XSRF-TOKEN",this.headerName=e.headerName??"X-CSRF-Token",this.fieldName=e.fieldName??"_csrf",this.excludePaths=e.excludePaths??[],this.onlyPaths=e.onlyPaths??null}async handle(e,t){let{event:s}=e,r=s.request.method.toUpperCase();if(["GET","HEAD","OPTIONS"].includes(r))return this.setTokenAndContinue(e,t);if((s.request.headers.get("authorization")??"").startsWith("Bearer "))return t();let a=s.url.pathname;if(this.onlyPaths&&!this.onlyPaths.some(c=>a.startsWith(c)))return this.setTokenAndContinue(e,t);if(this.excludePaths.some(c=>a.startsWith(c)))return t();let n=this.getCookieToken(s),l=s.request.headers.get(this.headerName)??await this.getBodyToken(s);return!n||!l||!this.timingSafeEqual(n,l)?new Response(JSON.stringify({message:"CSRF token mismatch"}),{status:419,headers:{"Content-Type":"application/json"}}):t()}async setTokenAndContinue(e,t){let s=await t();if(!(s instanceof Response))return s;let i=this.getCookieToken(e.event)||this.generateToken();return s.headers.append("Set-Cookie",`${this.cookieName}=${i}; Path=/; SameSite=Lax`),s}getCookieToken(e){let s=(e.request.headers.get("cookie")??"").match(new RegExp(`${this.cookieName}=([^;]+)`));return s?s[1]:null}async getBodyToken(e){try{let t=e.request.headers.get("content-type")??"";if(t.includes("application/x-www-form-urlencoded")||t.includes("multipart/form-data"))return(await e.request.clone().formData()).get(this.fieldName);if(t.includes("application/json"))return(await e.request.clone().json())[this.fieldName]??null}catch{}return null}generateToken(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let s=new TextEncoder,r=s.encode(e),i=s.encode(t),a=0;for(let n=0;n<r.length;n++)a|=r[n]^i[n];return a===0}},ce=class extends ${allowedOrigins;constructor(e={}){super(),this.allowedOrigins=new Set(e.allowedOrigins??[])}async handle(e,t){let{event:s}=e,r=s.request.method.toUpperCase();if(["GET","HEAD","OPTIONS"].includes(r)||(s.request.headers.get("authorization")??"").startsWith("Bearer "))return t();let a=s.request.headers.get("origin");if(!a)return t();let n=s.url.origin;return a===n||this.allowedOrigins.has(a)?t():new Response(JSON.stringify({message:"Cross-origin request blocked"}),{status:403,headers:{"Content-Type":"application/json"}})}},Ut=class extends ${secret;tolerance;signatureHeader;timestampHeader;onlyPaths;constructor(e){super(),this.secret=e.secret,this.tolerance=e.tolerance??300,this.signatureHeader=e.signatureHeader??"X-Signature",this.timestampHeader=e.timestampHeader??"X-Timestamp",this.onlyPaths=e.onlyPaths??null}async handle(e,t){let{event:s}=e;if(this.onlyPaths){let y=s.url.pathname;if(!this.onlyPaths.some(v=>y.startsWith(v)))return t()}let r=s.request.headers.get(this.signatureHeader),i=s.request.headers.get(this.timestampHeader);if(!r||!i)return new Response(JSON.stringify({message:"Missing request signature"}),{status:401,headers:{"Content-Type":"application/json"}});let a=parseInt(i,10),n=Math.floor(Date.now()/1e3);if(isNaN(a)||Math.abs(n-a)>this.tolerance)return new Response(JSON.stringify({message:"Request signature expired"}),{status:401,headers:{"Content-Type":"application/json"}});let c=await s.request.clone().text(),{createHmac:m}=await import("crypto"),p=s.request.method.toUpperCase(),h=s.url.pathname+s.url.search,u=`${i}.${p}.${h}.${c}`,b=m("sha256",this.secret).update(u).digest("hex");return r.length!==b.length||!this.timingSafeCompare(r,b)?new Response(JSON.stringify({message:"Invalid request signature"}),{status:401,headers:{"Content-Type":"application/json"}}):t()}timingSafeCompare(e,t){if(e.length!==t.length)return!1;let s=new TextEncoder,r=s.encode(e),i=s.encode(t),a=0;for(let n=0;n<r.length;n++)a|=r[n]^i[n];return a===0}static sign(e,t,s,r,i){let{createHmac:a}=Qe("crypto"),n=i??Math.floor(Date.now()/1e3),l=`${n}.${t.toUpperCase()}.${s}.${r}`;return{signature:a("sha256",e).update(l).digest("hex"),timestamp:n}}},de=class extends ${attempts=new Map;maxAttempts;decayMinutes;constructor(e={}){super(),this.maxAttempts=e.maxAttempts??5,this.decayMinutes=e.decayMinutes??1}async handle(e,t){let r=`${e.event.request.headers.get("x-forwarded-for")??e.event.getClientAddress?.()??"unknown"}:${e.event.url.pathname}`,i=Date.now(),a=this.attempts.get(r);if(a){if(i<a.blockedUntil){let l=Math.ceil((a.blockedUntil-i)/1e3);return new Response(JSON.stringify({message:"Too many attempts. Please try again later.",retry_after:l}),{status:429,headers:{"Content-Type":"application/json","Retry-After":String(l)}})}if(a.count>=this.maxAttempts){a.blockedUntil=i+this.decayMinutes*6e4,a.count=0;let l=this.decayMinutes*60;return new Response(JSON.stringify({message:"Too many attempts. Please try again later.",retry_after:l}),{status:429,headers:{"Content-Type":"application/json","Retry-After":String(l)}})}}let n=await t();if(n instanceof Response&&n.status>=400&&n.status<500){let l=this.attempts.get(r)??{count:0,blockedUntil:0};if(l.count++,this.attempts.set(r,l),this.attempts.size>1e4)for(let[c,m]of this.attempts)i>m.blockedUntil+this.decayMinutes*6e4*2&&this.attempts.delete(c)}return n}}});import{z as me}from"zod";function di(o,e=!1){let t=new o;return e?{GET:t.handle("show"),PUT:t.handle("update"),PATCH:t.handle("update"),DELETE:t.handle("destroy")}:{GET:t.handle("index"),POST:t.handle("store")}}var Ft,z,Ne,Ie,je,ui=w(()=>{"use strict";ue();Ft=class{controllerMiddleware=[];middleware(e,t){let s;typeof e=="function"&&e.prototype instanceof $?s=new e:s=e,this.controllerMiddleware.push({middleware:s,only:t?.only,except:t?.except})}handle(e){return async t=>{try{let s=this.controllerMiddleware.filter(r=>!(r.only&&!r.only.includes(e)||r.except&&r.except.includes(e)));if(s.length>0){let r=new H;for(let{middleware:n}of s)r.use(n);let i={event:t,params:t.params,locals:t.locals},a=await r.execute(i,async()=>this.callMethod(e,t));if(a instanceof Response)return a}return await this.callMethod(e,t)}catch(s){return this.handleError(s,t)}}}json(e,t=200,s={}){let r=JSON.stringify(e,null,2);return new Response(r,{status:t,headers:{"Content-Type":"application/json",...s}})}text(e,t=200){return new Response(e,{status:t,headers:{"Content-Type":"text/plain"}})}html(e,t=200){return new Response(e,{status:t,headers:{"Content-Type":"text/html"}})}redirect(e,t=302){return new Response(null,{status:t,headers:{Location:e}})}noContent(){return new Response(null,{status:204})}created(e){return e?this.json(e,201):new Response(null,{status:201})}async validate(e,t){let s=t instanceof me.ZodObject?t:me.object(t),r,i=e.request.headers.get("content-type")??"";if(i.includes("application/json"))r=await e.request.json();else if(i.includes("multipart/form-data")||i.includes("application/x-www-form-urlencoded")){let n=await e.request.formData();r=Object.fromEntries(n)}else r=Object.fromEntries(e.url.searchParams);let a=s.safeParse(r);if(!a.success)throw new z(a.error);return a.data}validateQuery(e,t){let s=t instanceof me.ZodObject?t:me.object(t),r=Object.fromEntries(e.url.searchParams),i=s.safeParse(r);if(!i.success)throw new z(i.error);return i.data}validateParams(e,t){let r=(t instanceof me.ZodObject?t:me.object(t)).safeParse(e.params);if(!r.success)throw new z(r.error);return r.data}handleError(e,t){return e instanceof z?this.json({message:"Validation failed",errors:e.errors},422):e instanceof Ne?this.json({message:e.message||"Not found"},404):e instanceof Ie?this.json({message:e.message||"Unauthorized"},401):e instanceof je?this.json({message:e.message||"Forbidden"},403):(console.error("[Svelar] Controller error:",e),this.json({message:process.env.NODE_ENV==="production"?"Internal server error":e.message},500))}async callMethod(e,t){let s=this[e];if(typeof s!="function")throw new Error(`Method "${e}" not found on controller "${this.constructor.name}".`);let r=await s.call(this,t);return r instanceof Response?r:this.json(r)}};z=class extends Error{errors;constructor(e){super("Validation failed"),this.name="ValidationError",this.errors={};for(let t of e.issues){let s=t.path.join(".");this.errors[s]||(this.errors[s]=[]),this.errors[s].push(t.message)}}},Ne=class extends Error{constructor(e="Not found"){super(e),this.name="NotFoundError"}},Ie=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}},je=class extends Error{constructor(e="Forbidden"){super(e),this.name="ForbiddenError"}}});import{randomBytes as Xn,createHmac as mi,timingSafeEqual as eo}from"crypto";import{promises as K}from"fs";import{join as Oe}from"path";var pe,qe,V,Bt,Ht,zt,he,Us=w(()=>{"use strict";ue();pe=class o{constructor(e,t){this.id=e;t&&(this.data={...t},this.data._flash&&(this.previousFlashData=this.data._flash,delete this.data._flash))}data={};dirty=!1;flashData={};previousFlashData={};get(e,t){return e in this.flashData?this.flashData[e]:e in this.previousFlashData?this.previousFlashData[e]:e in this.data?this.data[e]:t}set(e,t){this.data[e]=t,this.dirty=!0}has(e){return e in this.data||e in this.flashData||e in this.previousFlashData}forget(e){delete this.data[e],this.dirty=!0}flush(){this.data={},this.dirty=!0}flash(e,t){this.flashData[e]=t,this.dirty=!0}all(){return{...this.data,...this.previousFlashData,...this.flashData}}isDirty(){return this.dirty||Object.keys(this.flashData).length>0}toPersist(){let e={...this.data};return Object.keys(this.flashData).length>0&&(e._flash=this.flashData),e}regenerateId(){let e=this.id,t=o.generateId();this.id=t,this.dirty=!0;let s=qe.get(e);return s instanceof V&&s.markOldSessionId(e),qe.delete(e),t}static generateId(){return Xn(32).toString("hex")}},qe=new Map,V=class{sessions=new Map;oldSessionIds=new Set;async read(e){if(this.oldSessionIds.has(e))return null;let t=this.sessions.get(e);return t?Date.now()>t.expiresAt?(this.sessions.delete(e),null):t.data:null}async write(e,t,s){this.sessions.set(e,{data:t,expiresAt:Date.now()+s*1e3}),qe.set(e,this)}async destroy(e){this.sessions.delete(e),qe.delete(e)}async gc(e){let t=Date.now();for(let[s,r]of this.sessions)t>r.expiresAt&&(this.sessions.delete(s),qe.delete(s))}markOldSessionId(e){this.oldSessionIds.add(e),this.sessions.delete(e)}},Bt=class{constructor(e="sessions",t){this.tableName=e;this.connectionName=t}tableEnsured=!1;async ensureTable(){if(!this.tableEnsured)try{let{Connection:e}=await Promise.resolve().then(()=>(P(),R));switch(e.getDriver(this.connectionName)){case"sqlite":await e.raw(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
41
+ ORDER BY created_at ASC LIMIT 1`,[e,s]);if(!r||r.length===0)return null;let i=r[0];await t.raw(`UPDATE ${this.table} SET reserved_at = ?, attempts = attempts + 1 WHERE id = ?`,[s,i.id]);let a=JSON.parse(i.payload),n=this.registry.resolve(a.jobClass,a.payload);return{id:i.id,jobClass:a.jobClass,payload:a.payload,queue:i.queue,attempts:i.attempts+1,maxAttempts:i.max_attempts,availableAt:i.available_at*1e3,createdAt:i.created_at*1e3,job:n}}async size(e="default"){return(await(await this.getConnection()).raw(`SELECT COUNT(*) as count FROM ${this.table} WHERE queue = ? AND reserved_at IS NULL`,[e]))?.[0]?.count??0}async clear(e){let t=await this.getConnection();e?await t.raw(`DELETE FROM ${this.table} WHERE queue = ?`,[e]):await t.raw(`DELETE FROM ${this.table}`,[])}async delete(e){await(await this.getConnection()).raw(`DELETE FROM ${this.table} WHERE id = ?`,[e])}async release(e,t=0){let s=await this.getConnection(),r=Math.floor(Date.now()/1e3)+t;await s.raw(`UPDATE ${this.table} SET reserved_at = NULL, available_at = ? WHERE id = ?`,[r,e])}},Dt=class{queues=new Map;config;registry;_bullmq=null;constructor(e,t){this.config=e,this.registry=t}async getBullMQ(){if(this._bullmq)return this._bullmq;try{return this._bullmq=await Function('return import("bullmq")')(),this._bullmq}catch{throw new Error("bullmq is required for the Redis queue driver. Install it with: npm install bullmq")}}getRedisConnection(){if(this.config.url){let e=new URL(this.config.url);return{host:e.hostname||"localhost",port:parseInt(e.port)||6379,password:e.password||this.config.password||void 0,db:parseInt(e.pathname?.slice(1)||"0")||this.config.db||0}}return{host:this.config.host??"localhost",port:this.config.port??6379,password:this.config.password,db:this.config.db??0}}async getQueue(e){if(this.queues.has(e))return this.queues.get(e);let t=await this.getBullMQ(),s=this.getRedisConnection(),r=this.config.prefix??"svelar",i=new t.Queue(e,{connection:s,prefix:r,defaultJobOptions:{removeOnComplete:this.config.defaultJobOptions?.removeOnComplete??100,removeOnFail:this.config.defaultJobOptions?.removeOnFail??500}});return this.queues.set(e,i),i}async push(e){let t=await this.getQueue(e.queue),s=Math.max(0,e.availableAt-Date.now());await t.add(e.jobClass,{jobClass:e.jobClass,payload:e.payload},{jobId:e.id,delay:s>0?s:void 0,attempts:e.maxAttempts,backoff:{type:"fixed",delay:(e.job.retryDelay??60)*1e3}})}async pop(e){return null}async size(e="default"){let s=await(await this.getQueue(e)).getJobCounts("waiting","delayed","active");return s.waiting+s.delayed+s.active}async clear(e){if(e)await(await this.getQueue(e)).obliterate({force:!0});else for(let t of this.queues.values())await t.obliterate({force:!0})}async createWorker(e,t,s,r){let i=await this.getBullMQ(),a=this.getRedisConnection(),n=this.config.prefix??"svelar",l=new i.Worker(e,async c=>{let m=c.data,p=t.resolve(m.jobClass,m.payload);p.attempts=c.attemptsMade+1,await p.handle()},{connection:a,prefix:n,concurrency:r?.concurrency??1});return l.on("failed",async(c,m)=>{let p=c?.data;if(p)try{let h=t.resolve(p.jobClass,p.payload);c.attemptsMade>=(c.opts?.attempts??3)&&(h.failed(m),await s.store({id:c.id,jobClass:p.jobClass,payload:p.payload,queue:e,attempts:c.attemptsMade,maxAttempts:c.opts?.attempts??3,availableAt:Date.now(),createdAt:c.timestamp??Date.now(),job:h},m))}catch{console.error("[Queue] Failed to resolve job for failure handler:",m.message)}}),l}},_s=class{table="svelar_failed_jobs";async getConnection(){let{Connection:e}=await Promise.resolve().then(()=>(S(),R));return e}async store(e,t){try{await(await this.getConnection()).raw(`INSERT INTO ${this.table} (id, queue, job_class, payload, exception, failed_at)
42
+ VALUES (?, ?, ?, ?, ?, ?)`,[crypto.randomUUID(),e.queue,e.jobClass,e.payload,t.stack??t.message,Math.floor(Date.now()/1e3)])}catch{console.error("[Queue] Could not persist failed job (run migration to create svelar_failed_jobs table)")}}async all(){return(await(await this.getConnection()).raw(`SELECT * FROM ${this.table} ORDER BY failed_at DESC`,[])??[]).map(s=>({id:s.id,queue:s.queue,jobClass:s.job_class,payload:s.payload,exception:s.exception,failedAt:s.failed_at}))}async find(e){let s=await(await this.getConnection()).raw(`SELECT * FROM ${this.table} WHERE id = ? LIMIT 1`,[e]);if(!s||s.length===0)return null;let r=s[0];return{id:r.id,queue:r.queue,jobClass:r.job_class,payload:r.payload,exception:r.exception,failedAt:r.failed_at}}async forget(e){return await(await this.getConnection()).raw(`DELETE FROM ${this.table} WHERE id = ?`,[e]),!0}async flush(){let e=await this.getConnection(),s=(await e.raw(`SELECT COUNT(*) as count FROM ${this.table}`,[]))?.[0]?.count??0;return await e.raw(`DELETE FROM ${this.table}`,[]),s}},Ms=class{jobs=new Map;register(e){this.jobs.set(e.name,e)}registerAll(e){for(let t of e)this.register(t)}resolve(e,t){let s=this.jobs.get(e);if(!s)throw new Error(`Job class "${e}" is not registered. Call Queue.register(${e}) in your app bootstrap. Registered jobs: [${[...this.jobs.keys()].join(", ")}]`);let r=Object.create(s.prototype);r.attempts=0,r.maxAttempts=3,r.retryDelay=60,r.queue="default";try{let i=JSON.parse(t);r.restore(i)}catch{}return r}has(e){return this.jobs.has(e)}},Ns=class{config={default:"sync",connections:{sync:{driver:"sync"}}};drivers=new Map;processing=!1;jobRegistry=new Ms;failedStore=new _s;_activeWorker=null;configure(e){this.config=e,this.drivers.clear()}register(e){this.jobRegistry.register(e)}registerAll(e){this.jobRegistry.registerAll(e)}async dispatch(e,t){let s=this.config.default,r=this.config.connections[s],i=this.resolveDriver(s);t?.queue&&(e.queue=t.queue),t?.maxAttempts!==void 0&&(e.maxAttempts=t.maxAttempts);let a={id:crypto.randomUUID(),jobClass:e.constructor.name,payload:e.serialize(),queue:e.queue??r?.queue??"default",attempts:0,maxAttempts:e.maxAttempts,availableAt:Date.now()+(t?.delay??0)*1e3,createdAt:Date.now(),job:e};await i.push(a)}async dispatchSync(e){let t=new At,s={id:crypto.randomUUID(),jobClass:e.constructor.name,payload:e.serialize(),queue:e.queue,attempts:0,maxAttempts:e.maxAttempts,availableAt:Date.now(),createdAt:Date.now(),job:e};await t.push(s)}async chain(e,t){if(e.length===0)return;let s=new Is(e);t?.queue&&(s.queue=t.queue),t?.maxAttempts!==void 0&&(s.maxAttempts=t.maxAttempts),await this.dispatch(s,t)}async work(e){let t=this.config.default,s=this.resolveDriver(t),r=e?.queue??"default";if(s instanceof Dt){let l=await s.createWorker(r,this.jobRegistry,this.failedStore,{concurrency:e?.concurrency??1});return this.processing=!0,this._activeWorker=l,await new Promise(c=>{let m=()=>{this.processing?setTimeout(m,500):l.close().then(c).catch(c)};m()}),0}let i=e?.maxJobs??1/0,a=(e?.sleep??1)*1e3,n=0;for(this.processing=!0;this.processing&&n<i;){let l=await s.pop(r);if(!l){if(i===1/0){await new Promise(c=>setTimeout(c,a));continue}break}l.attempts++,l.job.attempts=l.attempts;try{await l.job.handle(),n++,s instanceof Z&&await s.delete(l.id)}catch(c){if(l.attempts<l.maxAttempts){l.job.retrying(l.attempts);let m=l.job.retryDelay??60;s instanceof Z?await s.release(l.id,m):(l.availableAt=Date.now()+m*1e3,await s.push(l))}else l.job.failed(c),await this.failedStore.store(l,c),s instanceof Z&&await s.delete(l.id)}}return n}async stop(){this.processing=!1,this._activeWorker&&(await this._activeWorker.close(),this._activeWorker=null)}async size(e){return this.resolveDriver(this.config.default).size(e)}async clear(e){return this.resolveDriver(this.config.default).clear(e)}async failed(){return this.failedStore.all()}async retry(e){let t=await this.failedStore.find(e);if(!t)return!1;let s=this.jobRegistry.resolve(t.jobClass,t.payload);return s.queue=t.queue,await this.dispatch(s,{queue:t.queue}),await this.failedStore.forget(e),!0}async retryAll(){let e=await this.failedStore.all(),t=0;for(let s of e)try{let r=this.jobRegistry.resolve(s.jobClass,s.payload);r.queue=s.queue,await this.dispatch(r,{queue:s.queue}),await this.failedStore.forget(s.id),t++}catch{}return t}async forgetFailed(e){return this.failedStore.forget(e)}async flushFailed(){return this.failedStore.flush()}resolveDriver(e){if(this.drivers.has(e))return this.drivers.get(e);let t=this.config.connections[e];if(!t)throw new Error(`Queue connection "${e}" is not defined.`);let s;switch(t.driver){case"sync":s=new At;break;case"memory":s=new Ls;break;case"database":s=new Z(t.table??"svelar_jobs",this.jobRegistry);break;case"redis":s=new Dt(t,this.jobRegistry);break;default:throw new Error(`Unknown queue driver: ${t.driver}`)}return this.drivers.set(e,s),s}},Is=class extends X{remainingJobs;constructor(e){super(),this.remainingJobs=[...e],this.maxAttempts=1}async handle(){for(let e of this.remainingJobs){let t=null,s=!1;for(let r=1;r<=e.maxAttempts;r++){e.attempts=r;try{await e.handle(),s=!0;break}catch(i){t=i,r<e.maxAttempts&&(e.retrying(r),e.retryDelay>0&&await new Promise(a=>setTimeout(a,e.retryDelay*1e3)))}}if(!s&&t)throw e.failed(t),new Error(`Chain stopped: ${e.constructor.name} failed after ${e.maxAttempts} attempt(s). Remaining jobs: [${this.remainingJobs.slice(this.remainingJobs.indexOf(e)+1).map(r=>r.constructor.name).join(", ")}]`)}}serialize(){return JSON.stringify({jobs:this.remainingJobs.map(e=>({jobClass:e.constructor.name,payload:e.serialize()}))})}},js=P("svelar.queue",()=>new Ns)});var j,Os=C(()=>{"use strict";S();j=class o{tableName;selectColumns=["*"];whereClauses=[];joinClauses=[];orderClauses=[];groupByColumns=[];havingClauses=[];limitValue=null;offsetValue=null;eagerLoads=[];isDistinct=!1;connectionName;cteClauses=[];unionClauses=[];modelClass;constructor(e,t,s){this.tableName=e,this.modelClass=t,this.connectionName=s}select(...e){return this.selectColumns=e.length>0?e:["*"],this}addSelect(...e){return this.selectColumns[0]==="*"?this.selectColumns=e:this.selectColumns.push(...e),this}distinct(){return this.isDistinct=!0,this}from(e){return this.tableName=e,this}where(e,t,s){return s===void 0?this.whereClauses.push({type:"basic",column:e,operator:"=",value:t,boolean:"AND"}):this.whereClauses.push({type:"basic",column:e,operator:t,value:s,boolean:"AND"}),this}orWhere(e,t,s){return s===void 0?this.whereClauses.push({type:"basic",column:e,operator:"=",value:t,boolean:"OR"}):this.whereClauses.push({type:"basic",column:e,operator:t,value:s,boolean:"OR"}),this}whereIn(e,t){return this.whereClauses.push({type:"in",column:e,values:t,boolean:"AND"}),this}whereNotIn(e,t){return this.whereClauses.push({type:"notIn",column:e,values:t,boolean:"AND"}),this}whereNull(e){return this.whereClauses.push({type:"null",column:e,boolean:"AND"}),this}whereNotNull(e){return this.whereClauses.push({type:"notNull",column:e,boolean:"AND"}),this}whereBetween(e,t){return this.whereClauses.push({type:"between",column:e,values:t,boolean:"AND"}),this}whereRaw(e,t=[]){return this.whereClauses.push({type:"raw",raw:e,values:t,boolean:"AND"}),this}whereNested(e,t="AND"){let s=new o(this.tableName,this.modelClass,this.connectionName);if(e(s),s.whereClauses.length>0){let{whereSQL:r,whereBindings:i}=s.buildWhere(),a=r.replace(/^WHERE /,"");this.whereClauses.push({type:"raw",raw:`(${a})`,values:i,boolean:t})}return this}orWhereNested(e){return this.whereNested(e,"OR")}whereExists(e){let t=new o("__placeholder__",void 0,this.connectionName);e(t);let{sql:s,bindings:r}=t.toSQL();return this.whereClauses.push({type:"exists",subSQL:s,subBindings:r,boolean:"AND"}),this}whereNotExists(e){let t=new o("__placeholder__",void 0,this.connectionName);e(t);let{sql:s,bindings:r}=t.toSQL();return this.whereClauses.push({type:"notExists",subSQL:s,subBindings:r,boolean:"AND"}),this}whereSub(e,t,s){let r=new o("__placeholder__",void 0,this.connectionName);s(r);let{sql:i,bindings:a}=r.toSQL();return this.whereClauses.push({type:"sub",column:e,operator:t,subSQL:i,subBindings:a,boolean:"AND"}),this}orWhereRaw(e,t=[]){return this.whereClauses.push({type:"raw",raw:e,values:t,boolean:"OR"}),this}orWhereIn(e,t){return this.whereClauses.push({type:"in",column:e,values:t,boolean:"OR"}),this}orWhereNull(e){return this.whereClauses.push({type:"null",column:e,boolean:"OR"}),this}orWhereNotNull(e){return this.whereClauses.push({type:"notNull",column:e,boolean:"OR"}),this}withCTE(e,t,s=!1){let r=new o("__placeholder__",void 0,this.connectionName);t(r);let{sql:i,bindings:a}=r.toSQL();return this.cteClauses.push({name:e,sql:i,bindings:a,recursive:s}),this}withRecursiveCTE(e,t){return this.withCTE(e,t,!0)}withRawCTE(e,t,s=[],r=!1){return this.cteClauses.push({name:e,sql:t,bindings:s,recursive:r}),this}union(e){let t=new o("__placeholder__",void 0,this.connectionName);e(t);let{sql:s,bindings:r}=t.toSQL();return this.unionClauses.push({sql:s,bindings:r,all:!1}),this}unionAll(e){let t=new o("__placeholder__",void 0,this.connectionName);e(t);let{sql:s,bindings:r}=t.toSQL();return this.unionClauses.push({sql:s,bindings:r,all:!0}),this}join(e,t,s,r){return this.joinClauses.push({type:"INNER",table:e,first:t,operator:s,second:r}),this}leftJoin(e,t,s,r){return this.joinClauses.push({type:"LEFT",table:e,first:t,operator:s,second:r}),this}rightJoin(e,t,s,r){return this.joinClauses.push({type:"RIGHT",table:e,first:t,operator:s,second:r}),this}crossJoin(e){return this.joinClauses.push({type:"CROSS",table:e,first:"",operator:"",second:""}),this}orderBy(e,t="asc"){return this.orderClauses.push({column:e,direction:t}),this}latest(e="created_at"){return this.orderBy(e,"desc")}oldest(e="created_at"){return this.orderBy(e,"asc")}groupBy(...e){return this.groupByColumns.push(...e),this}having(e,t,s){return this.havingClauses.push({type:"basic",column:e,operator:t,value:s,boolean:"AND"}),this}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}take(e){return this.limit(e)}skip(e){return this.offset(e)}with(...e){return this.eagerLoads.push(...e),this}async get(){let{sql:e,bindings:t}=this.toSQL(),s=await f.raw(e,t,this.connectionName),r=this.hydrateMany(s);return this.eagerLoads.length>0&&this.modelClass&&await this.loadRelations(r),r}async first(){return this.limitValue=1,(await this.get())[0]??null}async firstOrFail(){let e=await this.first();if(!e)throw new Error(`No results found for query on "${this.tableName}".`);return e}async find(e,t="id"){return this.where(t,e).first()}async findOrFail(e,t="id"){return this.where(t,e).firstOrFail()}async count(e="*"){let{sql:t,bindings:s}=this.buildAggregate(`COUNT(${e})`),r=await f.raw(t,s,this.connectionName);return Number(r[0]?.aggregate??0)}async sum(e){let{sql:t,bindings:s}=this.buildAggregate(`SUM(${e})`),r=await f.raw(t,s,this.connectionName);return Number(r[0]?.aggregate??0)}async avg(e){let{sql:t,bindings:s}=this.buildAggregate(`AVG(${e})`),r=await f.raw(t,s,this.connectionName);return Number(r[0]?.aggregate??0)}async max(e){let{sql:t,bindings:s}=this.buildAggregate(`MAX(${e})`);return(await f.raw(t,s,this.connectionName))[0]?.aggregate??null}async min(e){let{sql:t,bindings:s}=this.buildAggregate(`MIN(${e})`);return(await f.raw(t,s,this.connectionName))[0]?.aggregate??null}async exists(){return await this.count()>0}async doesntExist(){return!await this.exists()}async pluck(e){return this.selectColumns=[e],(await f.raw(this.toSQL().sql,this.toSQL().bindings,this.connectionName)).map(s=>s[e])}async value(e){return this.selectColumns=[e],this.limitValue=1,(await f.raw(this.toSQL().sql,this.toSQL().bindings,this.connectionName))[0]?.[e]??null}async chunk(e,t){let s=1,r=!0;for(;r;){let i=this.clone();i.limitValue=e,i.offsetValue=(s-1)*e;let a=await i.get();if(a.length===0||await t(a,s)===!1||a.length<e)break;s++}}when(e,t){return e&&t(this),this}selectRaw(e){return this.selectColumns[0]==="*"?this.selectColumns=[e]:this.selectColumns.push(e),this}async upsert(e,t,s){let r=f.getDriver(this.connectionName),i=Object.keys(e),a=Object.values(e),n=a.map(()=>"?").join(", "),l=s??i.filter(m=>!t.includes(m)),c;if(r==="postgres"){let m=l.map(p=>`${p} = EXCLUDED.${p}`).join(", ");c=`INSERT INTO ${this.tableName} (${i.join(", ")}) VALUES (${n}) ON CONFLICT (${t.join(", ")}) DO UPDATE SET ${m}`}else if(r==="mysql"){let m=l.map(p=>`${p} = VALUES(${p})`).join(", ");c=`INSERT INTO ${this.tableName} (${i.join(", ")}) VALUES (${n}) ON DUPLICATE KEY UPDATE ${m}`}else{let m=l.map(p=>`${p} = excluded.${p}`).join(", ");c=`INSERT INTO ${this.tableName} (${i.join(", ")}) VALUES (${n}) ON CONFLICT (${t.join(", ")}) DO UPDATE SET ${m}`}return f.raw(c,a,this.connectionName)}async insertMany(e){if(e.length===0)return;let t=Object.keys(e[0]),s=[],r=[];for(let a of e){let n=t.map(l=>a[l]);s.push(...n),r.push(`(${n.map(()=>"?").join(", ")})`)}let i=`INSERT INTO ${this.tableName} (${t.join(", ")}) VALUES ${r.join(", ")}`;return f.raw(i,s,this.connectionName)}async firstOrCreate(e,t={}){for(let[a,n]of Object.entries(e))this.where(a,n);let s=await this.first();if(s)return s;let r={...e,...t},i=await new o(this.tableName,this.modelClass,this.connectionName).insertGetId(r);return new o(this.tableName,this.modelClass,this.connectionName).findOrFail(i)}async updateOrCreate(e,t){let s=new o(this.tableName,this.modelClass,this.connectionName);for(let[n,l]of Object.entries(e))s.where(n,l);let r=await s.first();if(r)return await new o(this.tableName,this.modelClass,this.connectionName).where(this.modelClass?.primaryKey??"id",r[this.modelClass?.primaryKey??"id"]).update(t),new o(this.tableName,this.modelClass,this.connectionName).findOrFail(r[this.modelClass?.primaryKey??"id"]);let i={...e,...t},a=await new o(this.tableName,this.modelClass,this.connectionName).insertGetId(i);return new o(this.tableName,this.modelClass,this.connectionName).findOrFail(a)}whereColumn(e,t,s){return s===void 0?this.whereClauses.push({type:"raw",raw:`${e} = ${t}`,values:[],boolean:"AND"}):this.whereClauses.push({type:"raw",raw:`${e} ${t} ${s}`,values:[],boolean:"AND"}),this}havingRaw(e,t=[]){return this.havingClauses.push({type:"raw",raw:e,values:t,boolean:"AND"}),this}orderByRaw(e){return this.orderClauses.push({column:e,direction:"asc"}),this.orderClauses[this.orderClauses.length-1].__raw=!0,this}selectSub(e,t){let s=new o("__placeholder__",void 0,this.connectionName);e(s);let{sql:r,bindings:i}=s.toSQL(),a=`(${r}) as ${t}`;return this.selectColumns[0]==="*"?this.selectColumns=[a]:this.selectColumns.push(a),this._selectBindings||(this._selectBindings=[]),this._selectBindings.push(...i),this}_selectBindings;async truncate(){f.getDriver(this.connectionName)==="sqlite"?(await f.raw(`DELETE FROM ${this.tableName}`,[],this.connectionName),await f.raw("DELETE FROM sqlite_sequence WHERE name = ?",[this.tableName],this.connectionName)):await f.raw(`TRUNCATE TABLE ${this.tableName}`,[],this.connectionName)}async paginate(e=1,t=15){let s=await this.clone().count(),r=Math.ceil(s/t);return this.limitValue=t,this.offsetValue=(e-1)*t,{data:await this.get(),total:s,page:e,perPage:t,lastPage:r,hasMore:e<r}}async insert(e){let t=Object.keys(e),s=Object.values(e),r=s.map(()=>"?").join(", "),i=`INSERT INTO ${this.tableName} (${t.join(", ")}) VALUES (${r})`;return f.raw(i,s,this.connectionName)}async insertGetId(e,t="id"){let s=f.getDriver(this.connectionName),r=Object.keys(e),i=Object.values(e),a=i.map(()=>"?").join(", "),n=`INSERT INTO ${this.tableName} (${r.join(", ")}) VALUES (${a})`;return s==="postgres"?(n+=` RETURNING ${t}`,(await f.raw(n,i,this.connectionName))[0]?.[t]):(await f.raw(n,i,this.connectionName),s==="sqlite"?(await f.raw("SELECT last_insert_rowid() as id",[],this.connectionName))[0]?.id:s==="mysql"?(await f.raw("SELECT LAST_INSERT_ID() as id",[],this.connectionName))[0]?.id:0)}async update(e){let t=Object.keys(e),s=Object.values(e),r=t.map(l=>`${l} = ?`).join(", "),{whereSQL:i,whereBindings:a}=this.buildWhere(),n=`UPDATE ${this.tableName} SET ${r}${i}`;return await f.raw(n,[...s,...a],this.connectionName),1}async delete(){let{whereSQL:e,whereBindings:t}=this.buildWhere(),s=`DELETE FROM ${this.tableName}${e}`;return await f.raw(s,t,this.connectionName),1}async increment(e,t=1){let{whereSQL:s,whereBindings:r}=this.buildWhere(),i=`UPDATE ${this.tableName} SET ${e} = ${e} + ?${s}`;await f.raw(i,[t,...r],this.connectionName)}async decrement(e,t=1){return this.increment(e,-t)}toSQL(){let e=[],t=[];if(this.cteClauses.length>0){let n=this.cteClauses.some(c=>c.recursive)?"WITH RECURSIVE":"WITH",l=this.cteClauses.map(c=>(t.push(...c.bindings),`${c.name} AS (${c.sql})`));e.push(`${n} ${l.join(", ")}`)}this._selectBindings?.length&&t.push(...this._selectBindings);let s=this.isDistinct?"DISTINCT ":"";e.push(`SELECT ${s}${this.selectColumns.join(", ")}`),e.push(`FROM ${this.tableName}`);for(let a of this.joinClauses)a.type==="CROSS"?e.push(`CROSS JOIN ${a.table}`):e.push(`${a.type} JOIN ${a.table} ON ${a.first} ${a.operator} ${a.second}`);let{whereSQL:r,whereBindings:i}=this.buildWhere();if(r&&(e.push(r.trim()),t.push(...i)),this.groupByColumns.length>0&&e.push(`GROUP BY ${this.groupByColumns.join(", ")}`),this.havingClauses.length>0){let a=[];for(let n of this.havingClauses)n.type==="raw"?(a.push(n.raw),n.values&&t.push(...n.values)):(a.push(`${n.column} ${n.operator} ?`),t.push(n.value));e.push(`HAVING ${a.join(" AND ")}`)}if(this.orderClauses.length>0){let a=this.orderClauses.map(n=>n.__raw?n.column:`${n.column} ${n.direction.toUpperCase()}`);e.push(`ORDER BY ${a.join(", ")}`)}if(this.limitValue!==null&&e.push(`LIMIT ${this.limitValue}`),this.offsetValue!==null&&e.push(`OFFSET ${this.offsetValue}`),this.unionClauses.length>0)for(let a of this.unionClauses)e.push(a.all?"UNION ALL":"UNION"),e.push(a.sql),t.push(...a.bindings);return{sql:e.join(" "),bindings:t}}clone(){let e=new o(this.tableName,this.modelClass,this.connectionName);return e.selectColumns=[...this.selectColumns],e.whereClauses=[...this.whereClauses],e.joinClauses=[...this.joinClauses],e.orderClauses=[...this.orderClauses],e.groupByColumns=[...this.groupByColumns],e.havingClauses=[...this.havingClauses],e.limitValue=this.limitValue,e.offsetValue=this.offsetValue,e.eagerLoads=[...this.eagerLoads],e.isDistinct=this.isDistinct,e.cteClauses=[...this.cteClauses],e.unionClauses=[...this.unionClauses],e}buildWhere(){if(this.whereClauses.length===0)return{whereSQL:"",whereBindings:[]};let e=[],t=[];for(let s=0;s<this.whereClauses.length;s++){let r=this.whereClauses[s],i=s===0?"WHERE":r.boolean;switch(r.type){case"basic":if((r.operator==="IS"||r.operator==="IS NOT")&&r.value===null){let l=(r.operator==="IS","null");e.push(`${i} ${r.column} ${r.operator} ${l}`)}else e.push(`${i} ${r.column} ${r.operator} ?`),t.push(r.value);break;case"in":let a=r.values.map(()=>"?").join(", ");e.push(`${i} ${r.column} IN (${a})`),t.push(...r.values);break;case"notIn":let n=r.values.map(()=>"?").join(", ");e.push(`${i} ${r.column} NOT IN (${n})`),t.push(...r.values);break;case"null":e.push(`${i} ${r.column} IS NULL`);break;case"notNull":e.push(`${i} ${r.column} IS NOT NULL`);break;case"between":e.push(`${i} ${r.column} BETWEEN ? AND ?`),t.push(r.values[0],r.values[1]);break;case"raw":e.push(`${i} ${r.raw}`),r.values&&t.push(...r.values);break;case"exists":e.push(`${i} EXISTS (${r.subSQL})`),r.subBindings&&t.push(...r.subBindings);break;case"notExists":e.push(`${i} NOT EXISTS (${r.subSQL})`),r.subBindings&&t.push(...r.subBindings);break;case"sub":e.push(`${i} ${r.column} ${r.operator} (${r.subSQL})`),r.subBindings&&t.push(...r.subBindings);break}}return{whereSQL:e.join(" "),whereBindings:t}}buildAggregate(e){let t=this.selectColumns;this.selectColumns=[`${e} as aggregate`];let s=this.toSQL();return this.selectColumns=t,s}hydrateMany(e){return this.modelClass?e.map(t=>this.modelClass.hydrate(t)):e}async loadRelations(e){if(!(!this.modelClass||e.length===0))for(let t of this.eagerLoads){let r=new this.modelClass()[t]?.();r&&typeof r.eagerLoad=="function"&&await r.eagerLoad(e,t)}}}});var te,se,re,ie,ae,qs=C(()=>{"use strict";S();te=class{parentModel;relatedModel;constructor(e,t){this.parentModel=e,this.relatedModel=t}query(){return this.relatedModel.query()}},se=class extends te{constructor(t,s,r,i="id"){super(t,s);this.foreignKey=r;this.localKey=i}async load(t){let s=t.getAttribute(this.localKey);return this.relatedModel.query().where(this.foreignKey,s).first()}async eagerLoad(t,s){let r=t.map(n=>n.getAttribute(this.localKey)),i=await this.relatedModel.query().whereIn(this.foreignKey,r).get(),a=new Map;for(let n of i)a.set(n.getAttribute(this.foreignKey),n);for(let n of t){let l=n.getAttribute(this.localKey);n.setRelation(s,a.get(l)??null)}}async create(t){let s=this.parentModel.getAttribute(this.localKey);return this.relatedModel.create({...t,[this.foreignKey]:s})}},re=class extends te{constructor(t,s,r,i="id"){super(t,s);this.foreignKey=r;this.localKey=i}async load(t){let s=t.getAttribute(this.localKey);return this.relatedModel.query().where(this.foreignKey,s).get()}async eagerLoad(t,s){let r=t.map(n=>n.getAttribute(this.localKey)),i=await this.relatedModel.query().whereIn(this.foreignKey,r).get(),a=new Map;for(let n of i){let l=n.getAttribute(this.foreignKey);a.has(l)||a.set(l,[]),a.get(l).push(n)}for(let n of t){let l=n.getAttribute(this.localKey);n.setRelation(s,a.get(l)??[])}}async create(t){let s=this.parentModel.getAttribute(this.localKey);return this.relatedModel.create({...t,[this.foreignKey]:s})}async createMany(t){let s=[];for(let r of t)s.push(await this.create(r));return s}},ie=class extends te{constructor(t,s,r,i="id"){super(t,s);this.foreignKey=r;this.ownerKey=i}async load(t){let s=t.getAttribute(this.foreignKey);return s==null?null:this.relatedModel.query().where(this.ownerKey,s).first()}async eagerLoad(t,s){let r=t.map(n=>n.getAttribute(this.foreignKey)).filter(n=>n!=null);if(r.length===0){for(let n of t)n.setRelation(s,null);return}let i=await this.relatedModel.query().whereIn(this.ownerKey,r).get(),a=new Map;for(let n of i)a.set(n.getAttribute(this.ownerKey),n);for(let n of t){let l=n.getAttribute(this.foreignKey);n.setRelation(s,a.get(l)??null)}}associate(t){return this.parentModel.setAttribute(this.foreignKey,t.getAttribute(this.ownerKey)),this.parentModel}dissociate(){return this.parentModel.setAttribute(this.foreignKey,null),this.parentModel}},ae=class extends te{constructor(t,s,r,i,a,n="id",l="id"){super(t,s);this.pivotTable=r;this.foreignPivotKey=i;this.relatedPivotKey=a;this.parentKey=n;this.relatedKey=l}async load(t){let s=t.getAttribute(this.parentKey),r=this.relatedModel.tableName,a=(await f.raw(`SELECT ${this.relatedPivotKey} FROM ${this.pivotTable} WHERE ${this.foreignPivotKey} = ?`,[s])).map(n=>n[this.relatedPivotKey]);return a.length===0?[]:this.relatedModel.query().whereIn(this.relatedKey,a).get()}async eagerLoad(t,s){let r=t.map(p=>p.getAttribute(this.parentKey));if(r.length===0){for(let p of t)p.setRelation(s,[]);return}let i=r.map(()=>"?").join(", "),a=await f.raw(`SELECT * FROM ${this.pivotTable} WHERE ${this.foreignPivotKey} IN (${i})`,r),n=[...new Set(a.map(p=>p[this.relatedPivotKey]))],l=n.length>0?await this.relatedModel.query().whereIn(this.relatedKey,n).get():[],c=new Map;for(let p of l)c.set(p.getAttribute(this.relatedKey),p);let m=new Map;for(let p of a){let h=p[this.foreignPivotKey],u=p[this.relatedPivotKey],b=c.get(u);b&&(m.has(h)||m.set(h,[]),m.get(h).push(b))}for(let p of t){let h=p.getAttribute(this.parentKey);p.setRelation(s,m.get(h)??[])}}async attach(t,s){let r=this.parentModel.getAttribute(this.parentKey),i={[this.foreignPivotKey]:r,[this.relatedPivotKey]:t,...s},a=Object.keys(i),n=Object.values(i),l=n.map(()=>"?").join(", ");await f.raw(`INSERT INTO ${this.pivotTable} (${a.join(", ")}) VALUES (${l})`,n)}async detach(t){let s=this.parentModel.getAttribute(this.parentKey);t?await f.raw(`DELETE FROM ${this.pivotTable} WHERE ${this.foreignPivotKey} = ? AND ${this.relatedPivotKey} = ?`,[s,t]):await f.raw(`DELETE FROM ${this.pivotTable} WHERE ${this.foreignPivotKey} = ?`,[s])}async sync(t){await this.detach();for(let s of t)await this.attach(s)}async toggle(t){let s=this.parentModel.getAttribute(this.parentKey);for(let r of t)(await f.raw(`SELECT 1 FROM ${this.pivotTable} WHERE ${this.foreignPivotKey} = ? AND ${this.relatedPivotKey} = ? LIMIT 1`,[s,r])).length>0?await this.detach(r):await this.attach(r)}}});var li=C(()=>{"use strict"});var _e,Us=C(()=>{"use strict";_e=class{app;constructor(e){this.app=e}boot(){}}});var ci=C(()=>{"use strict";Us();It()});var Me,ne,It=C(()=>{"use strict";E();li();ci();Me=class{listeners=new Map;wildcardListeners=[];onceListeners=new Map;listen(e,t){let s=typeof e=="string"?e:e.name;return this.listeners.has(s)||this.listeners.set(s,[]),this.listeners.get(s).push(t),()=>{let r=this.listeners.get(s);if(r){let i=r.indexOf(t);i>=0&&r.splice(i,1)}}}once(e,t){let s=typeof e=="string"?e:e.name;return this.onceListeners.has(s)||this.onceListeners.set(s,[]),this.onceListeners.get(s).push(t),()=>{let r=this.onceListeners.get(s);if(r){let i=r.indexOf(t);i>=0&&r.splice(i,1)}}}onAny(e){return this.wildcardListeners.push(e),()=>{let t=this.wildcardListeners.indexOf(e);t>=0&&this.wildcardListeners.splice(t,1)}}async dispatch(e){let t=e.constructor.name,s=this.listeners.get(t)??[];for(let i of s)await i(e);let r=this.onceListeners.get(t)??[];for(let i of r)await i(e);this.onceListeners.delete(t);for(let i of this.wildcardListeners)await i(t,e)}async emit(e,t){let s=this.listeners.get(e)??[];for(let i of s)await i(t);let r=this.onceListeners.get(e)??[];for(let i of r)await i(t);this.onceListeners.delete(e);for(let i of this.wildcardListeners)await i(e,t)}subscribe(e){e.subscribe(this)}forget(e){let t=typeof e=="string"?e:e.name;this.listeners.delete(t),this.onceListeners.delete(t)}flush(){this.listeners.clear(),this.onceListeners.clear(),this.wildcardListeners=[]}hasListeners(e){let t=typeof e=="string"?e:e.name;return(this.listeners.get(t)?.length??0)>0||(this.onceListeners.get(t)?.length??0)>0||this.wildcardListeners.length>0}listenerCount(e){let t=typeof e=="string"?e:e.name;return(this.listeners.get(t)?.length??0)+(this.onceListeners.get(t)?.length??0)}},ne=P("svelar.event",()=>new Me)});var jt,di=C(()=>{"use strict";Os();qs();It();jt=class o{static table;static primaryKey="id";static incrementing=!0;static timestamps=!0;static createdAt="created_at";static updatedAt="updated_at";static casts={};static fillable=[];static hidden=[];static connection=void 0;static hooks=new Map;static observers=new Map;static events=[];attributes={};originalAttributes={};relations={};exists=!1;constructor(e){return e&&this.fill(e),new Proxy(this,{get(t,s,r){return typeof s=="symbol"||s in t||typeof s!="string"||["table","primaryKey","incrementing","timestamps","casts","fillable","hidden","connection"].includes(s)?Reflect.get(t,s,r):typeof t[s]=="function"?t[s].bind(t):t.getAttribute(s)},set(t,s,r){return typeof s=="symbol"||s in t?Reflect.set(t,s,r):(t.setAttribute(s,r),!0)}})}static query(){let e=new this,t=this;return new j(t.table,this,t.connection)}static async find(e){let t=this;return this.query().find(e,t.primaryKey)}static async findOrFail(e){let t=this;return this.query().findOrFail(e,t.primaryKey)}static async all(){return this.query().get()}static async first(){return this.query().first()}static async firstOrFail(){return this.query().firstOrFail()}static where(e,t,s){return this.query().where(e,t,s)}static whereIn(e,t){return this.query().whereIn(e,t)}static whereNull(e){return this.query().whereNull(e)}static whereNotNull(e){return this.query().whereNotNull(e)}static orderBy(e,t){return this.query().orderBy(e,t)}static latest(e){return this.query().latest(e)}static oldest(e){return this.query().oldest(e)}static with(...e){return this.query().with(...e)}static async count(){return this.query().count()}static async create(e){let t=new this,s=this;if(t.fill(e),await t.fireHook("creating"),await t.fireHook("saving"),s.timestamps){let n=new Date().toISOString();t.setAttribute(s.createdAt,n),t.setAttribute(s.updatedAt,n)}let r=t.getInsertableAttributes(),a=await new j(s.table,this,s.connection).insertGetId(r,s.primaryKey);return s.incrementing&&a&&t.setAttribute(s.primaryKey,a),t.syncOriginal(),t.exists=!0,await t.fireHook("created"),await t.fireHook("saved"),t}async save(){let e=this.constructor;if(this.exists){await this.fireHook("updating"),await this.fireHook("saving"),e.timestamps&&this.setAttribute(e.updatedAt,new Date().toISOString());let t=this.getDirty();if(Object.keys(t).length>0){let s=this.getAttribute(e.primaryKey);await new j(e.table,this.constructor,e.connection).where(e.primaryKey,s).update(t)}this.syncOriginal(),await this.fireHook("updated"),await this.fireHook("saved")}else{if(await this.fireHook("creating"),await this.fireHook("saving"),e.timestamps){let i=new Date().toISOString();this.getAttribute(e.createdAt)||this.setAttribute(e.createdAt,i),this.setAttribute(e.updatedAt,i)}let t=this.getInsertableAttributes(),r=await new j(e.table,this.constructor,e.connection).insertGetId(t,e.primaryKey);e.incrementing&&r&&this.setAttribute(e.primaryKey,r),this.syncOriginal(),this.exists=!0,await this.fireHook("created"),await this.fireHook("saved")}}async update(e){this.fill(e),await this.save()}async delete(){let e=this.constructor;await this.fireHook("deleting");let t=this.getAttribute(e.primaryKey);await new j(e.table,this.constructor,e.connection).where(e.primaryKey,t).delete(),this.exists=!1,await this.fireHook("deleted")}async refresh(){let e=this.constructor,t=this.getAttribute(e.primaryKey),s=await this.constructor.find(t);s&&(this.attributes={...s.attributes},this.syncOriginal())}getAttribute(e){let t=this.constructor,s=this.attributes[e],r=t.casts[e];if(r&&s!==void 0&&s!==null)switch(r){case"number":return Number(s);case"boolean":return!!s;case"string":return String(s);case"date":return new Date(s);case"json":return typeof s=="string"?JSON.parse(s):s}return s}setAttribute(e,t){this.constructor.casts[e]==="json"&&typeof t!="string"?this.attributes[e]=JSON.stringify(t):this.attributes[e]=t}fill(e){let t=this.constructor;for(let[s,r]of Object.entries(e))t.fillable.length>0&&!t.fillable.includes(s)||this.setAttribute(s,r)}getAttributes(){return{...this.attributes}}getOriginal(e){return e?this.originalAttributes[e]:{...this.originalAttributes}}getDirty(){let e={};for(let[t,s]of Object.entries(this.attributes))s!==this.originalAttributes[t]&&(e[t]=s);return e}isDirty(...e){let t=this.getDirty();return e.length===0?Object.keys(t).length>0:e.some(s=>s in t)}isClean(...e){return!this.isDirty(...e)}wasChanged(...e){return this.isDirty(...e)}hasOne(e,t,s){return new se(this,e,t,s??this.constructor.primaryKey)}hasMany(e,t,s){return new re(this,e,t,s??this.constructor.primaryKey)}belongsTo(e,t,s){return new ie(this,e,t,s??e.primaryKey)}belongsToMany(e,t,s,r,i,a){return new ae(this,e,t,s,r,i??this.constructor.primaryKey,a??e.primaryKey)}setRelation(e,t){this.relations[e]=t}getRelation(e){return this.relations[e]}relationLoaded(e){return e in this.relations}toJSON(){let e=this.constructor,t={};for(let[s,r]of Object.entries(this.attributes))e.hidden.includes(s)||(t[s]=this.getAttribute(s));for(let[s,r]of Object.entries(this.relations))Array.isArray(r)?t[s]=r.map(i=>i instanceof o?i.toJSON():i):r instanceof o?t[s]=r.toJSON():t[s]=r;return t}toObject(){return this.toJSON()}static hydrate(e){let t=new this;return t.attributes={...e},t.syncOriginal(),t.exists=!0,t}static boot(e){this.hooks.set(this.name,e)}static observe(e){let t=this.observers.get(this.name)??[];t.push(e),this.observers.set(this.name,t)}static removeObservers(){this.observers.delete(this.name)}async fireHook(e){let t=this.constructor,s=o.hooks.get(t.name);s?.[e]&&await s[e](this),typeof this[e]=="function"&&await this[e]();let r=o.observers.get(t.name)??[];for(let a of r){let n=a[e];typeof n=="function"&&await n.call(a,this)}let i=t.name.toLowerCase();await ne.emit(`${i}.${e}`,this)}async fireEvent(e){let t=this.constructor;if(!t.events.includes(e))throw new Error(`Event "${e}" is not declared in ${t.name}.events. Add it to: static events = ['${e}', ...];`);let s=o.observers.get(t.name)??[];for(let i of s){let a=i[e];typeof a=="function"&&await a.call(i,this)}let r=t.name.toLowerCase();await ne.emit(`${r}.${e}`,this)}syncOriginal(){this.originalAttributes={...this.attributes}}getInsertableAttributes(){let e=this.constructor,t={...this.attributes};return e.incrementing&&t[e.primaryKey]===void 0&&delete t[e.primaryKey],t}static get tableName(){return this.table}}});var Ot,ui=C(()=>{"use strict";Ot=class{async call(e){await new e().run()}}});var J,mi,Fs=C(()=>{"use strict";E();J=class{bindings=new Map;aliases=new Map;resolved=new Set;bind(e,t){this.bindings.set(e,{factory:t,singleton:!1,tags:[]})}singleton(e,t){this.bindings.set(e,{factory:t,singleton:!0,tags:[]})}instance(e,t){this.bindings.set(e,{factory:()=>t,singleton:!0,instance:t,tags:[]})}alias(e,t){this.aliases.set(e,t)}async make(e){let t=this.resolveAlias(e),s=this.bindings.get(t);if(!s)throw new Error(`No binding found for "${e}" in the container.`);if(s.singleton&&s.instance!==void 0)return s.instance;let r=await s.factory(this);return s.singleton&&(s.instance=r),this.resolved.add(t),r}makeSync(e){let t=this.resolveAlias(e),s=this.bindings.get(t);if(!s)throw new Error(`No binding found for "${e}" in the container.`);if(s.singleton&&s.instance!==void 0)return s.instance;let r=s.factory(this);if(r instanceof Promise)throw new Error(`Binding "${e}" has an async factory. Use container.make() instead of container.makeSync().`);return s.singleton&&(s.instance=r),this.resolved.add(t),r}has(e){let t=this.resolveAlias(e);return this.bindings.has(t)}isResolved(e){return this.resolved.has(this.resolveAlias(e))}tag(e,t){for(let s of e){let r=this.bindings.get(s);r&&r.tags.push(t)}}async tagged(e){let t=[];for(let[s,r]of this.bindings)r.tags.includes(e)&&t.push(await this.make(s));return t}flush(){for(let e of this.bindings.values())e.singleton&&(e.instance=void 0);this.resolved.clear()}forget(e){this.bindings.delete(e),this.resolved.delete(e)}getBindings(){return[...this.bindings.keys()]}resolveAlias(e){return this.aliases.get(e)??e}},mi=P("svelar.container",()=>new J)});var qt,pi=C(()=>{"use strict";Fs();qt=class{container;providers=[];booted=!1;constructor(e){this.container=e??new J,this.container.instance("app",this),this.container.instance("container",this.container)}register(e){let t=new e(this.container);return this.providers.push(t),this}async bootstrap(){if(this.booted)return this;for(let e of this.providers)await e.register();for(let e of this.providers)await e.boot();return this.booted=!0,this}isBooted(){return this.booted}async make(e){return this.container.make(e)}getProviders(){return[...this.providers]}}});var $,H,Ut,oe,Ft,le,ce,Bt,de,ue=C(()=>{"use strict";$=class{},H=class{middleware=[];namedMiddleware=new Map;use(e){return typeof e=="function"&&"prototype"in e&&typeof e.prototype?.handle=="function"?this.middleware.push(new e):this.middleware.push(e),this}register(e,t){return typeof t=="function"&&"prototype"in t&&typeof t.prototype?.handle=="function"?this.namedMiddleware.set(e,new t):this.namedMiddleware.set(e,t),this}get(e){return this.namedMiddleware.get(e)}async execute(e,t,s){let r=[...this.middleware];if(s)for(let a of s){let n=this.namedMiddleware.get(a);n&&r.push(n)}let i=t;for(let a=r.length-1;a>=0;a--){let n=r[a],l=i;typeof n.handle=="function"?i=()=>n.handle(e,l):i=()=>n(e,l)}return i()}count(){return this.middleware.length}},Ut=class extends ${constructor(t={}){super();this.options=t}async handle(t,s){let r=await s();if(!r)return;let i=Array.isArray(this.options.origin)?this.options.origin.join(", "):this.options.origin??"*";return r.headers.set("Access-Control-Allow-Origin",i),r.headers.set("Access-Control-Allow-Methods",(this.options.methods??["GET","POST","PUT","DELETE","PATCH","OPTIONS"]).join(", ")),r.headers.set("Access-Control-Allow-Headers",(this.options.headers??["Content-Type","Authorization"]).join(", ")),this.options.credentials&&r.headers.set("Access-Control-Allow-Credentials","true"),this.options.maxAge&&r.headers.set("Access-Control-Max-Age",String(this.options.maxAge)),t.event.request.method==="OPTIONS"?new Response(null,{status:204,headers:r.headers}):r}},oe=class extends ${requests=new Map;maxRequests;windowMs;constructor(e={}){super(),this.maxRequests=e.maxRequests??60,this.windowMs=e.windowMs??6e4}async handle(e,t){let s=e.event.request.headers.get("x-forwarded-for")??e.event.getClientAddress?.()??"unknown",r=Date.now(),i=this.requests.get(s);if(i&&r<i.resetAt){if(i.count>=this.maxRequests)return new Response(JSON.stringify({error:"Too many requests"}),{status:429,headers:{"Content-Type":"application/json","Retry-After":String(Math.ceil((i.resetAt-r)/1e3))}});i.count++}else this.requests.set(s,{count:1,resetAt:r+this.windowMs});return t()}},Ft=class extends ${async handle(e,t){let s=Date.now(),r=e.event.request.method,i=e.event.url.pathname,a=await t(),n=Date.now()-s,l=a instanceof Response?a.status:200;return console.log(`[${new Date().toISOString()}] ${r} ${i} \u2192 ${l} (${n}ms)`),a}},le=class extends ${cookieName;headerName;fieldName;excludePaths;onlyPaths;constructor(e={}){super(),this.cookieName=e.cookieName??"XSRF-TOKEN",this.headerName=e.headerName??"X-CSRF-Token",this.fieldName=e.fieldName??"_csrf",this.excludePaths=e.excludePaths??[],this.onlyPaths=e.onlyPaths??null}async handle(e,t){let{event:s}=e,r=s.request.method.toUpperCase();if(["GET","HEAD","OPTIONS"].includes(r))return this.setTokenAndContinue(e,t);if((s.request.headers.get("authorization")??"").startsWith("Bearer "))return t();let a=s.url.pathname;if(this.onlyPaths&&!this.onlyPaths.some(c=>a.startsWith(c)))return this.setTokenAndContinue(e,t);if(this.excludePaths.some(c=>a.startsWith(c)))return t();let n=this.getCookieToken(s),l=s.request.headers.get(this.headerName)??await this.getBodyToken(s);return!n||!l||!this.timingSafeEqual(n,l)?new Response(JSON.stringify({message:"CSRF token mismatch"}),{status:419,headers:{"Content-Type":"application/json"}}):t()}async setTokenAndContinue(e,t){let s=await t();if(!(s instanceof Response))return s;let i=this.getCookieToken(e.event)||this.generateToken();return s.headers.append("Set-Cookie",`${this.cookieName}=${i}; Path=/; SameSite=Lax`),s}getCookieToken(e){let s=(e.request.headers.get("cookie")??"").match(new RegExp(`${this.cookieName}=([^;]+)`));return s?s[1]:null}async getBodyToken(e){try{let t=e.request.headers.get("content-type")??"";if(t.includes("application/x-www-form-urlencoded")||t.includes("multipart/form-data"))return(await e.request.clone().formData()).get(this.fieldName);if(t.includes("application/json"))return(await e.request.clone().json())[this.fieldName]??null}catch{}return null}generateToken(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let s=new TextEncoder,r=s.encode(e),i=s.encode(t),a=0;for(let n=0;n<r.length;n++)a|=r[n]^i[n];return a===0}},ce=class extends ${allowedOrigins;constructor(e={}){super(),this.allowedOrigins=new Set(e.allowedOrigins??[])}async handle(e,t){let{event:s}=e,r=s.request.method.toUpperCase();if(["GET","HEAD","OPTIONS"].includes(r)||(s.request.headers.get("authorization")??"").startsWith("Bearer "))return t();let a=s.request.headers.get("origin");if(!a)return t();let n=s.url.origin;return a===n||this.allowedOrigins.has(a)?t():new Response(JSON.stringify({message:"Cross-origin request blocked"}),{status:403,headers:{"Content-Type":"application/json"}})}},Bt=class extends ${secret;tolerance;signatureHeader;timestampHeader;onlyPaths;constructor(e){super(),this.secret=e.secret,this.tolerance=e.tolerance??300,this.signatureHeader=e.signatureHeader??"X-Signature",this.timestampHeader=e.timestampHeader??"X-Timestamp",this.onlyPaths=e.onlyPaths??null}async handle(e,t){let{event:s}=e;if(this.onlyPaths){let y=s.url.pathname;if(!this.onlyPaths.some(v=>y.startsWith(v)))return t()}let r=s.request.headers.get(this.signatureHeader),i=s.request.headers.get(this.timestampHeader);if(!r||!i)return new Response(JSON.stringify({message:"Missing request signature"}),{status:401,headers:{"Content-Type":"application/json"}});let a=parseInt(i,10),n=Math.floor(Date.now()/1e3);if(isNaN(a)||Math.abs(n-a)>this.tolerance)return new Response(JSON.stringify({message:"Request signature expired"}),{status:401,headers:{"Content-Type":"application/json"}});let c=await s.request.clone().text(),{createHmac:m}=await import("crypto"),p=s.request.method.toUpperCase(),h=s.url.pathname+s.url.search,u=`${i}.${p}.${h}.${c}`,b=m("sha256",this.secret).update(u).digest("hex");return r.length!==b.length||!this.timingSafeCompare(r,b)?new Response(JSON.stringify({message:"Invalid request signature"}),{status:401,headers:{"Content-Type":"application/json"}}):t()}timingSafeCompare(e,t){if(e.length!==t.length)return!1;let s=new TextEncoder,r=s.encode(e),i=s.encode(t),a=0;for(let n=0;n<r.length;n++)a|=r[n]^i[n];return a===0}static sign(e,t,s,r,i){let{createHmac:a}=Qe("crypto"),n=i??Math.floor(Date.now()/1e3),l=`${n}.${t.toUpperCase()}.${s}.${r}`;return{signature:a("sha256",e).update(l).digest("hex"),timestamp:n}}},de=class extends ${attempts=new Map;maxAttempts;decayMinutes;constructor(e={}){super(),this.maxAttempts=e.maxAttempts??5,this.decayMinutes=e.decayMinutes??1}async handle(e,t){let r=`${e.event.request.headers.get("x-forwarded-for")??e.event.getClientAddress?.()??"unknown"}:${e.event.url.pathname}`,i=Date.now(),a=this.attempts.get(r);if(a){if(i<a.blockedUntil){let l=Math.ceil((a.blockedUntil-i)/1e3);return new Response(JSON.stringify({message:"Too many attempts. Please try again later.",retry_after:l}),{status:429,headers:{"Content-Type":"application/json","Retry-After":String(l)}})}if(a.count>=this.maxAttempts){a.blockedUntil=i+this.decayMinutes*6e4,a.count=0;let l=this.decayMinutes*60;return new Response(JSON.stringify({message:"Too many attempts. Please try again later.",retry_after:l}),{status:429,headers:{"Content-Type":"application/json","Retry-After":String(l)}})}}let n=await t();if(n instanceof Response&&n.status>=400&&n.status<500){let l=this.attempts.get(r)??{count:0,blockedUntil:0};if(l.count++,this.attempts.set(r,l),this.attempts.size>1e4)for(let[c,m]of this.attempts)i>m.blockedUntil+this.decayMinutes*6e4*2&&this.attempts.delete(c)}return n}}});import{z as me}from"zod";function hi(o,e=!1){let t=new o;return e?{GET:t.handle("show"),PUT:t.handle("update"),PATCH:t.handle("update"),DELETE:t.handle("destroy")}:{GET:t.handle("index"),POST:t.handle("store")}}var Ht,z,Ne,Ie,je,gi=C(()=>{"use strict";ue();Ht=class{controllerMiddleware=[];middleware(e,t){let s;typeof e=="function"&&e.prototype instanceof $?s=new e:s=e,this.controllerMiddleware.push({middleware:s,only:t?.only,except:t?.except})}handle(e){return async t=>{try{let s=this.controllerMiddleware.filter(r=>!(r.only&&!r.only.includes(e)||r.except&&r.except.includes(e)));if(s.length>0){let r=new H;for(let{middleware:n}of s)r.use(n);let i={event:t,params:t.params,locals:t.locals},a=await r.execute(i,async()=>this.callMethod(e,t));if(a instanceof Response)return a}return await this.callMethod(e,t)}catch(s){return this.handleError(s,t)}}}json(e,t=200,s={}){let r=JSON.stringify(e,null,2);return new Response(r,{status:t,headers:{"Content-Type":"application/json",...s}})}text(e,t=200){return new Response(e,{status:t,headers:{"Content-Type":"text/plain"}})}html(e,t=200){return new Response(e,{status:t,headers:{"Content-Type":"text/html"}})}redirect(e,t=302){return new Response(null,{status:t,headers:{Location:e}})}noContent(){return new Response(null,{status:204})}created(e){return e?this.json(e,201):new Response(null,{status:201})}async validate(e,t){let s=t instanceof me.ZodObject?t:me.object(t),r,i=e.request.headers.get("content-type")??"";if(i.includes("application/json"))r=await e.request.json();else if(i.includes("multipart/form-data")||i.includes("application/x-www-form-urlencoded")){let n=await e.request.formData();r=Object.fromEntries(n)}else r=Object.fromEntries(e.url.searchParams);let a=s.safeParse(r);if(!a.success)throw new z(a.error);return a.data}validateQuery(e,t){let s=t instanceof me.ZodObject?t:me.object(t),r=Object.fromEntries(e.url.searchParams),i=s.safeParse(r);if(!i.success)throw new z(i.error);return i.data}validateParams(e,t){let r=(t instanceof me.ZodObject?t:me.object(t)).safeParse(e.params);if(!r.success)throw new z(r.error);return r.data}handleError(e,t){return e instanceof z?this.json({message:"Validation failed",errors:e.errors},422):e instanceof Ne?this.json({message:e.message||"Not found"},404):e instanceof Ie?this.json({message:e.message||"Unauthorized"},401):e instanceof je?this.json({message:e.message||"Forbidden"},403):(console.error("[Svelar] Controller error:",e),this.json({message:process.env.NODE_ENV==="production"?"Internal server error":e.message},500))}async callMethod(e,t){let s=this[e];if(typeof s!="function")throw new Error(`Method "${e}" not found on controller "${this.constructor.name}".`);let r=await s.call(this,t);return r instanceof Response?r:this.json(r)}};z=class extends Error{errors;constructor(e){super("Validation failed"),this.name="ValidationError",this.errors={};for(let t of e.issues){let s=t.path.join(".");this.errors[s]||(this.errors[s]=[]),this.errors[s].push(t.message)}}},Ne=class extends Error{constructor(e="Not found"){super(e),this.name="NotFoundError"}},Ie=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}},je=class extends Error{constructor(e="Forbidden"){super(e),this.name="ForbiddenError"}}});import{randomBytes as po,createHmac as fi,timingSafeEqual as ho}from"crypto";import{promises as K}from"fs";import{join as Oe}from"path";var pe,qe,V,zt,Kt,Wt,he,Bs=C(()=>{"use strict";ue();pe=class o{constructor(e,t){this.id=e;t&&(this.data={...t},this.data._flash&&(this.previousFlashData=this.data._flash,delete this.data._flash))}data={};dirty=!1;flashData={};previousFlashData={};get(e,t){return e in this.flashData?this.flashData[e]:e in this.previousFlashData?this.previousFlashData[e]:e in this.data?this.data[e]:t}set(e,t){this.data[e]=t,this.dirty=!0}has(e){return e in this.data||e in this.flashData||e in this.previousFlashData}forget(e){delete this.data[e],this.dirty=!0}flush(){this.data={},this.dirty=!0}flash(e,t){this.flashData[e]=t,this.dirty=!0}all(){return{...this.data,...this.previousFlashData,...this.flashData}}isDirty(){return this.dirty||Object.keys(this.flashData).length>0}toPersist(){let e={...this.data};return Object.keys(this.flashData).length>0&&(e._flash=this.flashData),e}regenerateId(){let e=this.id,t=o.generateId();this.id=t,this.dirty=!0;let s=qe.get(e);return s instanceof V&&s.markOldSessionId(e),qe.delete(e),t}static generateId(){return po(32).toString("hex")}},qe=new Map,V=class{sessions=new Map;oldSessionIds=new Set;async read(e){if(this.oldSessionIds.has(e))return null;let t=this.sessions.get(e);return t?Date.now()>t.expiresAt?(this.sessions.delete(e),null):t.data:null}async write(e,t,s){this.sessions.set(e,{data:t,expiresAt:Date.now()+s*1e3}),qe.set(e,this)}async destroy(e){this.sessions.delete(e),qe.delete(e)}async gc(e){let t=Date.now();for(let[s,r]of this.sessions)t>r.expiresAt&&(this.sessions.delete(s),qe.delete(s))}markOldSessionId(e){this.oldSessionIds.add(e),this.sessions.delete(e)}},zt=class{constructor(e="sessions",t){this.tableName=e;this.connectionName=t}tableEnsured=!1;async ensureTable(){if(!this.tableEnsured)try{let{Connection:e}=await Promise.resolve().then(()=>(S(),R));switch(e.getDriver(this.connectionName)){case"sqlite":await e.raw(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
43
43
  id TEXT PRIMARY KEY,
44
44
  payload TEXT NOT NULL,
45
45
  expires_at TEXT NOT NULL
@@ -51,10 +51,10 @@ var da=Object.defineProperty;var Qe=(o=>typeof require<"u"?require:typeof Proxy<
51
51
  id VARCHAR(255) PRIMARY KEY,
52
52
  payload TEXT NOT NULL,
53
53
  expires_at DATETIME NOT NULL
54
- ) ENGINE=InnoDB`,[],this.connectionName);break}this.tableEnsured=!0}catch{}}async read(e){await this.ensureTable();let{Connection:t}=await Promise.resolve().then(()=>(P(),R)),s=await t.raw(`SELECT payload, expires_at FROM ${this.tableName} WHERE id = ?`,[e],this.connectionName);if(s.length===0)return null;let r=s[0];if(new Date(r.expires_at)<new Date)return await this.destroy(e),null;try{return JSON.parse(r.payload)}catch{return null}}async write(e,t,s){await this.ensureTable();let{Connection:r}=await Promise.resolve().then(()=>(P(),R)),i=JSON.stringify(t),a=new Date(Date.now()+s*1e3).toISOString(),n=r.getDriver(this.connectionName);n==="sqlite"?await r.raw(`INSERT INTO ${this.tableName} (id, payload, expires_at) VALUES (?, ?, ?)
54
+ ) ENGINE=InnoDB`,[],this.connectionName);break}this.tableEnsured=!0}catch{}}async read(e){await this.ensureTable();let{Connection:t}=await Promise.resolve().then(()=>(S(),R)),s=await t.raw(`SELECT payload, expires_at FROM ${this.tableName} WHERE id = ?`,[e],this.connectionName);if(s.length===0)return null;let r=s[0];if(new Date(r.expires_at)<new Date)return await this.destroy(e),null;try{return JSON.parse(r.payload)}catch{return null}}async write(e,t,s){await this.ensureTable();let{Connection:r}=await Promise.resolve().then(()=>(S(),R)),i=JSON.stringify(t),a=new Date(Date.now()+s*1e3).toISOString(),n=r.getDriver(this.connectionName);n==="sqlite"?await r.raw(`INSERT INTO ${this.tableName} (id, payload, expires_at) VALUES (?, ?, ?)
55
55
  ON CONFLICT(id) DO UPDATE SET payload = excluded.payload, expires_at = excluded.expires_at`,[e,i,a],this.connectionName):n==="postgres"?await r.raw(`INSERT INTO ${this.tableName} (id, payload, expires_at) VALUES ($1, $2, $3)
56
56
  ON CONFLICT(id) DO UPDATE SET payload = $2, expires_at = $3`,[e,i,a],this.connectionName):await r.raw(`INSERT INTO ${this.tableName} (id, payload, expires_at) VALUES (?, ?, ?)
57
- ON DUPLICATE KEY UPDATE payload = VALUES(payload), expires_at = VALUES(expires_at)`,[e,i,a],this.connectionName)}async destroy(e){let{Connection:t}=await Promise.resolve().then(()=>(P(),R));await t.raw(`DELETE FROM ${this.tableName} WHERE id = ?`,[e],this.connectionName)}async gc(e){let{Connection:t}=await Promise.resolve().then(()=>(P(),R));await t.raw(`DELETE FROM ${this.tableName} WHERE expires_at < ?`,[new Date().toISOString()],this.connectionName)}},Ht=class{dir;constructor(e){this.dir=e??Oe(process.cwd(),"storage","sessions")}filePath(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"");return Oe(this.dir,`${t}.json`)}async ensureDir(){await K.mkdir(this.dir,{recursive:!0})}async read(e){try{let t=await K.readFile(this.filePath(e),"utf-8"),s=JSON.parse(t);return new Date(s.expiresAt)<new Date?(await this.destroy(e),null):s.data}catch{return null}}async write(e,t,s){await this.ensureDir();let r={data:t,expiresAt:new Date(Date.now()+s*1e3).toISOString()};await K.writeFile(this.filePath(e),JSON.stringify(r),"utf-8")}async destroy(e){try{await K.unlink(this.filePath(e))}catch{}}async gc(e){try{let t=await K.readdir(this.dir),s=new Date;for(let r of t)if(r.endsWith(".json"))try{let i=await K.readFile(Oe(this.dir,r),"utf-8"),a=JSON.parse(i);new Date(a.expiresAt)<s&&await K.unlink(Oe(this.dir,r))}catch{await K.unlink(Oe(this.dir,r)).catch(()=>{})}}catch{}}},zt=class{redis;prefix;constructor(e){this.prefix=e?.prefix??"svelar_session:",e?.client?this.redis=e.client:this._url=e?.url}_url;_connecting;async getClient(){return this.redis?this.redis:(this._connecting||(this._connecting=(async()=>{try{let{default:e}=await import("ioredis");return this.redis=this._url?new e(this._url):new e,this.redis}catch{throw new Error('RedisSessionStore requires "ioredis" package. Install it: npm install ioredis')}})()),this._connecting)}async read(e){let s=await(await this.getClient()).get(this.prefix+e);if(!s)return null;try{return JSON.parse(s)}catch{return null}}async write(e,t,s){await(await this.getClient()).set(this.prefix+e,JSON.stringify(t),"EX",s)}async destroy(e){await(await this.getClient()).del(this.prefix+e)}async gc(e){}},he=class extends ${config;constructor(e){if(super(),this.config={cookieName:"svelar_session",lifetime:7200,secret:"",path:"/",domain:"",secure:process.env.NODE_ENV==="production",httpOnly:!0,sameSite:"lax",...e},!this.config.secret)throw new Error("APP_KEY is not set. Pass `secret` to createSvelarApp() \u2014 e.g. secret: env.APP_KEY (from $env/dynamic/private).")}async handle(e,t){let s=e.event.request.headers.get("cookie")??"",r=this.getSessionIdFromCookie(s),i=null;if(r){let l=this.verifySignedId(r);l?(i=await this.config.store.read(l),r=l):r=null}r||(r=pe.generateId());let a=new pe(r,i??{});e.event.locals.session=a,e.locals.session=a;let n=await t();if(a.isDirty()&&await this.config.store.write(a.id,a.toPersist(),this.config.lifetime),n instanceof Response){let l=this.signId(a.id),c=this.buildCookieString(l);n.headers.append("Set-Cookie",c)}return n}getSessionIdFromCookie(e){let t=e.split(";").map(s=>s.trim());for(let s of t){let[r,...i]=s.split("=");if(r===this.config.cookieName)return decodeURIComponent(i.join("="))}return null}signId(e){let t=mi("sha256",this.config.secret).update(e).digest("base64url");return`${e}.${t}`}verifySignedId(e){let t=e.lastIndexOf(".");if(t===-1)return null;let s=e.slice(0,t),r=e.slice(t+1),i=mi("sha256",this.config.secret).update(s).digest("base64url");if(r.length!==i.length)return null;let a=Buffer.from(r),n=Buffer.from(i);if(a.length!==n.length)return null;try{if(eo(a,n))return s}catch{}return null}buildCookieString(e){let t=[`${this.config.cookieName}=${encodeURIComponent(e)}`];return t.push(`Path=${this.config.path}`),t.push(`Max-Age=${this.config.lifetime}`),this.config.domain&&t.push(`Domain=${this.config.domain}`),this.config.secure&&t.push("Secure"),this.config.httpOnly&&t.push("HttpOnly"),t.push(`SameSite=${this.config.sameSite}`),t.join("; ")}}});var Ue={};L(Ue,{Hash:()=>Hs});import{randomBytes as Fs,scrypt as pi,timingSafeEqual as to}from"crypto";async function so(o,e=16384){let t=Fs(16),s=64,r=await new Promise((i,a)=>{pi(o,t,s,{N:e,r:8,p:1},(n,l)=>{n?a(n):i(l)})});return`$scrypt$N=${e}$${t.toString("base64")}$${r.toString("base64")}`}async function ro(o,e){let t=e.split("$");if(t.length!==5||t[1]!=="scrypt")return!1;let s=parseInt(t[2].replace("N=",""),10),r=Buffer.from(t[3],"base64"),i=Buffer.from(t[4],"base64"),a=i.length,n=await new Promise((l,c)=>{pi(o,r,a,{N:s,r:8,p:1},(m,p)=>{m?c(m):l(p)})});return to(n,i)}var Bs,Hs,ge=w(()=>{"use strict";E();Bs=class{config={driver:"scrypt",scryptCost:16384,bcryptRounds:12};configure(e){Object.assign(this.config,e)}async make(e){switch(this.config.driver){case"scrypt":return so(e,this.config.scryptCost);case"bcrypt":try{return(await import("bcrypt")).default.hash(e,this.config.bcryptRounds??12)}catch{throw new Error('bcrypt driver requires the "bcrypt" package. Install it: npm install bcrypt')}case"argon2":try{return(await import("argon2")).default.hash(e)}catch{throw new Error('argon2 driver requires the "argon2" package. Install it: npm install argon2')}default:throw new Error(`Unsupported hash driver: ${this.config.driver}`)}}async verify(e,t){if(t.startsWith("$scrypt$"))return ro(e,t);if(t.startsWith("$2b$")||t.startsWith("$2a$")||t.startsWith("$2y$"))try{return(await import("bcrypt")).default.compare(e,t)}catch{throw new Error("bcrypt package required to verify bcrypt hashes.")}if(t.startsWith("$argon2"))try{return(await import("argon2")).default.verify(t,e)}catch{throw new Error("argon2 package required to verify argon2 hashes.")}return!1}needsRehash(e){if(this.config.driver==="scrypt"&&e.startsWith("$scrypt$")){let t=e.match(/N=(\d+)/);if(t)return parseInt(t[1],10)!==this.config.scryptCost}if(this.config.driver==="bcrypt"&&(e.startsWith("$2b$")||e.startsWith("$2a$"))){let t=e.match(/\$2[aby]\$(\d+)\$/);if(t)return parseInt(t[1],10)!==this.config.bcryptRounds}return this.config.driver==="scrypt"&&!e.startsWith("$scrypt$")||this.config.driver==="bcrypt"&&!e.startsWith("$2")||this.config.driver==="argon2"&&!e.startsWith("$argon2")}randomString(e=32){return Fs(Math.ceil(e/2)).toString("hex").slice(0,e)}randomToken(e=32){return Fs(e).toString("base64url")}},Hs=S("svelar.hash",()=>new Bs)});var hi={};L(hi,{EmailTemplates:()=>io});import{randomUUID as q}from"crypto";var zs,io,gi=w(()=>{"use strict";E();zs=class{config={driver:"memory"};templates=new Map;constructor(){this.registerDefaults()}configure(e){this.config=e}async register(e){let t={...e,id:q(),createdAt:Date.now(),updatedAt:Date.now()};if(this.config.driver==="memory")this.templates.set(e.name,t);else if(this.config.driver==="database")try{let{Connection:s}=await Promise.resolve().then(()=>(P(),R));await s.connection()}catch{this.templates.set(e.name,t)}return t}async render(e,t){let s=await this.get(e);if(!s)throw new Error(`Template "${e}" not found`);let r=this.interpolate(s.subject,t),i=this.interpolate(s.html,t),a=s.text?this.interpolate(s.text,t):void 0;return{subject:r,html:i,text:a}}async get(e){return this.templates.get(e)||null}async list(e){let t=Array.from(this.templates.values());return e&&(t=t.filter(s=>s.category===e)),t}async update(e,t){let s=this.templates.get(e);return s?(Object.assign(s,t,{updatedAt:Date.now()}),s):null}async delete(e){return this.templates.delete(e)}registerDefaults(){this.templates.set("welcome",{id:q(),name:"welcome",subject:"Welcome to {{appName}}, {{user.name}}!",html:`
57
+ ON DUPLICATE KEY UPDATE payload = VALUES(payload), expires_at = VALUES(expires_at)`,[e,i,a],this.connectionName)}async destroy(e){let{Connection:t}=await Promise.resolve().then(()=>(S(),R));await t.raw(`DELETE FROM ${this.tableName} WHERE id = ?`,[e],this.connectionName)}async gc(e){let{Connection:t}=await Promise.resolve().then(()=>(S(),R));await t.raw(`DELETE FROM ${this.tableName} WHERE expires_at < ?`,[new Date().toISOString()],this.connectionName)}},Kt=class{dir;constructor(e){this.dir=e??Oe(process.cwd(),"storage","sessions")}filePath(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"");return Oe(this.dir,`${t}.json`)}async ensureDir(){await K.mkdir(this.dir,{recursive:!0})}async read(e){try{let t=await K.readFile(this.filePath(e),"utf-8"),s=JSON.parse(t);return new Date(s.expiresAt)<new Date?(await this.destroy(e),null):s.data}catch{return null}}async write(e,t,s){await this.ensureDir();let r={data:t,expiresAt:new Date(Date.now()+s*1e3).toISOString()};await K.writeFile(this.filePath(e),JSON.stringify(r),"utf-8")}async destroy(e){try{await K.unlink(this.filePath(e))}catch{}}async gc(e){try{let t=await K.readdir(this.dir),s=new Date;for(let r of t)if(r.endsWith(".json"))try{let i=await K.readFile(Oe(this.dir,r),"utf-8"),a=JSON.parse(i);new Date(a.expiresAt)<s&&await K.unlink(Oe(this.dir,r))}catch{await K.unlink(Oe(this.dir,r)).catch(()=>{})}}catch{}}},Wt=class{redis;prefix;constructor(e){this.prefix=e?.prefix??"svelar_session:",e?.client?this.redis=e.client:this._url=e?.url}_url;_connecting;async getClient(){return this.redis?this.redis:(this._connecting||(this._connecting=(async()=>{try{let{default:e}=await import("ioredis");return this.redis=this._url?new e(this._url):new e,this.redis}catch{throw new Error('RedisSessionStore requires "ioredis" package. Install it: npm install ioredis')}})()),this._connecting)}async read(e){let s=await(await this.getClient()).get(this.prefix+e);if(!s)return null;try{return JSON.parse(s)}catch{return null}}async write(e,t,s){await(await this.getClient()).set(this.prefix+e,JSON.stringify(t),"EX",s)}async destroy(e){await(await this.getClient()).del(this.prefix+e)}async gc(e){}},he=class extends ${config;constructor(e){if(super(),this.config={cookieName:"svelar_session",lifetime:7200,secret:"",path:"/",domain:"",secure:process.env.NODE_ENV==="production",httpOnly:!0,sameSite:"lax",...e},!this.config.secret)throw new Error("APP_KEY is not set. Pass `secret` to createSvelarApp() \u2014 e.g. secret: env.APP_KEY (from $env/dynamic/private).")}async handle(e,t){let s=e.event.request.headers.get("cookie")??"",r=this.getSessionIdFromCookie(s),i=null;if(r){let l=this.verifySignedId(r);l?(i=await this.config.store.read(l),r=l):r=null}r||(r=pe.generateId());let a=new pe(r,i??{});e.event.locals.session=a,e.locals.session=a;let n=await t();if(a.isDirty()&&await this.config.store.write(a.id,a.toPersist(),this.config.lifetime),n instanceof Response){let l=this.signId(a.id),c=this.buildCookieString(l);n.headers.append("Set-Cookie",c)}return n}getSessionIdFromCookie(e){let t=e.split(";").map(s=>s.trim());for(let s of t){let[r,...i]=s.split("=");if(r===this.config.cookieName)return decodeURIComponent(i.join("="))}return null}signId(e){let t=fi("sha256",this.config.secret).update(e).digest("base64url");return`${e}.${t}`}verifySignedId(e){let t=e.lastIndexOf(".");if(t===-1)return null;let s=e.slice(0,t),r=e.slice(t+1),i=fi("sha256",this.config.secret).update(s).digest("base64url");if(r.length!==i.length)return null;let a=Buffer.from(r),n=Buffer.from(i);if(a.length!==n.length)return null;try{if(ho(a,n))return s}catch{}return null}buildCookieString(e){let t=[`${this.config.cookieName}=${encodeURIComponent(e)}`];return t.push(`Path=${this.config.path}`),t.push(`Max-Age=${this.config.lifetime}`),this.config.domain&&t.push(`Domain=${this.config.domain}`),this.config.secure&&t.push("Secure"),this.config.httpOnly&&t.push("HttpOnly"),t.push(`SameSite=${this.config.sameSite}`),t.join("; ")}}});var Ue={};L(Ue,{Hash:()=>Ks});import{randomBytes as Hs,scrypt as bi,timingSafeEqual as go}from"crypto";async function fo(o,e=16384){let t=Hs(16),s=64,r=await new Promise((i,a)=>{bi(o,t,s,{N:e,r:8,p:1},(n,l)=>{n?a(n):i(l)})});return`$scrypt$N=${e}$${t.toString("base64")}$${r.toString("base64")}`}async function bo(o,e){let t=e.split("$");if(t.length!==5||t[1]!=="scrypt")return!1;let s=parseInt(t[2].replace("N=",""),10),r=Buffer.from(t[3],"base64"),i=Buffer.from(t[4],"base64"),a=i.length,n=await new Promise((l,c)=>{bi(o,r,a,{N:s,r:8,p:1},(m,p)=>{m?c(m):l(p)})});return go(n,i)}var zs,Ks,ge=C(()=>{"use strict";E();zs=class{config={driver:"scrypt",scryptCost:16384,bcryptRounds:12};configure(e){Object.assign(this.config,e)}async make(e){switch(this.config.driver){case"scrypt":return fo(e,this.config.scryptCost);case"bcrypt":try{return(await import("bcrypt")).default.hash(e,this.config.bcryptRounds??12)}catch{throw new Error('bcrypt driver requires the "bcrypt" package. Install it: npm install bcrypt')}case"argon2":try{return(await import("argon2")).default.hash(e)}catch{throw new Error('argon2 driver requires the "argon2" package. Install it: npm install argon2')}default:throw new Error(`Unsupported hash driver: ${this.config.driver}`)}}async verify(e,t){if(t.startsWith("$scrypt$"))return bo(e,t);if(t.startsWith("$2b$")||t.startsWith("$2a$")||t.startsWith("$2y$"))try{return(await import("bcrypt")).default.compare(e,t)}catch{throw new Error("bcrypt package required to verify bcrypt hashes.")}if(t.startsWith("$argon2"))try{return(await import("argon2")).default.verify(t,e)}catch{throw new Error("argon2 package required to verify argon2 hashes.")}return!1}needsRehash(e){if(this.config.driver==="scrypt"&&e.startsWith("$scrypt$")){let t=e.match(/N=(\d+)/);if(t)return parseInt(t[1],10)!==this.config.scryptCost}if(this.config.driver==="bcrypt"&&(e.startsWith("$2b$")||e.startsWith("$2a$"))){let t=e.match(/\$2[aby]\$(\d+)\$/);if(t)return parseInt(t[1],10)!==this.config.bcryptRounds}return this.config.driver==="scrypt"&&!e.startsWith("$scrypt$")||this.config.driver==="bcrypt"&&!e.startsWith("$2")||this.config.driver==="argon2"&&!e.startsWith("$argon2")}randomString(e=32){return Hs(Math.ceil(e/2)).toString("hex").slice(0,e)}randomToken(e=32){return Hs(e).toString("base64url")}},Ks=P("svelar.hash",()=>new zs)});var yi={};L(yi,{EmailTemplates:()=>yo});import{randomUUID as q}from"crypto";var Ws,yo,vi=C(()=>{"use strict";E();Ws=class{config={driver:"memory"};templates=new Map;constructor(){this.registerDefaults()}configure(e){this.config=e}async register(e){let t={...e,id:q(),createdAt:Date.now(),updatedAt:Date.now()};if(this.config.driver==="memory")this.templates.set(e.name,t);else if(this.config.driver==="database")try{let{Connection:s}=await Promise.resolve().then(()=>(S(),R));await s.connection()}catch{this.templates.set(e.name,t)}return t}async render(e,t){let s=await this.get(e);if(!s)throw new Error(`Template "${e}" not found`);let r=this.interpolate(s.subject,t),i=this.interpolate(s.html,t),a=s.text?this.interpolate(s.text,t):void 0;return{subject:r,html:i,text:a}}async get(e){return this.templates.get(e)||null}async list(e){let t=Array.from(this.templates.values());return e&&(t=t.filter(s=>s.category===e)),t}async update(e,t){let s=this.templates.get(e);return s?(Object.assign(s,t,{updatedAt:Date.now()}),s):null}async delete(e){return this.templates.delete(e)}registerDefaults(){this.templates.set("welcome",{id:q(),name:"welcome",subject:"Welcome to {{appName}}, {{user.name}}!",html:`
58
58
  <h1>Welcome, {{user.name}}!</h1>
59
59
  <p>Thank you for joining {{appName}}.</p>
60
60
  <p>Your account has been created with the email: <strong>{{user.email}}</strong></p>
@@ -110,21 +110,21 @@ This code expires in {{expiresMinutes}} minutes.`,variables:["appName","user.nam
110
110
  <p>Your {{plan.name}} subscription has been canceled.</p>
111
111
  <p>You have access until {{accessUntilDate}}.</p>
112
112
  `,text:`Your {{plan.name}} subscription is canceled.
113
- Access until: {{accessUntilDate}}`,variables:["user.name","plan.name","accessUntilDate"],category:"billing",active:!0,createdAt:Date.now(),updatedAt:Date.now()})}interpolate(e,t){let s=e;return s=s.replace(/\{\{#if\s+(\w+(?:\.\w+)*)\}\}([\s\S]*?)\{\{\/if\}\}/g,(r,i,a)=>this.getNestedValue(t,i)?a:""),s=s.replace(/\{\{#each\s+(\w+(?:\.\w+)*)\}\}([\s\S]*?)\{\{\/each\}\}/g,(r,i,a)=>{let n=this.getNestedValue(t,i);return Array.isArray(n)?n.map((l,c)=>{let m={...t,this:l,$index:c};return this.interpolate(a,m)}).join(""):""}),s=s.replace(/\{\{([\w.$]+)\}\}/g,(r,i)=>{let a=this.getNestedValue(t,i);return a!=null?String(a):""}),s}getNestedValue(e,t){return t.split(".").reduce((s,r)=>s?.[r],e)}},io=S("svelar.emailTemplates",()=>new zs)});var Zs={};L(Zs,{Mailable:()=>Fe,Mailer:()=>Ys});function Gs(o){return typeof o=="string"?o:`${o.name} <${o.address}>`}function M(o){return o?Array.isArray(o)?o:[o]:[]}function fi(o){return Buffer.isBuffer(o)?o.toString("base64"):Buffer.from(o).toString("base64")}var Kt,Ks,Ws,Js,Vs,Fe,Qs,Ys,Wt=w(()=>{"use strict";E();Kt=class{async send(e){let t=M(e.to);return console.log(`[Mail] To: ${t.join(", ")} | Subject: ${e.subject}`),e.text&&console.log(`[Mail] Body: ${e.text.slice(0,200)}`),{accepted:t,rejected:[]}}},Ks=class{async send(e){return{accepted:M(e.to),rejected:[]}}},Ws=class{constructor(e){this.config=e}async send(e){try{let r=await(await import("nodemailer")).createTransport({host:this.config.host,port:this.config.port??587,secure:this.config.secure??!1,auth:this.config.auth}).sendMail({from:e.from?Gs(e.from):void 0,to:M(e.to).join(", "),cc:M(e.cc).join(", ")||void 0,bcc:M(e.bcc).join(", ")||void 0,replyTo:e.replyTo,subject:e.subject,text:e.text,html:e.html,attachments:e.attachments});return{accepted:r.accepted,rejected:r.rejected,messageId:r.messageId}}catch(t){throw t.code==="MODULE_NOT_FOUND"?new Error("SMTP driver requires nodemailer. Install: npm install nodemailer"):t}}},Js=class{constructor(e){this.config=e}async send(e){let t=this.config.apiToken;if(!t)throw new Error("Postmark apiToken is required. Set it in your mailer config or POSTMARK_API_TOKEN env var.");let s=M(e.to),r=M(e.cc),i=M(e.bcc),a={From:e.from?Gs(e.from):void 0,To:s.join(", "),Subject:e.subject,MessageStream:this.config.messageStream||"outbound"};r.length>0&&(a.Cc=r.join(", ")),i.length>0&&(a.Bcc=i.join(", ")),e.replyTo&&(a.ReplyTo=e.replyTo),e.html&&(a.HtmlBody=e.html),e.text&&(a.TextBody=e.text),!a.HtmlBody&&!a.TextBody&&(a.TextBody=""),e.tags&&(a.Tag=Object.values(e.tags)[0]),e.attachments?.length&&(a.Attachments=e.attachments.map(c=>({Name:c.filename,Content:fi(c.content),ContentType:c.contentType||"application/octet-stream"})));let n=await fetch("https://api.postmarkapp.com/email",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-Postmark-Server-Token":t},body:JSON.stringify(a)});if(!n.ok){let c=await n.json().catch(()=>({Message:n.statusText}));throw new Error(`Postmark error ${n.status}: ${c.Message||JSON.stringify(c)}`)}let l=await n.json();return{accepted:s,rejected:[],messageId:l.MessageID}}},Vs=class{constructor(e){this.config=e}async send(e){let t=this.config.apiKey;if(!t)throw new Error("Resend apiKey is required. Set it in your mailer config or RESEND_API_KEY env var.");let s=M(e.to),r=M(e.cc),i=M(e.bcc),a={from:e.from?Gs(e.from):void 0,to:s,subject:e.subject};r.length>0&&(a.cc=r),i.length>0&&(a.bcc=i),e.replyTo&&(a.reply_to=[e.replyTo]),e.html&&(a.html=e.html),e.text&&(a.text=e.text),e.tags&&(a.tags=Object.entries(e.tags).map(([c,m])=>({name:c,value:m}))),e.attachments?.length&&(a.attachments=e.attachments.map(c=>({filename:c.filename,content:fi(c.content),content_type:c.contentType||"application/octet-stream"})));let n=await fetch("https://api.resend.com/emails",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(a)});if(!n.ok){let c=await n.json().catch(()=>({message:n.statusText}));throw new Error(`Resend error ${n.status}: ${c.message||JSON.stringify(c)}`)}let l=await n.json();return{accepted:s,rejected:[],messageId:l.id}}},Fe=class{message={};to(e){return this.message.to=e,this}cc(e){return this.message.cc=e,this}bcc(e){return this.message.bcc=e,this}from(e){return this.message.from=e,this}replyTo(e){return this.message.replyTo=e,this}subject(e){return this.message.subject=e,this}text(e){return this.message.text=e,this}html(e){return this.message.html=e,this}attach(e,t,s){return this.message.attachments||(this.message.attachments=[]),this.message.attachments.push({filename:e,content:t,contentType:s}),this}tag(e,t){return this.message.tags||(this.message.tags={}),this.message.tags[e]=t,this}toMessage(){return this.message}},Qs=class{config=null;transports=new Map;configure(e){this.config=e,this.transports.clear()}async send(e,t){let s=this.resolveTransport(t);return!e.from&&this.config?.from&&(e.from=this.config.from),s.send(e)}async sendMailable(e,t){e.build();let s=e.toMessage();return!s.from&&this.config?.from&&(s.from=this.config.from),this.send(s,t)}mailer(e){let t=this.resolveTransport(e);return{send:s=>(!s.from&&this.config?.from&&(s.from=this.config.from),t.send(s))}}resolveTransport(e){let t=e??this.config?.default??"log";if(this.transports.has(t))return this.transports.get(t);if(!this.config){let i=new Kt;return this.transports.set(t,i),i}let s=this.config.mailers[t];if(!s)throw new Error(`Mailer "${t}" is not defined.`);let r;switch(s.driver){case"smtp":r=new Ws(s);break;case"postmark":r=new Js(s);break;case"resend":r=new Vs(s);break;case"log":r=new Kt;break;case"null":r=new Ks;break;case"custom":{if(!s.transport)throw new Error(`Custom mail driver "${t}" requires a "transport" instance.`);r=s.transport;break}default:throw new Error(`Unknown mail driver: ${s.driver}`)}return this.transports.set(t,r),r}},Ys=S("svelar.mail",()=>new Qs)});import{createHmac as fe,randomBytes as Be}from"crypto";function bi(o){return(typeof o=="string"?Buffer.from(o):o).toString("base64url")}function yi(o){return Buffer.from(o,"base64url").toString("utf-8")}function vi(o,e,t,s){return fe(s==="HS384"?"sha384":s==="HS512"?"sha512":"sha256",t).update(`${o}.${e}`).digest("base64url")}function Xs(o,e,t="HS256"){let s=bi(JSON.stringify({alg:t,typ:"JWT"})),r=bi(JSON.stringify(o)),i=vi(s,r,e,t);return`${s}.${r}.${i}`}function er(o,e){let t=o.split(".");if(t.length!==3)return null;let[s,r,i]=t,a;try{a=JSON.parse(yi(s))}catch{return null}let n=vi(s,r,e,a.alg);if(i!==n)return null;try{let l=JSON.parse(yi(r));return l.exp&&Date.now()/1e3>l.exp?null:l}catch{return null}}var Jt,be,Vt,tr=w(()=>{"use strict";ue();Jt=class{config;currentUser=null;constructor(e){this.config={identifierColumn:"email",passwordColumn:"password",...e}}async attempt(e,t){let{Hash:s}=await Promise.resolve().then(()=>(ge(),Ue)),r=e[this.config.identifierColumn],i=e[this.config.passwordColumn];if(!r||!i)return null;let a=await this.config.model.where(this.config.identifierColumn,r).first();if(!a)return null;let n=a.getAttribute(this.config.passwordColumn);return await s.verify(i,n)?(this.currentUser=a,t&&(t.set("auth_user_id",a.getAttribute("id")),t.regenerateId()),a):null}async attemptJwt(e){let{Hash:t}=await Promise.resolve().then(()=>(ge(),Ue));if(!this.config.jwt)throw new Error("JWT configuration required for JWT guard.");let s=e[this.config.identifierColumn],r=e[this.config.passwordColumn];if(!s||!r)return null;let i=await this.config.model.where(this.config.identifierColumn,s).first();if(!i)return null;let a=i.getAttribute(this.config.passwordColumn);return await t.verify(r,a)?(this.currentUser=i,this.issueTokenPair(i)):null}async issueTokenPair(e){let t=this.config.jwt,s=t.expiresIn??3600,r=Math.floor(Date.now()/1e3),i={sub:e.getAttribute("id"),iat:r,exp:r+s,...t.issuer?{iss:t.issuer}:{}},a=Xs(i,t.secret,t.algorithm),n=new Date((r+s)*1e3),l={user:e,token:a,expiresAt:n};if(t.refreshTokens){let c=t.refreshExpiresIn??604800,m=Be(32).toString("base64url"),p=fe("sha256",t.secret).update(m).digest("hex"),h=new Date((r+c)*1e3),{Connection:u}=await Promise.resolve().then(()=>(P(),R)),b=t.refreshTable??"refresh_tokens";await u.raw(`INSERT INTO ${b} (user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?)`,[e.getAttribute("id"),p,h.toISOString(),new Date().toISOString()]),l.refreshToken=m,l.refreshExpiresAt=h}return l}async refreshJwt(e){if(!this.config.jwt)throw new Error("JWT configuration required.");if(!this.config.jwt.refreshTokens)throw new Error("Refresh tokens are not enabled. Set jwt.refreshTokens = true.");let t=this.config.jwt,s=fe("sha256",t.secret).update(e).digest("hex"),{Connection:r}=await Promise.resolve().then(()=>(P(),R)),i=t.refreshTable??"refresh_tokens",a=await r.raw(`SELECT user_id, expires_at, revoked_at FROM ${i} WHERE token = ?`,[s]);if(a.length===0)return null;let n=a[0];if(n.revoked_at||new Date(n.expires_at)<new Date)return null;await r.raw(`UPDATE ${i} SET revoked_at = ? WHERE token = ?`,[new Date().toISOString(),s]);let l=await this.config.model.find(n.user_id);return l?(this.currentUser=l,this.issueTokenPair(l)):null}async revokeRefreshTokens(e){if(!this.config.jwt?.refreshTokens)return;let{Connection:t}=await Promise.resolve().then(()=>(P(),R)),s=this.config.jwt.refreshTable??"refresh_tokens";await t.raw(`UPDATE ${s} SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL`,[new Date().toISOString(),e])}async resolveFromToken(e){if(!this.config.jwt)throw new Error("JWT configuration required.");let t=er(e,this.config.jwt.secret);if(!t)return null;let s=await this.config.model.find(t.sub);return s&&(this.currentUser=s),s}async resolveFromSession(e){let t=e.get("auth_user_id");if(!t)return null;let s=await this.config.model.find(t);return s&&(this.currentUser=s),s}async register(e){let{Hash:t}=await Promise.resolve().then(()=>(ge(),Ue));e[this.config.passwordColumn]&&(e[this.config.passwordColumn]=await t.make(e[this.config.passwordColumn]));let s=await this.config.model.create(e);return this.currentUser=s,s}async logout(e){this.currentUser=null,e&&(e.forget("auth_user_id"),e.regenerateId())}user(){return this.currentUser}check(){return this.currentUser!==null}id(){return this.currentUser?.getAttribute("id")??null}async generateApiToken(e,t="default"){let s=Be(32).toString("hex"),r=this.config.jwt?.secret??process.env.APP_KEY;if(!r)throw new Error("APP_KEY is not set. Set it in your .env file or pass jwt.secret in auth config.");let i=fe("sha256",r).update(s).digest("hex"),{Connection:a}=await Promise.resolve().then(()=>(P(),R)),n=this.config.token?.table??"personal_access_tokens";return await a.raw(`INSERT INTO ${n} (user_id, name, token, created_at) VALUES (?, ?, ?, ?)`,[e.getAttribute("id"),t,i,new Date().toISOString()]),s}async resolveFromApiToken(e){let{Connection:t}=await Promise.resolve().then(()=>(P(),R)),s=this.config.token?.table??"personal_access_tokens",r=this.config.jwt?.secret??process.env.APP_KEY;if(!r)throw new Error("APP_KEY is not set. Set it in your .env file or pass jwt.secret in auth config.");let i=fe("sha256",r).update(e).digest("hex"),a=await t.raw(`SELECT user_id FROM ${s} WHERE token = ?`,[i]);if(a.length===0)return null;let n=await this.config.model.find(a[0].user_id);return n&&(this.currentUser=n),n}async sendPasswordReset(e){let t=await this.config.model.where(this.config.identifierColumn,e).first();if(!t)return!1;let{Connection:s}=await Promise.resolve().then(()=>(P(),R)),r=this.config.passwordResets?.table??"password_resets",i=this.config.passwordResets?.expiresIn??3600;await this.ensureTable(r,`
113
+ Access until: {{accessUntilDate}}`,variables:["user.name","plan.name","accessUntilDate"],category:"billing",active:!0,createdAt:Date.now(),updatedAt:Date.now()})}interpolate(e,t){let s=e;return s=s.replace(/\{\{#if\s+(\w+(?:\.\w+)*)\}\}([\s\S]*?)\{\{\/if\}\}/g,(r,i,a)=>this.getNestedValue(t,i)?a:""),s=s.replace(/\{\{#each\s+(\w+(?:\.\w+)*)\}\}([\s\S]*?)\{\{\/each\}\}/g,(r,i,a)=>{let n=this.getNestedValue(t,i);return Array.isArray(n)?n.map((l,c)=>{let m={...t,this:l,$index:c};return this.interpolate(a,m)}).join(""):""}),s=s.replace(/\{\{([\w.$]+)\}\}/g,(r,i)=>{let a=this.getNestedValue(t,i);return a!=null?String(a):""}),s}getNestedValue(e,t){return t.split(".").reduce((s,r)=>s?.[r],e)}},yo=P("svelar.emailTemplates",()=>new Ws)});var er={};L(er,{Mailable:()=>Fe,Mailer:()=>Xs});function Zs(o){return typeof o=="string"?o:`${o.name} <${o.address}>`}function M(o){return o?Array.isArray(o)?o:[o]:[]}function wi(o){return Buffer.isBuffer(o)?o.toString("base64"):Buffer.from(o).toString("base64")}var Jt,Js,Vs,Qs,Gs,Fe,Ys,Xs,Vt=C(()=>{"use strict";E();Jt=class{async send(e){let t=M(e.to);return console.log(`[Mail] To: ${t.join(", ")} | Subject: ${e.subject}`),e.text&&console.log(`[Mail] Body: ${e.text.slice(0,200)}`),{accepted:t,rejected:[]}}},Js=class{async send(e){return{accepted:M(e.to),rejected:[]}}},Vs=class{constructor(e){this.config=e}async send(e){try{let r=await(await import("nodemailer")).createTransport({host:this.config.host,port:this.config.port??587,secure:this.config.secure??!1,auth:this.config.auth}).sendMail({from:e.from?Zs(e.from):void 0,to:M(e.to).join(", "),cc:M(e.cc).join(", ")||void 0,bcc:M(e.bcc).join(", ")||void 0,replyTo:e.replyTo,subject:e.subject,text:e.text,html:e.html,attachments:e.attachments});return{accepted:r.accepted,rejected:r.rejected,messageId:r.messageId}}catch(t){throw t.code==="MODULE_NOT_FOUND"?new Error("SMTP driver requires nodemailer. Install: npm install nodemailer"):t}}},Qs=class{constructor(e){this.config=e}async send(e){let t=this.config.apiToken;if(!t)throw new Error("Postmark apiToken is required. Set it in your mailer config or POSTMARK_API_TOKEN env var.");let s=M(e.to),r=M(e.cc),i=M(e.bcc),a={From:e.from?Zs(e.from):void 0,To:s.join(", "),Subject:e.subject,MessageStream:this.config.messageStream||"outbound"};r.length>0&&(a.Cc=r.join(", ")),i.length>0&&(a.Bcc=i.join(", ")),e.replyTo&&(a.ReplyTo=e.replyTo),e.html&&(a.HtmlBody=e.html),e.text&&(a.TextBody=e.text),!a.HtmlBody&&!a.TextBody&&(a.TextBody=""),e.tags&&(a.Tag=Object.values(e.tags)[0]),e.attachments?.length&&(a.Attachments=e.attachments.map(c=>({Name:c.filename,Content:wi(c.content),ContentType:c.contentType||"application/octet-stream"})));let n=await fetch("https://api.postmarkapp.com/email",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","X-Postmark-Server-Token":t},body:JSON.stringify(a)});if(!n.ok){let c=await n.json().catch(()=>({Message:n.statusText}));throw new Error(`Postmark error ${n.status}: ${c.Message||JSON.stringify(c)}`)}let l=await n.json();return{accepted:s,rejected:[],messageId:l.MessageID}}},Gs=class{constructor(e){this.config=e}async send(e){let t=this.config.apiKey;if(!t)throw new Error("Resend apiKey is required. Set it in your mailer config or RESEND_API_KEY env var.");let s=M(e.to),r=M(e.cc),i=M(e.bcc),a={from:e.from?Zs(e.from):void 0,to:s,subject:e.subject};r.length>0&&(a.cc=r),i.length>0&&(a.bcc=i),e.replyTo&&(a.reply_to=[e.replyTo]),e.html&&(a.html=e.html),e.text&&(a.text=e.text),e.tags&&(a.tags=Object.entries(e.tags).map(([c,m])=>({name:c,value:m}))),e.attachments?.length&&(a.attachments=e.attachments.map(c=>({filename:c.filename,content:wi(c.content),content_type:c.contentType||"application/octet-stream"})));let n=await fetch("https://api.resend.com/emails",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(a)});if(!n.ok){let c=await n.json().catch(()=>({message:n.statusText}));throw new Error(`Resend error ${n.status}: ${c.message||JSON.stringify(c)}`)}let l=await n.json();return{accepted:s,rejected:[],messageId:l.id}}},Fe=class{message={};to(e){return this.message.to=e,this}cc(e){return this.message.cc=e,this}bcc(e){return this.message.bcc=e,this}from(e){return this.message.from=e,this}replyTo(e){return this.message.replyTo=e,this}subject(e){return this.message.subject=e,this}text(e){return this.message.text=e,this}html(e){return this.message.html=e,this}attach(e,t,s){return this.message.attachments||(this.message.attachments=[]),this.message.attachments.push({filename:e,content:t,contentType:s}),this}tag(e,t){return this.message.tags||(this.message.tags={}),this.message.tags[e]=t,this}toMessage(){return this.message}},Ys=class{config=null;transports=new Map;configure(e){this.config=e,this.transports.clear()}async send(e,t){let s=this.resolveTransport(t);return!e.from&&this.config?.from&&(e.from=this.config.from),s.send(e)}async sendMailable(e,t){e.build();let s=e.toMessage();return!s.from&&this.config?.from&&(s.from=this.config.from),this.send(s,t)}mailer(e){let t=this.resolveTransport(e);return{send:s=>(!s.from&&this.config?.from&&(s.from=this.config.from),t.send(s))}}resolveTransport(e){let t=e??this.config?.default??"log";if(this.transports.has(t))return this.transports.get(t);if(!this.config){let i=new Jt;return this.transports.set(t,i),i}let s=this.config.mailers[t];if(!s)throw new Error(`Mailer "${t}" is not defined.`);let r;switch(s.driver){case"smtp":r=new Vs(s);break;case"postmark":r=new Qs(s);break;case"resend":r=new Gs(s);break;case"log":r=new Jt;break;case"null":r=new Js;break;case"custom":{if(!s.transport)throw new Error(`Custom mail driver "${t}" requires a "transport" instance.`);r=s.transport;break}default:throw new Error(`Unknown mail driver: ${s.driver}`)}return this.transports.set(t,r),r}},Xs=P("svelar.mail",()=>new Ys)});import{createHmac as fe,randomBytes as Be}from"crypto";function Ci(o){return(typeof o=="string"?Buffer.from(o):o).toString("base64url")}function xi(o){return Buffer.from(o,"base64url").toString("utf-8")}function Pi(o,e,t,s){return fe(s==="HS384"?"sha384":s==="HS512"?"sha512":"sha256",t).update(`${o}.${e}`).digest("base64url")}function tr(o,e,t="HS256"){let s=Ci(JSON.stringify({alg:t,typ:"JWT"})),r=Ci(JSON.stringify(o)),i=Pi(s,r,e,t);return`${s}.${r}.${i}`}function sr(o,e){let t=o.split(".");if(t.length!==3)return null;let[s,r,i]=t,a;try{a=JSON.parse(xi(s))}catch{return null}let n=Pi(s,r,e,a.alg);if(i!==n)return null;try{let l=JSON.parse(xi(r));return l.exp&&Date.now()/1e3>l.exp?null:l}catch{return null}}var Qt,be,Gt,rr=C(()=>{"use strict";ue();Qt=class{config;currentUser=null;constructor(e){this.config={identifierColumn:"email",passwordColumn:"password",...e}}async attempt(e,t){let{Hash:s}=await Promise.resolve().then(()=>(ge(),Ue)),r=e[this.config.identifierColumn],i=e[this.config.passwordColumn];if(!r||!i)return null;let a=await this.config.model.where(this.config.identifierColumn,r).first();if(!a)return null;let n=a.getAttribute(this.config.passwordColumn);return await s.verify(i,n)?(this.currentUser=a,t&&(t.set("auth_user_id",a.getAttribute("id")),t.regenerateId()),a):null}async attemptJwt(e){let{Hash:t}=await Promise.resolve().then(()=>(ge(),Ue));if(!this.config.jwt)throw new Error("JWT configuration required for JWT guard.");let s=e[this.config.identifierColumn],r=e[this.config.passwordColumn];if(!s||!r)return null;let i=await this.config.model.where(this.config.identifierColumn,s).first();if(!i)return null;let a=i.getAttribute(this.config.passwordColumn);return await t.verify(r,a)?(this.currentUser=i,this.issueTokenPair(i)):null}async issueTokenPair(e){let t=this.config.jwt,s=t.expiresIn??3600,r=Math.floor(Date.now()/1e3),i={sub:e.getAttribute("id"),iat:r,exp:r+s,...t.issuer?{iss:t.issuer}:{}},a=tr(i,t.secret,t.algorithm),n=new Date((r+s)*1e3),l={user:e,token:a,expiresAt:n};if(t.refreshTokens){let c=t.refreshExpiresIn??604800,m=Be(32).toString("base64url"),p=fe("sha256",t.secret).update(m).digest("hex"),h=new Date((r+c)*1e3),{Connection:u}=await Promise.resolve().then(()=>(S(),R)),b=t.refreshTable??"refresh_tokens";await u.raw(`INSERT INTO ${b} (user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?)`,[e.getAttribute("id"),p,h.toISOString(),new Date().toISOString()]),l.refreshToken=m,l.refreshExpiresAt=h}return l}async refreshJwt(e){if(!this.config.jwt)throw new Error("JWT configuration required.");if(!this.config.jwt.refreshTokens)throw new Error("Refresh tokens are not enabled. Set jwt.refreshTokens = true.");let t=this.config.jwt,s=fe("sha256",t.secret).update(e).digest("hex"),{Connection:r}=await Promise.resolve().then(()=>(S(),R)),i=t.refreshTable??"refresh_tokens",a=await r.raw(`SELECT user_id, expires_at, revoked_at FROM ${i} WHERE token = ?`,[s]);if(a.length===0)return null;let n=a[0];if(n.revoked_at||new Date(n.expires_at)<new Date)return null;await r.raw(`UPDATE ${i} SET revoked_at = ? WHERE token = ?`,[new Date().toISOString(),s]);let l=await this.config.model.find(n.user_id);return l?(this.currentUser=l,this.issueTokenPair(l)):null}async revokeRefreshTokens(e){if(!this.config.jwt?.refreshTokens)return;let{Connection:t}=await Promise.resolve().then(()=>(S(),R)),s=this.config.jwt.refreshTable??"refresh_tokens";await t.raw(`UPDATE ${s} SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL`,[new Date().toISOString(),e])}async resolveFromToken(e){if(!this.config.jwt)throw new Error("JWT configuration required.");let t=sr(e,this.config.jwt.secret);if(!t)return null;let s=await this.config.model.find(t.sub);return s&&(this.currentUser=s),s}async resolveFromSession(e){let t=e.get("auth_user_id");if(!t)return null;let s=await this.config.model.find(t);return s&&(this.currentUser=s),s}async register(e){let{Hash:t}=await Promise.resolve().then(()=>(ge(),Ue));e[this.config.passwordColumn]&&(e[this.config.passwordColumn]=await t.make(e[this.config.passwordColumn]));let s=await this.config.model.create(e);return this.currentUser=s,s}async logout(e){this.currentUser=null,e&&(e.forget("auth_user_id"),e.regenerateId())}user(){return this.currentUser}check(){return this.currentUser!==null}id(){return this.currentUser?.getAttribute("id")??null}async generateApiToken(e,t="default"){let s=Be(32).toString("hex"),r=this.config.jwt?.secret??process.env.APP_KEY;if(!r)throw new Error("APP_KEY is not set. Set it in your .env file or pass jwt.secret in auth config.");let i=fe("sha256",r).update(s).digest("hex"),{Connection:a}=await Promise.resolve().then(()=>(S(),R)),n=this.config.token?.table??"personal_access_tokens";return await a.raw(`INSERT INTO ${n} (user_id, name, token, created_at) VALUES (?, ?, ?, ?)`,[e.getAttribute("id"),t,i,new Date().toISOString()]),s}async resolveFromApiToken(e){let{Connection:t}=await Promise.resolve().then(()=>(S(),R)),s=this.config.token?.table??"personal_access_tokens",r=this.config.jwt?.secret??process.env.APP_KEY;if(!r)throw new Error("APP_KEY is not set. Set it in your .env file or pass jwt.secret in auth config.");let i=fe("sha256",r).update(e).digest("hex"),a=await t.raw(`SELECT user_id FROM ${s} WHERE token = ?`,[i]);if(a.length===0)return null;let n=await this.config.model.find(a[0].user_id);return n&&(this.currentUser=n),n}async sendPasswordReset(e){let t=await this.config.model.where(this.config.identifierColumn,e).first();if(!t)return!1;let{Connection:s}=await Promise.resolve().then(()=>(S(),R)),r=this.config.passwordResets?.table??"password_resets",i=this.config.passwordResets?.expiresIn??3600;await this.ensureTable(r,`
114
114
  CREATE TABLE IF NOT EXISTS ${r} (
115
115
  email TEXT NOT NULL,
116
116
  token TEXT NOT NULL,
117
117
  expires_at TEXT NOT NULL,
118
118
  created_at TEXT NOT NULL
119
119
  )
120
- `),await s.raw(`DELETE FROM ${r} WHERE email = ?`,[e]);let a=Be(32).toString("base64url"),n=this.hashToken(a),l=new Date(Date.now()+i*1e3).toISOString();await s.raw(`INSERT INTO ${r} (email, token, expires_at, created_at) VALUES (?, ?, ?, ?)`,[e,n,l,new Date().toISOString()]);let c=this.config.appUrl??process.env.APP_URL??"http://localhost:5173",m=this.config.appName??process.env.APP_NAME??"Svelar",p=`${c}/reset-password?token=${a}&email=${encodeURIComponent(e)}`;return await this.sendAuthEmail("password-reset",e,{appName:m,"user.name":t.getAttribute("name")??e,resetUrl:p}),!0}async resetPassword(e,t,s){let{Connection:r}=await Promise.resolve().then(()=>(P(),R)),{Hash:i}=await Promise.resolve().then(()=>(ge(),Ue)),a=this.config.passwordResets?.table??"password_resets",n=this.hashToken(e),l=await r.raw(`SELECT email, expires_at FROM ${a} WHERE token = ? AND email = ?`,[n,t]);if(l.length===0)return!1;let c=l[0];if(new Date(c.expires_at)<new Date)return await r.raw(`DELETE FROM ${a} WHERE email = ?`,[t]),!1;let m=await this.config.model.where(this.config.identifierColumn,t).first();if(!m)return!1;let p=await i.make(s);return await this.config.model.where("id",m.getAttribute("id")).update({[this.config.passwordColumn]:p}),await r.raw(`DELETE FROM ${a} WHERE email = ?`,[t]),await this.revokeRefreshTokens(m.getAttribute("id")),!0}async sendVerificationEmail(e){let{Connection:t}=await Promise.resolve().then(()=>(P(),R)),s=this.config.emailVerification?.table??"email_verifications",r=this.config.emailVerification?.expiresIn??86400,i=e.getAttribute(this.config.identifierColumn);await this.ensureTable(s,`
120
+ `),await s.raw(`DELETE FROM ${r} WHERE email = ?`,[e]);let a=Be(32).toString("base64url"),n=this.hashToken(a),l=new Date(Date.now()+i*1e3).toISOString();await s.raw(`INSERT INTO ${r} (email, token, expires_at, created_at) VALUES (?, ?, ?, ?)`,[e,n,l,new Date().toISOString()]);let c=this.config.appUrl??process.env.APP_URL??"http://localhost:5173",m=this.config.appName??process.env.APP_NAME??"Svelar",p=`${c}/reset-password?token=${a}&email=${encodeURIComponent(e)}`;return await this.sendAuthEmail("password-reset",e,{appName:m,"user.name":t.getAttribute("name")??e,resetUrl:p}),!0}async resetPassword(e,t,s){let{Connection:r}=await Promise.resolve().then(()=>(S(),R)),{Hash:i}=await Promise.resolve().then(()=>(ge(),Ue)),a=this.config.passwordResets?.table??"password_resets",n=this.hashToken(e),l=await r.raw(`SELECT email, expires_at FROM ${a} WHERE token = ? AND email = ?`,[n,t]);if(l.length===0)return!1;let c=l[0];if(new Date(c.expires_at)<new Date)return await r.raw(`DELETE FROM ${a} WHERE email = ?`,[t]),!1;let m=await this.config.model.where(this.config.identifierColumn,t).first();if(!m)return!1;let p=await i.make(s);return await this.config.model.where("id",m.getAttribute("id")).update({[this.config.passwordColumn]:p}),await r.raw(`DELETE FROM ${a} WHERE email = ?`,[t]),await this.revokeRefreshTokens(m.getAttribute("id")),!0}async sendVerificationEmail(e){let{Connection:t}=await Promise.resolve().then(()=>(S(),R)),s=this.config.emailVerification?.table??"email_verifications",r=this.config.emailVerification?.expiresIn??86400,i=e.getAttribute(this.config.identifierColumn);await this.ensureTable(s,`
121
121
  CREATE TABLE IF NOT EXISTS ${s} (
122
122
  user_id TEXT NOT NULL,
123
123
  token TEXT NOT NULL,
124
124
  expires_at TEXT NOT NULL,
125
125
  created_at TEXT NOT NULL
126
126
  )
127
- `),await t.raw(`DELETE FROM ${s} WHERE user_id = ?`,[e.getAttribute("id")]);let a=Be(32).toString("base64url"),n=this.hashToken(a),l=new Date(Date.now()+r*1e3).toISOString();await t.raw(`INSERT INTO ${s} (user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?)`,[e.getAttribute("id"),n,l,new Date().toISOString()]);let m=`${this.config.appUrl??process.env.APP_URL??"http://localhost:5173"}/verify-email?token=${a}&id=${e.getAttribute("id")}`;await this.sendAuthEmail("email-verification",i,{"user.name":e.getAttribute("name")??i,verifyUrl:m})}async verifyEmail(e,t){let{Connection:s}=await Promise.resolve().then(()=>(P(),R)),r=this.config.emailVerification?.table??"email_verifications",i=this.config.emailVerification?.verifiedColumn??"email_verified_at",a=this.hashToken(e),n=await s.raw(`SELECT user_id, expires_at FROM ${r} WHERE token = ? AND user_id = ?`,[a,t]);return n.length===0?!1:new Date(n[0].expires_at)<new Date?(await s.raw(`DELETE FROM ${r} WHERE user_id = ?`,[t]),!1):(await this.config.model.where("id",t).update({[i]:new Date().toISOString()}),await s.raw(`DELETE FROM ${r} WHERE user_id = ?`,[t]),!0)}isEmailVerified(e){let t=this.config.emailVerification?.verifiedColumn??"email_verified_at";return!!e.getAttribute(t)}async sendOtp(e,t="login"){let s=await this.config.model.where(this.config.identifierColumn,e).first();if(!s)return!1;let{Connection:r}=await Promise.resolve().then(()=>(P(),R)),i=this.config.otp?.table??"otp_codes",a=this.config.otp?.expiresIn??600,n=this.config.otp?.length??6;await this.ensureTable(i,`
127
+ `),await t.raw(`DELETE FROM ${s} WHERE user_id = ?`,[e.getAttribute("id")]);let a=Be(32).toString("base64url"),n=this.hashToken(a),l=new Date(Date.now()+r*1e3).toISOString();await t.raw(`INSERT INTO ${s} (user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?)`,[e.getAttribute("id"),n,l,new Date().toISOString()]);let m=`${this.config.appUrl??process.env.APP_URL??"http://localhost:5173"}/verify-email?token=${a}&id=${e.getAttribute("id")}`;await this.sendAuthEmail("email-verification",i,{"user.name":e.getAttribute("name")??i,verifyUrl:m})}async verifyEmail(e,t){let{Connection:s}=await Promise.resolve().then(()=>(S(),R)),r=this.config.emailVerification?.table??"email_verifications",i=this.config.emailVerification?.verifiedColumn??"email_verified_at",a=this.hashToken(e),n=await s.raw(`SELECT user_id, expires_at FROM ${r} WHERE token = ? AND user_id = ?`,[a,t]);return n.length===0?!1:new Date(n[0].expires_at)<new Date?(await s.raw(`DELETE FROM ${r} WHERE user_id = ?`,[t]),!1):(await this.config.model.where("id",t).update({[i]:new Date().toISOString()}),await s.raw(`DELETE FROM ${r} WHERE user_id = ?`,[t]),!0)}isEmailVerified(e){let t=this.config.emailVerification?.verifiedColumn??"email_verified_at";return!!e.getAttribute(t)}async sendOtp(e,t="login"){let s=await this.config.model.where(this.config.identifierColumn,e).first();if(!s)return!1;let{Connection:r}=await Promise.resolve().then(()=>(S(),R)),i=this.config.otp?.table??"otp_codes",a=this.config.otp?.expiresIn??600,n=this.config.otp?.length??6;await this.ensureTable(i,`
128
128
  CREATE TABLE IF NOT EXISTS ${i} (
129
129
  email TEXT NOT NULL,
130
130
  code TEXT NOT NULL,
@@ -133,12 +133,12 @@ Access until: {{accessUntilDate}}`,variables:["user.name","plan.name","accessUnt
133
133
  used_at TEXT,
134
134
  created_at TEXT NOT NULL
135
135
  )
136
- `),await r.raw(`DELETE FROM ${i} WHERE email = ? AND purpose = ?`,[e,t]);let l=this.generateOtpCode(n),c=this.hashToken(l),m=new Date(Date.now()+a*1e3).toISOString();await r.raw(`INSERT INTO ${i} (email, code, purpose, expires_at, created_at) VALUES (?, ?, ?, ?, ?)`,[e,c,t,m,new Date().toISOString()]);let p=this.config.appName??process.env.APP_NAME??"Svelar",h=Math.ceil(a/60);return await this.sendAuthEmail("otp-code",e,{appName:p,"user.name":s.getAttribute("name")??e,code:l,purpose:t,expiresMinutes:String(h)}),!0}async verifyOtp(e,t,s="login"){let{Connection:r}=await Promise.resolve().then(()=>(P(),R)),i=this.config.otp?.table??"otp_codes",a=this.hashToken(t),n=await r.raw(`SELECT email, expires_at, used_at FROM ${i} WHERE code = ? AND email = ? AND purpose = ? AND used_at IS NULL`,[a,e,s]);if(n.length===0)return null;if(new Date(n[0].expires_at)<new Date)return await r.raw(`DELETE FROM ${i} WHERE email = ? AND purpose = ?`,[e,s]),null;await r.raw(`UPDATE ${i} SET used_at = ? WHERE code = ? AND email = ? AND purpose = ?`,[new Date().toISOString(),a,e,s]);let l=await this.config.model.where(this.config.identifierColumn,e).first();return l&&(this.currentUser=l),l}async attemptOtp(e,t,s,r="login"){let i=await this.verifyOtp(e,t,r);return i?(s&&(s.set("auth_user_id",i.getAttribute("id")),s.regenerateId()),i):null}async cleanupExpiredTokens(){let{Connection:e}=await Promise.resolve().then(()=>(P(),R)),t=new Date().toISOString(),s=0,r=0,i=0,a=this.config.passwordResets?.table??"password_resets",n=this.config.emailVerification?.table??"email_verifications",l=this.config.otp?.table??"otp_codes";try{s=(await e.raw(`DELETE FROM ${a} WHERE expires_at < ?`,[t]))?.changes??0}catch{}try{r=(await e.raw(`DELETE FROM ${n} WHERE expires_at < ?`,[t]))?.changes??0}catch{}try{i=(await e.raw(`DELETE FROM ${l} WHERE expires_at < ? OR used_at IS NOT NULL`,[t]))?.changes??0}catch{}return{passwordResets:s,verifications:r,otpCodes:i}}hashToken(e){let t=this.config.jwt?.secret??process.env.APP_KEY;if(!t)throw new Error("APP_KEY is not set. Set it in your .env file or pass jwt.secret in auth config.");return fe("sha256",t).update(e).digest("hex")}generateOtpCode(e){let t=Be(e);return Array.from(t).map(s=>(s%10).toString()).join("")}tablesEnsured=new Set;async ensureTable(e,t){if(this.tablesEnsured.has(e))return;let{Connection:s}=await Promise.resolve().then(()=>(P(),R));await s.raw(t),this.tablesEnsured.add(e)}async sendAuthEmail(e,t,s){try{let{EmailTemplates:r}=await Promise.resolve().then(()=>(gi(),hi)),{Mailer:i}=await Promise.resolve().then(()=>(Wt(),Zs)),a=await r.render(e,s);await i.send({to:t,subject:a.subject,html:a.html,text:a.text})}catch(r){console.error(`[Auth] Failed to send ${e} email to ${t}:`,r.message)}}},be=class extends ${constructor(t){super();this.authManager=t}async handle(t,s){let r=null;if(t.event.locals.session&&(r=await this.authManager.resolveFromSession(t.event.locals.session)),!r){let i=t.event.request.headers.get("authorization");if(i?.startsWith("Bearer ")){let a=i.slice(7);try{r=await this.authManager.resolveFromToken(a)}catch{r=await this.authManager.resolveFromApiToken(a)}}}return t.event.locals.user=r,t.event.locals.auth=this.authManager,s()}},Vt=class extends ${async handle(e,t){return e.event.locals.user?t():new Response(JSON.stringify({message:"Unauthenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}}});import{appendFile as ao,mkdir as no}from"fs/promises";import{dirname as oo}from"path";function O(){return new Date().toISOString()}var Qt,He,sr,rr,ir,ar,nr,Gt,or=w(()=>{"use strict";E();Qt={debug:0,info:1,warn:2,error:3,fatal:4},He=class{minLevel;format;constructor(e){this.minLevel=e.level??"debug",this.format=e.format??"text"}write(e){if(Qt[e.level]<Qt[this.minLevel])return;if(this.format==="json"){console.log(JSON.stringify(e));return}let t={debug:"\x1B[90m",info:"\x1B[34m",warn:"\x1B[33m",error:"\x1B[31m",fatal:"\x1B[35m"},s="\x1B[0m",r=t[e.level]??"",i=e.level.toUpperCase().padEnd(5),a=Object.keys(e.context).length>0?` ${JSON.stringify(e.context)}`:"",n=e.level==="error"||e.level==="fatal"?"error":"log";console[n](`${r}[${e.timestamp}] ${i}${s} ${e.message}${a}`)}},sr=class{minLevel;path;format;initialized=!1;constructor(e){this.minLevel=e.level??"info",this.path=e.path??"storage/logs/app.log",this.format=e.format??"text"}async write(e){if(Qt[e.level]<Qt[this.minLevel])return;this.initialized||(await no(oo(this.path),{recursive:!0}),this.initialized=!0);let t;if(this.format==="json")t=JSON.stringify(e)+`
136
+ `),await r.raw(`DELETE FROM ${i} WHERE email = ? AND purpose = ?`,[e,t]);let l=this.generateOtpCode(n),c=this.hashToken(l),m=new Date(Date.now()+a*1e3).toISOString();await r.raw(`INSERT INTO ${i} (email, code, purpose, expires_at, created_at) VALUES (?, ?, ?, ?, ?)`,[e,c,t,m,new Date().toISOString()]);let p=this.config.appName??process.env.APP_NAME??"Svelar",h=Math.ceil(a/60);return await this.sendAuthEmail("otp-code",e,{appName:p,"user.name":s.getAttribute("name")??e,code:l,purpose:t,expiresMinutes:String(h)}),!0}async verifyOtp(e,t,s="login"){let{Connection:r}=await Promise.resolve().then(()=>(S(),R)),i=this.config.otp?.table??"otp_codes",a=this.hashToken(t),n=await r.raw(`SELECT email, expires_at, used_at FROM ${i} WHERE code = ? AND email = ? AND purpose = ? AND used_at IS NULL`,[a,e,s]);if(n.length===0)return null;if(new Date(n[0].expires_at)<new Date)return await r.raw(`DELETE FROM ${i} WHERE email = ? AND purpose = ?`,[e,s]),null;await r.raw(`UPDATE ${i} SET used_at = ? WHERE code = ? AND email = ? AND purpose = ?`,[new Date().toISOString(),a,e,s]);let l=await this.config.model.where(this.config.identifierColumn,e).first();return l&&(this.currentUser=l),l}async attemptOtp(e,t,s,r="login"){let i=await this.verifyOtp(e,t,r);return i?(s&&(s.set("auth_user_id",i.getAttribute("id")),s.regenerateId()),i):null}async cleanupExpiredTokens(){let{Connection:e}=await Promise.resolve().then(()=>(S(),R)),t=new Date().toISOString(),s=0,r=0,i=0,a=this.config.passwordResets?.table??"password_resets",n=this.config.emailVerification?.table??"email_verifications",l=this.config.otp?.table??"otp_codes";try{s=(await e.raw(`DELETE FROM ${a} WHERE expires_at < ?`,[t]))?.changes??0}catch{}try{r=(await e.raw(`DELETE FROM ${n} WHERE expires_at < ?`,[t]))?.changes??0}catch{}try{i=(await e.raw(`DELETE FROM ${l} WHERE expires_at < ? OR used_at IS NOT NULL`,[t]))?.changes??0}catch{}return{passwordResets:s,verifications:r,otpCodes:i}}hashToken(e){let t=this.config.jwt?.secret??process.env.APP_KEY;if(!t)throw new Error("APP_KEY is not set. Set it in your .env file or pass jwt.secret in auth config.");return fe("sha256",t).update(e).digest("hex")}generateOtpCode(e){let t=Be(e);return Array.from(t).map(s=>(s%10).toString()).join("")}tablesEnsured=new Set;async ensureTable(e,t){if(this.tablesEnsured.has(e))return;let{Connection:s}=await Promise.resolve().then(()=>(S(),R));await s.raw(t),this.tablesEnsured.add(e)}async sendAuthEmail(e,t,s){try{let{EmailTemplates:r}=await Promise.resolve().then(()=>(vi(),yi)),{Mailer:i}=await Promise.resolve().then(()=>(Vt(),er)),a=await r.render(e,s);await i.send({to:t,subject:a.subject,html:a.html,text:a.text})}catch(r){console.error(`[Auth] Failed to send ${e} email to ${t}:`,r.message)}}},be=class extends ${constructor(t){super();this.authManager=t}async handle(t,s){let r=null;if(t.event.locals.session&&(r=await this.authManager.resolveFromSession(t.event.locals.session)),!r){let i=t.event.request.headers.get("authorization");if(i?.startsWith("Bearer ")){let a=i.slice(7);try{r=await this.authManager.resolveFromToken(a)}catch{r=await this.authManager.resolveFromApiToken(a)}}}return t.event.locals.user=r,t.event.locals.auth=this.authManager,s()}},Gt=class extends ${async handle(e,t){return e.event.locals.user?t():new Response(JSON.stringify({message:"Unauthenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}}});import{appendFile as vo,mkdir as wo}from"fs/promises";import{dirname as Co}from"path";function O(){return new Date().toISOString()}var Yt,He,ir,ar,nr,or,lr,Zt,cr=C(()=>{"use strict";E();Yt={debug:0,info:1,warn:2,error:3,fatal:4},He=class{minLevel;format;constructor(e){this.minLevel=e.level??"debug",this.format=e.format??"text"}write(e){if(Yt[e.level]<Yt[this.minLevel])return;if(this.format==="json"){console.log(JSON.stringify(e));return}let t={debug:"\x1B[90m",info:"\x1B[34m",warn:"\x1B[33m",error:"\x1B[31m",fatal:"\x1B[35m"},s="\x1B[0m",r=t[e.level]??"",i=e.level.toUpperCase().padEnd(5),a=Object.keys(e.context).length>0?` ${JSON.stringify(e.context)}`:"",n=e.level==="error"||e.level==="fatal"?"error":"log";console[n](`${r}[${e.timestamp}] ${i}${s} ${e.message}${a}`)}},ir=class{minLevel;path;format;initialized=!1;constructor(e){this.minLevel=e.level??"info",this.path=e.path??"storage/logs/app.log",this.format=e.format??"text"}async write(e){if(Yt[e.level]<Yt[this.minLevel])return;this.initialized||(await wo(Co(this.path),{recursive:!0}),this.initialized=!0);let t;if(this.format==="json")t=JSON.stringify(e)+`
137
137
  `;else{let s=e.level.toUpperCase().padEnd(5),r=Object.keys(e.context).length>0?` ${JSON.stringify(e.context)}`:"";t=`[${e.timestamp}] ${s} ${e.message}${r}
138
- `}await ao(this.path,t)}},rr=class{minLevel="debug";channelNames;resolver;constructor(e,t){this.channelNames=e.channels??[],this.resolver=t,this.minLevel=e.level??"debug"}async write(e){for(let t of this.channelNames){let s=this.resolver(t);s&&await s.write(e)}}},ir=class{minLevel="debug";write(){}},ar=class{config={default:"console",channels:{console:{driver:"console",level:"debug"}}};channels=new Map;configure(e){this.config=e,this.channels.clear()}channel(e){return new nr(this.resolveChannel(e))}debug(e,t={}){this.writeToDefault({level:"debug",message:e,context:t,timestamp:O()})}info(e,t={}){this.writeToDefault({level:"info",message:e,context:t,timestamp:O()})}warn(e,t={}){this.writeToDefault({level:"warn",message:e,context:t,timestamp:O()})}error(e,t={}){this.writeToDefault({level:"error",message:e,context:t,timestamp:O()})}fatal(e,t={}){this.writeToDefault({level:"fatal",message:e,context:t,timestamp:O()})}writeToDefault(e){this.resolveChannel(this.config.default).write(e)}resolveChannel(e){if(this.channels.has(e))return this.channels.get(e);let t=this.config.channels[e];if(!t){let r=new He({driver:"console"});return this.channels.set(e,r),r}let s=this.createChannel(t);return this.channels.set(e,s),s}createChannel(e){switch(e.driver){case"console":return new He(e);case"file":return new sr(e);case"stack":return new rr(e,t=>this.resolveChannel(t));case"null":return new ir;default:return new He(e)}}},nr=class{constructor(e){this.channel=e}debug(e,t={}){this.channel.write({level:"debug",message:e,context:t,timestamp:O()})}info(e,t={}){this.channel.write({level:"info",message:e,context:t,timestamp:O()})}warn(e,t={}){this.channel.write({level:"warn",message:e,context:t,timestamp:O()})}error(e,t={}){this.channel.write({level:"error",message:e,context:t,timestamp:O()})}fatal(e,t={}){this.channel.write({level:"fatal",message:e,context:t,timestamp:O()})}};Gt=S("svelar.log",()=>new ar)});function es(o,e){throw new N(o,e??lo(o))}function wi(o,e,t){o&&es(e,t)}function Ci(o,e,t){o||es(e,t)}function lo(o){return{400:"Bad request",401:"Unauthenticated",403:"Forbidden",404:"Not found",405:"Method not allowed",409:"Conflict",419:"Page expired",422:"Unprocessable entity",429:"Too many requests",500:"Internal server error",502:"Bad gateway",503:"Service unavailable",504:"Gateway timeout"}[o]??"An error occurred"}var N,Yt,lr,cr,Zt,Xt,ye,dr=w(()=>{"use strict";or();N=class extends Error{constructor(t,s,r){super(s);this.statusCode=t;this.details=r;this.name="HttpError"}},Yt=class extends N{constructor(e="The requested resource was not found"){super(404,e),this.name="NotFoundError"}},lr=class extends N{constructor(e="Unauthenticated"){super(401,e),this.name="UnauthorizedError"}},cr=class extends N{constructor(e="You do not have permission to perform this action"){super(403,e),this.name="ForbiddenError"}},Zt=class extends N{constructor(t,s="The given data was invalid"){super(422,s,{errors:t});this.errors=t;this.name="ValidationError"}},Xt=class extends Yt{constructor(e,t){super(t?`${e} with ID ${t} not found`:`${e} not found`),this.name="ModelNotFoundError"}};ye=class{config;constructor(e={}){this.config={debug:process.env.NODE_ENV!=="production",dontReport:[Zt,Yt,lr,cr],...e}}async handle(e,t){let s=e instanceof Error?e:new Error(String(e));return await this.reportError(s,t),this.config.render?this.config.render(s,t):this.renderError(s)}handleSvelteKitError(){return({error:e,event:t,status:s,message:r})=>{let i=e instanceof Error?e:new Error(String(e));return this.reportError(i,t),i instanceof N?{message:i.message,status:i.statusCode,...i.details??{},...this.config.debug?{stack:i.stack}:{}}:{message:this.config.debug?i.message:"An unexpected error occurred",status:s,...this.config.debug?{stack:i.stack}:{}}}}middleware(){let e=this;return async(t,s)=>{try{return await s()}catch(r){return e.handle(r,t.event)}}}async reportError(e,t){if(this.config.dontReport){for(let r of this.config.dontReport)if(e instanceof r)return}let s={error:e.name,...t?.url?{url:t.url.toString()}:{},...e.stack?{stack:e.stack}:{}};if(Gt.error(e.message,s),this.config.report)try{await this.config.report(e,t?{url:t.url?.toString()}:void 0)}catch{}}renderError(e){if(e instanceof N){let s={message:e.message};return e instanceof Zt&&(s.errors=e.errors),e.details&&Object.assign(s,e.details),this.config.debug&&(s.exception=e.name,s.stack=e.stack?.split(`
138
+ `}await vo(this.path,t)}},ar=class{minLevel="debug";channelNames;resolver;constructor(e,t){this.channelNames=e.channels??[],this.resolver=t,this.minLevel=e.level??"debug"}async write(e){for(let t of this.channelNames){let s=this.resolver(t);s&&await s.write(e)}}},nr=class{minLevel="debug";write(){}},or=class{config={default:"console",channels:{console:{driver:"console",level:"debug"}}};channels=new Map;configure(e){this.config=e,this.channels.clear()}channel(e){return new lr(this.resolveChannel(e))}debug(e,t={}){this.writeToDefault({level:"debug",message:e,context:t,timestamp:O()})}info(e,t={}){this.writeToDefault({level:"info",message:e,context:t,timestamp:O()})}warn(e,t={}){this.writeToDefault({level:"warn",message:e,context:t,timestamp:O()})}error(e,t={}){this.writeToDefault({level:"error",message:e,context:t,timestamp:O()})}fatal(e,t={}){this.writeToDefault({level:"fatal",message:e,context:t,timestamp:O()})}writeToDefault(e){this.resolveChannel(this.config.default).write(e)}resolveChannel(e){if(this.channels.has(e))return this.channels.get(e);let t=this.config.channels[e];if(!t){let r=new He({driver:"console"});return this.channels.set(e,r),r}let s=this.createChannel(t);return this.channels.set(e,s),s}createChannel(e){switch(e.driver){case"console":return new He(e);case"file":return new ir(e);case"stack":return new ar(e,t=>this.resolveChannel(t));case"null":return new nr;default:return new He(e)}}},lr=class{constructor(e){this.channel=e}debug(e,t={}){this.channel.write({level:"debug",message:e,context:t,timestamp:O()})}info(e,t={}){this.channel.write({level:"info",message:e,context:t,timestamp:O()})}warn(e,t={}){this.channel.write({level:"warn",message:e,context:t,timestamp:O()})}error(e,t={}){this.channel.write({level:"error",message:e,context:t,timestamp:O()})}fatal(e,t={}){this.channel.write({level:"fatal",message:e,context:t,timestamp:O()})}};Zt=P("svelar.log",()=>new or)});function ss(o,e){throw new N(o,e??xo(o))}function Si(o,e,t){o&&ss(e,t)}function Ri(o,e,t){o||ss(e,t)}function xo(o){return{400:"Bad request",401:"Unauthenticated",403:"Forbidden",404:"Not found",405:"Method not allowed",409:"Conflict",419:"Page expired",422:"Unprocessable entity",429:"Too many requests",500:"Internal server error",502:"Bad gateway",503:"Service unavailable",504:"Gateway timeout"}[o]??"An error occurred"}var N,Xt,dr,ur,es,ts,ye,mr=C(()=>{"use strict";cr();N=class extends Error{constructor(t,s,r){super(s);this.statusCode=t;this.details=r;this.name="HttpError"}},Xt=class extends N{constructor(e="The requested resource was not found"){super(404,e),this.name="NotFoundError"}},dr=class extends N{constructor(e="Unauthenticated"){super(401,e),this.name="UnauthorizedError"}},ur=class extends N{constructor(e="You do not have permission to perform this action"){super(403,e),this.name="ForbiddenError"}},es=class extends N{constructor(t,s="The given data was invalid"){super(422,s,{errors:t});this.errors=t;this.name="ValidationError"}},ts=class extends Xt{constructor(e,t){super(t?`${e} with ID ${t} not found`:`${e} not found`),this.name="ModelNotFoundError"}};ye=class{config;constructor(e={}){this.config={debug:process.env.NODE_ENV!=="production",dontReport:[es,Xt,dr,ur],...e}}async handle(e,t){let s=e instanceof Error?e:new Error(String(e));return await this.reportError(s,t),this.config.render?this.config.render(s,t):this.renderError(s)}handleSvelteKitError(){return({error:e,event:t,status:s,message:r})=>{let i=e instanceof Error?e:new Error(String(e));return this.reportError(i,t),i instanceof N?{message:i.message,status:i.statusCode,...i.details??{},...this.config.debug?{stack:i.stack}:{}}:{message:this.config.debug?i.message:"An unexpected error occurred",status:s,...this.config.debug?{stack:i.stack}:{}}}}middleware(){let e=this;return async(t,s)=>{try{return await s()}catch(r){return e.handle(r,t.event)}}}async reportError(e,t){if(this.config.dontReport){for(let r of this.config.dontReport)if(e instanceof r)return}let s={error:e.name,...t?.url?{url:t.url.toString()}:{},...e.stack?{stack:e.stack}:{}};if(Zt.error(e.message,s),this.config.report)try{await this.config.report(e,t?{url:t.url?.toString()}:void 0)}catch{}}renderError(e){if(e instanceof N){let s={message:e.message};return e instanceof es&&(s.errors=e.errors),e.details&&Object.assign(s,e.details),this.config.debug&&(s.exception=e.name,s.stack=e.stack?.split(`
139
139
  `).map(r=>r.trim())),new Response(JSON.stringify(s),{status:e.statusCode,headers:{"Content-Type":"application/json"}})}let t={message:this.config.debug?e.message:"Internal server error"};return this.config.debug&&(t.exception=e.name,t.stack=e.stack?.split(`
140
- `).map(s=>s.trim())),new Response(JSON.stringify(t),{status:500,headers:{"Content-Type":"application/json"}})}}});function xi(o={}){let{auth:e,secret:t=(()=>{throw new Error("APP_KEY is not set. Pass `secret` to createSvelarApp() \u2014 e.g. secret: env.APP_KEY (from $env/dynamic/private).")})(),sessionStore:s,sessionLifetime:r=86400,rateLimit:i=100,rateLimitWindow:a=6e4,csrfPaths:n=["/api/"],csrfExcludePaths:l=["/api/webhooks"],authThrottleAttempts:c=5,authThrottleDecay:m=1,debug:p=process.env.NODE_ENV!=="production",middleware:h=[],namedMiddleware:u={},i18n:b,errorConfig:y={}}=o,v=[new ce,new oe({maxRequests:i,windowMs:a}),new le({onlyPaths:n,excludePaths:l}),new he({store:s??new V,secret:t,lifetime:r})];e&&v.push(new be(e)),v.push(...h);let x={"auth-throttle":new de({maxAttempts:c,decayMinutes:m}),...u},k=new ye({debug:p,...y}),A=ur({middleware:v,namedMiddleware:x,onError:(xe,Se)=>k.handle(xe,Se)}),I;if(b){let{paraglideMiddleware:xe,getTextDirection:Se=()=>"ltr"}=b;I=mr(async({event:_,resolve:We})=>xe(_.request,({request:bs,locale:Je})=>(_.request=bs,We(_,{transformPageChunk:({html:Ve})=>Ve.replace("%lang%",Je).replace("%dir%",Se(Je))}))),A)}else I=A;return{handle:I,handleError:k.handleSvelteKitError()}}function ur(o={}){let e=new H;if(o.middleware)for(let t of o.middleware)e.use(t);if(o.namedMiddleware)for(let[t,s]of Object.entries(o.namedMiddleware))e.register(t,s);return async function({event:s,resolve:r}){let i={event:s,params:s.params??{},locals:s.locals??{}};try{o.app&&!o.app.isBooted()&&await o.app.bootstrap();let a=await e.execute(i,async()=>r(s));return a instanceof Response?a:r(s)}catch(a){if(o.onError){let n=await o.onError(a,s);if(n instanceof Response)return n}return console.error("[Svelar] Unhandled error in hooks:",a),new Response(JSON.stringify({message:process.env.NODE_ENV==="production"?"Internal server error":a.message}),{status:500,headers:{"Content-Type":"application/json"}})}}}function mr(...o){return async function({event:t,resolve:s}){let r=s;for(let i=o.length-1;i>=0;i--){let a=o[i],n=r;r=l=>a({event:l,resolve:n})}return r(t)}}var pr=w(()=>{"use strict";ue();Us();tr();dr()});function Si(o,e){let t=process.env[o];return t===void 0?e!==void 0?e:"":t==="true"?!0:t==="false"?!1:t==="null"?null:/^\d+$/.test(t)?Number(t):t}var hr,Pi,Ri=w(()=>{"use strict";E();hr=class{items=new Map;clear(){this.items.clear()}load(e){for(let[t,s]of Object.entries(e))this.set(t,s)}async loadFromDirectory(e){let{resolve:t,basename:s,extname:r}=await import("path"),{existsSync:i,readdirSync:a}=await import("fs"),{pathToFileURL:n}=await import("url"),l=t(e);if(!i(l))return[];let c=a(l).filter(p=>(p.endsWith(".ts")||p.endsWith(".js"))&&!p.startsWith(".")),m=[];for(let p of c){let h=s(p,r(p)),u=t(l,p);try{let y=await import(n(u).href),v=y.default??y.config??y;v&&typeof v=="object"&&!Array.isArray(v)&&(this.set(h,v),m.push(h))}catch{}}return m}get(e,t){let s=e.split("."),r=this.items.get(s[0]);for(let i=1;i<s.length;i++){if(r==null)return t;r=r[s[i]]}return r??t}set(e,t){let s=e.split(".");if(s.length===1){this.items.set(e,t);return}let r=this.items.get(s[0]);(r===void 0||typeof r!="object")&&(r={},this.items.set(s[0],r));let i=r;for(let a=1;a<s.length-1;a++)(i[s[a]]===void 0||typeof i[s[a]]!="object")&&(i[s[a]]={}),i=i[s[a]];i[s[s.length-1]]=t}has(e){return this.get(e)!==void 0}all(){let e={};for(let[t,s]of this.items)e[t]=s;return e}},Pi=S("svelar.config",()=>new hr)});import{z as T}from"zod";function ki(o,e){let t=o.safeParse(e);if(t.success)return{success:!0,data:t.data};let s={};for(let r of t.error.issues){let i=r.path.length>0?r.path:["_root"],a=s;for(let l=0;l<i.length-1;l++){let c=i[l];c in a||(a[c]={}),a=a[c]}let n=i[i.length-1];a[n]||(a[n]=[]),a[n].push(r.message)}return{success:!1,errors:s}}var Ti,Ei=w(()=>{"use strict";Ti={required:()=>T.string().min(1,"This field is required"),email:()=>T.string().email("Must be a valid email address"),string:(o,e)=>{let t=T.string();return o!==void 0&&(t=t.min(o)),e!==void 0&&(t=t.max(e)),t},number:(o,e)=>{let t=T.number();return o!==void 0&&(t=t.min(o)),e!==void 0&&(t=t.max(e)),t},integer:()=>T.number().int(),boolean:()=>T.boolean(),date:()=>T.coerce.date(),url:()=>T.string().url(),uuid:()=>T.string().uuid(),enum:o=>T.enum(o),array:o=>T.array(o),nullable:o=>o.nullable(),optional:o=>o.optional(),confirmed:(o="password")=>T.object({[o]:T.string(),[`${o}_confirmation`]:T.string()}).refine(e=>e[o]===e[`${o}_confirmation`],{message:"Confirmation does not match",path:[`${o}_confirmation`]}),min:o=>T.number().min(o),max:o=>T.number().max(o),between:(o,e)=>T.number().min(o).max(e),regex:(o,e)=>T.string().regex(o,e),ip:()=>T.string().refine(o=>{let e=o.split(".");return e.length!==4?!1:e.every(t=>{let s=Number(t);return Number.isInteger(s)&&s>=0&&s<=255})},{message:"Must be a valid IP address"}),json:()=>T.string().refine(o=>{try{return JSON.parse(o),!0}catch{return!1}},{message:"Must be valid JSON"})}});var $i={};L($i,{FormAuthorizationError:()=>G,FormRequest:()=>ve,FormValidationError:()=>Q});var ve,Q,G,ts=w(()=>{"use strict";ve=class{authorize(e){return!0}messages(){return{}}attributes(){return{}}passedValidation(e){return e}failedValidation(e){throw new Q(e)}failedAuthorization(){throw new G}async parseBody(e){let t=e.request.headers.get("content-type")??"";if(t.includes("application/json"))return e.request.json();if(t.includes("multipart/form-data")||t.includes("application/x-www-form-urlencoded")){let s=await e.request.formData();return Object.fromEntries(s)}return Object.fromEntries(e.url.searchParams)}static async validate(e){let t=new this;await t.authorize(e)||t.failedAuthorization();let r=await t.parseBody(e),i={...Object.fromEntries(e.url.searchParams),...e.params,...r},n=t.rules().safeParse(i);if(!n.success){let l={},c=t.messages(),m=t.attributes();for(let p of n.error.issues){let h=p.path.join("."),u=m[h]??h;l[u]||(l[u]=[]);let b=`${h}.${p.code}`,y=c[b]??c[h];l[u].push(y??p.message)}t.failedValidation(l)}return t.passedValidation(n.data)}},Q=class extends Error{constructor(t){super("The given data was invalid.");this.errors=t;this.name="FormValidationError"}statusCode=422;toResponse(){return new Response(JSON.stringify({message:this.message,errors:this.errors}),{status:422,headers:{"Content-Type":"application/json"}})}},G=class extends Error{statusCode=403;constructor(e="This action is unauthorized."){super(e),this.name="FormAuthorizationError"}toResponse(){return new Response(JSON.stringify({message:this.message}),{status:403,headers:{"Content-Type":"application/json"}})}}});import{readFile as Ai,writeFile as co,unlink as uo,mkdir as ze,readdir as gr,stat as Di,copyFile as mo,rename as po}from"fs/promises";import{existsSync as ho}from"fs";import{join as go,dirname as ss}from"path";var fr,rs,br,Li,_i=w(()=>{"use strict";E();fr=class{constructor(e){this.config=e;if(!e.root)throw new Error('Local disk requires a "root" path.')}resolve(e){return go(this.config.root,e)}async get(e){return Ai(this.resolve(e))}async getText(e){return Ai(this.resolve(e),"utf-8")}async put(e,t){let s=this.resolve(e);await ze(ss(s),{recursive:!0}),await co(s,t)}async append(e,t){let{appendFile:s}=await import("fs/promises"),r=this.resolve(e);await ze(ss(r),{recursive:!0}),await s(r,t)}async exists(e){return ho(this.resolve(e))}async delete(e){try{return await uo(this.resolve(e)),!0}catch{return!1}}async copy(e,t){let s=this.resolve(t);await ze(ss(s),{recursive:!0}),await mo(this.resolve(e),s)}async move(e,t){let s=this.resolve(t);await ze(ss(s),{recursive:!0}),await po(this.resolve(e),s)}async files(e=""){let t=this.resolve(e);try{return(await gr(t,{withFileTypes:!0})).filter(r=>r.isFile()).map(r=>e?`${e}/${r.name}`:r.name)}catch{return[]}}async allFiles(e=""){let t=[],s=this.resolve(e);try{let r=await gr(s,{withFileTypes:!0});for(let i of r){let a=e?`${e}/${i.name}`:i.name;i.isFile()?t.push(a):i.isDirectory()&&t.push(...await this.allFiles(a))}}catch{}return t}async directories(e=""){let t=this.resolve(e);try{return(await gr(t,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>e?`${e}/${r.name}`:r.name)}catch{return[]}}async makeDirectory(e){await ze(this.resolve(e),{recursive:!0})}async deleteDirectory(e){let{rm:t}=await import("fs/promises");await t(this.resolve(e),{recursive:!0,force:!0})}async size(e){return(await Di(this.resolve(e))).size}async lastModified(e){return(await Di(this.resolve(e))).mtime}url(e){return`${this.config.urlPrefix??""}/${e}`}},rs=class{config;_client=null;_s3Module=null;constructor(e){if(!e.bucket)throw new Error('S3 disk requires a "bucket" name.');this.config=e}async getS3(){if(this._s3Module)return this._s3Module;try{return this._s3Module=await Function('return import("@aws-sdk/client-s3")')(),this._s3Module}catch{throw new Error("S3 storage driver requires @aws-sdk/client-s3. Install it with: npm install @aws-sdk/client-s3")}}async getClient(){if(this._client)return this._client;let e=await this.getS3();return this._client=new e.S3Client({region:this.config.region??"us-east-1",endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle??!0,credentials:{accessKeyId:this.config.accessKeyId??"",secretAccessKey:this.config.secretAccessKey??""}}),this._client}key(e){let t=this.config.prefix;return t?`${t}/${e}`:e}async get(e){let t=await this.getS3(),i=await(await(await this.getClient()).send(new t.GetObjectCommand({Bucket:this.config.bucket,Key:this.key(e)}))).Body.transformToByteArray();return Buffer.from(i)}async getText(e){return(await this.get(e)).toString("utf-8")}async put(e,t){let s=await this.getS3(),r=await this.getClient(),i=typeof t=="string"?Buffer.from(t,"utf-8"):t;await r.send(new s.PutObjectCommand({Bucket:this.config.bucket,Key:this.key(e),Body:i}))}async append(e,t){let s=null;try{s=await this.get(e)}catch{}let r=typeof t=="string"?Buffer.from(t,"utf-8"):t,i=s?Buffer.concat([s,r]):r;await this.put(e,i)}async exists(e){let t=await this.getS3(),s=await this.getClient();try{return await s.send(new t.HeadObjectCommand({Bucket:this.config.bucket,Key:this.key(e)})),!0}catch{return!1}}async delete(e){let t=await this.getS3(),s=await this.getClient();try{return await s.send(new t.DeleteObjectCommand({Bucket:this.config.bucket,Key:this.key(e)})),!0}catch{return!1}}async copy(e,t){let s=await this.getS3();await(await this.getClient()).send(new s.CopyObjectCommand({Bucket:this.config.bucket,CopySource:`${this.config.bucket}/${this.key(e)}`,Key:this.key(t)}))}async move(e,t){await this.copy(e,t),await this.delete(e)}async files(e=""){let t=await this.getS3(),s=await this.getClient(),r=this.key(e?`${e}/`:"");try{return((await s.send(new t.ListObjectsV2Command({Bucket:this.config.bucket,Prefix:r,Delimiter:"/"}))).Contents??[]).map(a=>a.Key).filter(a=>a!==r).map(a=>{let n=this.config.prefix;return n?a.slice(n.length+1):a})}catch{return[]}}async allFiles(e=""){let t=await this.getS3(),s=await this.getClient(),r=this.key(e?`${e}/`:""),i=[],a;do{let n=await s.send(new t.ListObjectsV2Command({Bucket:this.config.bucket,Prefix:r,ContinuationToken:a}));for(let l of n.Contents??[]){let c=this.config.prefix,m=c?l.Key.slice(c.length+1):l.Key;m&&i.push(m)}a=n.IsTruncated?n.NextContinuationToken:void 0}while(a);return i}async directories(e=""){let t=await this.getS3(),s=await this.getClient(),r=this.key(e?`${e}/`:"");try{return((await s.send(new t.ListObjectsV2Command({Bucket:this.config.bucket,Prefix:r,Delimiter:"/"}))).CommonPrefixes??[]).map(a=>{let n=this.config.prefix;return(n?a.Prefix.slice(n.length+1):a.Prefix).replace(/\/$/,"")}).filter(a=>a.length>0)}catch{return[]}}async makeDirectory(e){}async deleteDirectory(e){let t=await this.allFiles(e);for(let s of t)await this.delete(s)}async size(e){let t=await this.getS3();return(await(await this.getClient()).send(new t.HeadObjectCommand({Bucket:this.config.bucket,Key:this.key(e)}))).ContentLength??0}async lastModified(e){let t=await this.getS3();return(await(await this.getClient()).send(new t.HeadObjectCommand({Bucket:this.config.bucket,Key:this.key(e)}))).LastModified??new Date}url(e){let t=this.config.urlPrefix;if(t)return`${t}/${e}`;let s=this.config.endpoint??`https://s3.${this.config.region??"us-east-1"}.amazonaws.com`;return this.config.forcePathStyle!==!1?`${s}/${this.config.bucket}/${this.key(e)}`:`${s.replace("://",`://${this.config.bucket}.`)}/${this.key(e)}`}async temporaryUrl(e,t=3600){try{let s=await Function('return import("@aws-sdk/s3-request-presigner")')(),r=await this.getS3(),i=await this.getClient(),a=new r.GetObjectCommand({Bucket:this.config.bucket,Key:this.key(e)});return await s.getSignedUrl(i,a,{expiresIn:t})}catch{throw new Error("Pre-signed URLs require @aws-sdk/s3-request-presigner. Install it with: npm install @aws-sdk/s3-request-presigner")}}async ensureBucket(){let e=await this.getS3(),t=await this.getClient();try{await t.send(new e.HeadBucketCommand({Bucket:this.config.bucket}))}catch{await t.send(new e.CreateBucketCommand({Bucket:this.config.bucket}))}}},br=class{config=null;disks=new Map;configure(e){this.config=e}disk(e){let t=e??this.config?.default??"local";if(this.disks.has(t))return this.disks.get(t);if(!this.config)throw new Error("Storage not configured. Call Storage.configure() first.");let s=this.config.disks[t];if(!s)throw new Error(`Storage disk "${t}" is not defined.`);let r=this.createDisk(s);return this.disks.set(t,r),r}async get(e){return this.disk().get(e)}async getText(e){return this.disk().getText(e)}async put(e,t){return this.disk().put(e,t)}async append(e,t){return this.disk().append(e,t)}async exists(e){return this.disk().exists(e)}async delete(e){return this.disk().delete(e)}async copy(e,t){return this.disk().copy(e,t)}async move(e,t){return this.disk().move(e,t)}async files(e){return this.disk().files(e)}async allFiles(e){return this.disk().allFiles(e)}async directories(e){return this.disk().directories(e)}async makeDirectory(e){return this.disk().makeDirectory(e)}async deleteDirectory(e){return this.disk().deleteDirectory(e)}async size(e){return this.disk().size(e)}async lastModified(e){return this.disk().lastModified(e)}url(e){return this.disk().url(e)}createDisk(e){switch(e.driver){case"local":return new fr(e);case"s3":return new rs(e);default:throw new Error(`Unknown storage driver: ${e.driver}`)}}s3Disk(e){let t=this.disk(e);if(!(t instanceof rs))throw new Error(`Disk "${e??this.config?.default}" is not an S3 disk.`);return t}},Li=S("svelar.storage",()=>new br)});import{readFile as fo,writeFile as bo,unlink as Mi,mkdir as Ni}from"fs/promises";import{join as yo,dirname as vo}from"path";import{createHash as wo}from"crypto";var yr,vr,wr,Cr,Ii,ji=w(()=>{"use strict";E();yr=class{store=new Map;async get(e){let t=this.store.get(e);return t?t.expiresAt&&Date.now()>t.expiresAt?(this.store.delete(e),null):t.value:null}async put(e,t,s){this.store.set(e,{value:t,expiresAt:s?Date.now()+s*1e3:null})}async forget(e){return this.store.delete(e)}async flush(){this.store.clear()}async has(e){let t=this.store.get(e);return t?t.expiresAt&&Date.now()>t.expiresAt?(this.store.delete(e),!1):!0:!1}async increment(e,t=1){let r=(await this.get(e)??0)+t,i=this.store.get(e);return await this.put(e,r,i?.expiresAt?Math.ceil((i.expiresAt-Date.now())/1e3):void 0),r}async decrement(e,t=1){return this.increment(e,-t)}},vr=class{basePath;constructor(e){this.basePath=e.path??"storage/cache"}filePath(e){let t=wo("md5").update(e).digest("hex");return yo(this.basePath,t.slice(0,2),t)}async get(e){let t=this.filePath(e);try{let s=await fo(t,"utf-8"),r=JSON.parse(s);return r.expiresAt&&Date.now()>r.expiresAt?(await Mi(t).catch(()=>{}),null):r.value}catch{return null}}async put(e,t,s){let r=this.filePath(e),i={value:t,expiresAt:s?Date.now()+s*1e3:null};await Ni(vo(r),{recursive:!0}),await bo(r,JSON.stringify(i))}async forget(e){try{return await Mi(this.filePath(e)),!0}catch{return!1}}async flush(){let{rm:e}=await import("fs/promises");await e(this.basePath,{recursive:!0,force:!0}),await Ni(this.basePath,{recursive:!0})}async has(e){return await this.get(e)!==null}async increment(e,t=1){let r=(await this.get(e)??0)+t;return await this.put(e,r),r}async decrement(e,t=1){return this.increment(e,-t)}},wr=class{async get(){return null}async put(){}async forget(){return!0}async flush(){}async has(){return!1}async increment(){return 0}async decrement(){return 0}},Cr=class{config={default:"memory",stores:{memory:{driver:"memory"}}};stores=new Map;configure(e){this.config=e,this.stores.clear()}store(e){let t=e??this.config.default;if(this.stores.has(t))return this.stores.get(t);let s=this.config.stores[t];if(!s)throw new Error(`Cache store "${t}" is not defined.`);let r=this.createStore(s);return this.stores.set(t,r),r}async get(e,t){let s=this.store();return await s.has(e)?s.get(e):t??null}async put(e,t,s){return this.store().put(e,t,s??this.config.stores[this.config.default]?.ttl)}async forget(e){return this.store().forget(e)}async flush(){return this.store().flush()}async has(e){return this.store().has(e)}async increment(e,t){return this.store().increment(e,t)}async decrement(e,t){return this.store().decrement(e,t)}async remember(e,t,s){let r=await this.store().get(e);if(r!==null)return r;let i=await s();return await this.store().put(e,i,t),i}async rememberForever(e,t){let s=await this.store().get(e);if(s!==null)return s;let r=await t();return await this.store().put(e,r),r}async pull(e,t){let s=await this.get(e,t);return await this.forget(e),s}createStore(e){switch(e.driver){case"memory":return new yr;case"file":return new vr(e);case"null":return new wr;case"redis":throw new Error("Redis cache requires ioredis. Install: npm install ioredis");default:throw new Error(`Unknown cache driver: ${e.driver}`)}}},Ii=S("svelar.cache",()=>new Cr)});var is,xr,Sr,Pr,Oi,qi=w(()=>{"use strict";E();is=class{},xr=class{async send(e,t){if(!t.toMail)return;let s=t.toMail(e),r=e.routeNotificationForMail?.()??e.getAttribute("email");if(!r){console.warn("[Notifications] No email address for notifiable.");return}try{let{Mailer:i}=await Promise.resolve().then(()=>(Wt(),Zs));await i.send({to:r,subject:s.subject,html:s.html,text:s.text,from:s.from})}catch(i){console.error("[Notifications] Failed to send mail notification:",i)}}},Sr=class{table;constructor(e="notifications"){this.table=e}async send(e,t){if(!t.toDatabase)return;let s=t.toDatabase(e);try{let{Connection:r}=await Promise.resolve().then(()=>(P(),R));await r.raw(`INSERT INTO ${this.table} (id, notifiable_id, type, data, read_at, created_at)
141
- VALUES (?, ?, ?, ?, NULL, ?)`,[crypto.randomUUID(),e.getAttribute("id"),s.type,JSON.stringify(s.data),new Date().toISOString()])}catch(r){console.error("[Notifications] Failed to store database notification:",r)}}},Pr=class{channels=new Map;constructor(){this.channels.set("mail",new xr),this.channels.set("database",new Sr)}extend(e,t){this.channels.set(e,t)}async send(e,t){let s=Array.isArray(e)?e:[e];for(let r of s){let i=t.via(r);for(let a of i){let n=this.channels.get(a);if(n)try{await n.send(r,t)}catch(l){console.error(`[Notifications] Channel "${a}" failed:`,l)}else console.warn(`[Notifications] Unknown channel: ${a}`)}}}async sendVia(e,t,s){for(let r of s){let i=this.channels.get(r);i&&await i.send(e,t)}}},Oi=S("svelar.notifier",()=>new Pr)});function Rr(o){return o.startsWith("private-")?"private":o.startsWith("presence-")?"presence":"public"}var Tr,as,kr,Er,Ui,Fi=w(()=>{"use strict";E();Tr=class{subscribers=[];name;type;constructor(e){this.name=e,this.type=Rr(e)}stream(e,t){let s=this,r=new ReadableStream({start(i){let a={channel:s.name};s.type==="presence"&&(a.members=s.getMembers());let n=`event: connected
140
+ `).map(s=>s.trim())),new Response(JSON.stringify(t),{status:500,headers:{"Content-Type":"application/json"}})}}});function Ti(o={}){let{auth:e,secret:t=(()=>{throw new Error("APP_KEY is not set. Pass `secret` to createSvelarApp() \u2014 e.g. secret: env.APP_KEY (from $env/dynamic/private).")})(),sessionStore:s,sessionLifetime:r=86400,rateLimit:i=100,rateLimitWindow:a=6e4,csrfPaths:n=["/api/"],csrfExcludePaths:l=["/api/webhooks"],authThrottleAttempts:c=5,authThrottleDecay:m=1,debug:p=process.env.NODE_ENV!=="production",middleware:h=[],namedMiddleware:u={},i18n:b,errorConfig:y={}}=o,v=[new ce,new oe({maxRequests:i,windowMs:a}),new le({onlyPaths:n,excludePaths:l}),new he({store:s??new V,secret:t,lifetime:r})];e&&v.push(new be(e)),v.push(...h);let x={"auth-throttle":new de({maxAttempts:c,decayMinutes:m}),...u},k=new ye({debug:p,...y}),A=pr({middleware:v,namedMiddleware:x,onError:(xe,Pe)=>k.handle(xe,Pe)}),I;if(b){let{paraglideMiddleware:xe,getTextDirection:Pe=()=>"ltr"}=b;I=hr(async({event:_,resolve:We})=>xe(_.request,({request:vs,locale:Je})=>(_.request=vs,We(_,{transformPageChunk:({html:Ve})=>Ve.replace("%lang%",Je).replace("%dir%",Pe(Je))}))),A)}else I=A;return{handle:I,handleError:k.handleSvelteKitError()}}function pr(o={}){let e=new H;if(o.middleware)for(let t of o.middleware)e.use(t);if(o.namedMiddleware)for(let[t,s]of Object.entries(o.namedMiddleware))e.register(t,s);return async function({event:s,resolve:r}){let i={event:s,params:s.params??{},locals:s.locals??{}};try{o.app&&!o.app.isBooted()&&await o.app.bootstrap();let a=await e.execute(i,async()=>r(s));return a instanceof Response?a:r(s)}catch(a){if(o.onError){let n=await o.onError(a,s);if(n instanceof Response)return n}return console.error("[Svelar] Unhandled error in hooks:",a),new Response(JSON.stringify({message:process.env.NODE_ENV==="production"?"Internal server error":a.message}),{status:500,headers:{"Content-Type":"application/json"}})}}}function hr(...o){return async function({event:t,resolve:s}){let r=s;for(let i=o.length-1;i>=0;i--){let a=o[i],n=r;r=l=>a({event:l,resolve:n})}return r(t)}}var gr=C(()=>{"use strict";ue();Bs();rr();mr()});function ki(o,e){let t=process.env[o];return t===void 0?e!==void 0?e:"":t==="true"?!0:t==="false"?!1:t==="null"?null:/^\d+$/.test(t)?Number(t):t}var fr,Ei,$i=C(()=>{"use strict";E();fr=class{items=new Map;clear(){this.items.clear()}load(e){for(let[t,s]of Object.entries(e))this.set(t,s)}async loadFromDirectory(e){let{resolve:t,basename:s,extname:r}=await import("path"),{existsSync:i,readdirSync:a}=await import("fs"),{pathToFileURL:n}=await import("url"),l=t(e);if(!i(l))return[];let c=a(l).filter(p=>(p.endsWith(".ts")||p.endsWith(".js"))&&!p.startsWith(".")),m=[];for(let p of c){let h=s(p,r(p)),u=t(l,p);try{let y=await import(n(u).href),v=y.default??y.config??y;v&&typeof v=="object"&&!Array.isArray(v)&&(this.set(h,v),m.push(h))}catch{}}return m}get(e,t){let s=e.split("."),r=this.items.get(s[0]);for(let i=1;i<s.length;i++){if(r==null)return t;r=r[s[i]]}return r??t}set(e,t){let s=e.split(".");if(s.length===1){this.items.set(e,t);return}let r=this.items.get(s[0]);(r===void 0||typeof r!="object")&&(r={},this.items.set(s[0],r));let i=r;for(let a=1;a<s.length-1;a++)(i[s[a]]===void 0||typeof i[s[a]]!="object")&&(i[s[a]]={}),i=i[s[a]];i[s[s.length-1]]=t}has(e){return this.get(e)!==void 0}all(){let e={};for(let[t,s]of this.items)e[t]=s;return e}},Ei=P("svelar.config",()=>new fr)});import{z as T}from"zod";function Di(o,e){let t=o.safeParse(e);if(t.success)return{success:!0,data:t.data};let s={};for(let r of t.error.issues){let i=r.path.length>0?r.path:["_root"],a=s;for(let l=0;l<i.length-1;l++){let c=i[l];c in a||(a[c]={}),a=a[c]}let n=i[i.length-1];a[n]||(a[n]=[]),a[n].push(r.message)}return{success:!1,errors:s}}var Ai,Li=C(()=>{"use strict";Ai={required:()=>T.string().min(1,"This field is required"),email:()=>T.string().email("Must be a valid email address"),string:(o,e)=>{let t=T.string();return o!==void 0&&(t=t.min(o)),e!==void 0&&(t=t.max(e)),t},number:(o,e)=>{let t=T.number();return o!==void 0&&(t=t.min(o)),e!==void 0&&(t=t.max(e)),t},integer:()=>T.number().int(),boolean:()=>T.boolean(),date:()=>T.coerce.date(),url:()=>T.string().url(),uuid:()=>T.string().uuid(),enum:o=>T.enum(o),array:o=>T.array(o),nullable:o=>o.nullable(),optional:o=>o.optional(),confirmed:(o="password")=>T.object({[o]:T.string(),[`${o}_confirmation`]:T.string()}).refine(e=>e[o]===e[`${o}_confirmation`],{message:"Confirmation does not match",path:[`${o}_confirmation`]}),min:o=>T.number().min(o),max:o=>T.number().max(o),between:(o,e)=>T.number().min(o).max(e),regex:(o,e)=>T.string().regex(o,e),ip:()=>T.string().refine(o=>{let e=o.split(".");return e.length!==4?!1:e.every(t=>{let s=Number(t);return Number.isInteger(s)&&s>=0&&s<=255})},{message:"Must be a valid IP address"}),json:()=>T.string().refine(o=>{try{return JSON.parse(o),!0}catch{return!1}},{message:"Must be valid JSON"})}});var _i={};L(_i,{FormAuthorizationError:()=>G,FormRequest:()=>ve,FormValidationError:()=>Q});var ve,Q,G,rs=C(()=>{"use strict";ve=class{authorize(e){return!0}messages(){return{}}attributes(){return{}}passedValidation(e){return e}failedValidation(e){throw new Q(e)}failedAuthorization(){throw new G}async parseBody(e){let t=e.request.headers.get("content-type")??"";if(t.includes("application/json"))return e.request.json();if(t.includes("multipart/form-data")||t.includes("application/x-www-form-urlencoded")){let s=await e.request.formData();return Object.fromEntries(s)}return Object.fromEntries(e.url.searchParams)}static async validate(e){let t=new this;await t.authorize(e)||t.failedAuthorization();let r=await t.parseBody(e),i={...Object.fromEntries(e.url.searchParams),...e.params,...r},n=t.rules().safeParse(i);if(!n.success){let l={},c=t.messages(),m=t.attributes();for(let p of n.error.issues){let h=p.path.join("."),u=m[h]??h;l[u]||(l[u]=[]);let b=`${h}.${p.code}`,y=c[b]??c[h];l[u].push(y??p.message)}t.failedValidation(l)}return t.passedValidation(n.data)}},Q=class extends Error{constructor(t){super("The given data was invalid.");this.errors=t;this.name="FormValidationError"}statusCode=422;toResponse(){return new Response(JSON.stringify({message:this.message,errors:this.errors}),{status:422,headers:{"Content-Type":"application/json"}})}},G=class extends Error{statusCode=403;constructor(e="This action is unauthorized."){super(e),this.name="FormAuthorizationError"}toResponse(){return new Response(JSON.stringify({message:this.message}),{status:403,headers:{"Content-Type":"application/json"}})}}});import{readFile as Mi,writeFile as Po,unlink as So,mkdir as ze,readdir as br,stat as Ni,copyFile as Ro,rename as To}from"fs/promises";import{existsSync as ko}from"fs";import{join as Eo,dirname as is}from"path";var yr,as,vr,Ii,ji=C(()=>{"use strict";E();yr=class{constructor(e){this.config=e;if(!e.root)throw new Error('Local disk requires a "root" path.')}resolve(e){return Eo(this.config.root,e)}async get(e){return Mi(this.resolve(e))}async getText(e){return Mi(this.resolve(e),"utf-8")}async put(e,t){let s=this.resolve(e);await ze(is(s),{recursive:!0}),await Po(s,t)}async append(e,t){let{appendFile:s}=await import("fs/promises"),r=this.resolve(e);await ze(is(r),{recursive:!0}),await s(r,t)}async exists(e){return ko(this.resolve(e))}async delete(e){try{return await So(this.resolve(e)),!0}catch{return!1}}async copy(e,t){let s=this.resolve(t);await ze(is(s),{recursive:!0}),await Ro(this.resolve(e),s)}async move(e,t){let s=this.resolve(t);await ze(is(s),{recursive:!0}),await To(this.resolve(e),s)}async files(e=""){let t=this.resolve(e);try{return(await br(t,{withFileTypes:!0})).filter(r=>r.isFile()).map(r=>e?`${e}/${r.name}`:r.name)}catch{return[]}}async allFiles(e=""){let t=[],s=this.resolve(e);try{let r=await br(s,{withFileTypes:!0});for(let i of r){let a=e?`${e}/${i.name}`:i.name;i.isFile()?t.push(a):i.isDirectory()&&t.push(...await this.allFiles(a))}}catch{}return t}async directories(e=""){let t=this.resolve(e);try{return(await br(t,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>e?`${e}/${r.name}`:r.name)}catch{return[]}}async makeDirectory(e){await ze(this.resolve(e),{recursive:!0})}async deleteDirectory(e){let{rm:t}=await import("fs/promises");await t(this.resolve(e),{recursive:!0,force:!0})}async size(e){return(await Ni(this.resolve(e))).size}async lastModified(e){return(await Ni(this.resolve(e))).mtime}url(e){return`${this.config.urlPrefix??""}/${e}`}},as=class{config;_client=null;_s3Module=null;constructor(e){if(!e.bucket)throw new Error('S3 disk requires a "bucket" name.');this.config=e}async getS3(){if(this._s3Module)return this._s3Module;try{return this._s3Module=await Function('return import("@aws-sdk/client-s3")')(),this._s3Module}catch{throw new Error("S3 storage driver requires @aws-sdk/client-s3. Install it with: npm install @aws-sdk/client-s3")}}async getClient(){if(this._client)return this._client;let e=await this.getS3();return this._client=new e.S3Client({region:this.config.region??"us-east-1",endpoint:this.config.endpoint,forcePathStyle:this.config.forcePathStyle??!0,credentials:{accessKeyId:this.config.accessKeyId??"",secretAccessKey:this.config.secretAccessKey??""}}),this._client}key(e){let t=this.config.prefix;return t?`${t}/${e}`:e}async get(e){let t=await this.getS3(),i=await(await(await this.getClient()).send(new t.GetObjectCommand({Bucket:this.config.bucket,Key:this.key(e)}))).Body.transformToByteArray();return Buffer.from(i)}async getText(e){return(await this.get(e)).toString("utf-8")}async put(e,t){let s=await this.getS3(),r=await this.getClient(),i=typeof t=="string"?Buffer.from(t,"utf-8"):t;await r.send(new s.PutObjectCommand({Bucket:this.config.bucket,Key:this.key(e),Body:i}))}async append(e,t){let s=null;try{s=await this.get(e)}catch{}let r=typeof t=="string"?Buffer.from(t,"utf-8"):t,i=s?Buffer.concat([s,r]):r;await this.put(e,i)}async exists(e){let t=await this.getS3(),s=await this.getClient();try{return await s.send(new t.HeadObjectCommand({Bucket:this.config.bucket,Key:this.key(e)})),!0}catch{return!1}}async delete(e){let t=await this.getS3(),s=await this.getClient();try{return await s.send(new t.DeleteObjectCommand({Bucket:this.config.bucket,Key:this.key(e)})),!0}catch{return!1}}async copy(e,t){let s=await this.getS3();await(await this.getClient()).send(new s.CopyObjectCommand({Bucket:this.config.bucket,CopySource:`${this.config.bucket}/${this.key(e)}`,Key:this.key(t)}))}async move(e,t){await this.copy(e,t),await this.delete(e)}async files(e=""){let t=await this.getS3(),s=await this.getClient(),r=this.key(e?`${e}/`:"");try{return((await s.send(new t.ListObjectsV2Command({Bucket:this.config.bucket,Prefix:r,Delimiter:"/"}))).Contents??[]).map(a=>a.Key).filter(a=>a!==r).map(a=>{let n=this.config.prefix;return n?a.slice(n.length+1):a})}catch{return[]}}async allFiles(e=""){let t=await this.getS3(),s=await this.getClient(),r=this.key(e?`${e}/`:""),i=[],a;do{let n=await s.send(new t.ListObjectsV2Command({Bucket:this.config.bucket,Prefix:r,ContinuationToken:a}));for(let l of n.Contents??[]){let c=this.config.prefix,m=c?l.Key.slice(c.length+1):l.Key;m&&i.push(m)}a=n.IsTruncated?n.NextContinuationToken:void 0}while(a);return i}async directories(e=""){let t=await this.getS3(),s=await this.getClient(),r=this.key(e?`${e}/`:"");try{return((await s.send(new t.ListObjectsV2Command({Bucket:this.config.bucket,Prefix:r,Delimiter:"/"}))).CommonPrefixes??[]).map(a=>{let n=this.config.prefix;return(n?a.Prefix.slice(n.length+1):a.Prefix).replace(/\/$/,"")}).filter(a=>a.length>0)}catch{return[]}}async makeDirectory(e){}async deleteDirectory(e){let t=await this.allFiles(e);for(let s of t)await this.delete(s)}async size(e){let t=await this.getS3();return(await(await this.getClient()).send(new t.HeadObjectCommand({Bucket:this.config.bucket,Key:this.key(e)}))).ContentLength??0}async lastModified(e){let t=await this.getS3();return(await(await this.getClient()).send(new t.HeadObjectCommand({Bucket:this.config.bucket,Key:this.key(e)}))).LastModified??new Date}url(e){let t=this.config.urlPrefix;if(t)return`${t}/${e}`;let s=this.config.endpoint??`https://s3.${this.config.region??"us-east-1"}.amazonaws.com`;return this.config.forcePathStyle!==!1?`${s}/${this.config.bucket}/${this.key(e)}`:`${s.replace("://",`://${this.config.bucket}.`)}/${this.key(e)}`}async temporaryUrl(e,t=3600){try{let s=await Function('return import("@aws-sdk/s3-request-presigner")')(),r=await this.getS3(),i=await this.getClient(),a=new r.GetObjectCommand({Bucket:this.config.bucket,Key:this.key(e)});return await s.getSignedUrl(i,a,{expiresIn:t})}catch{throw new Error("Pre-signed URLs require @aws-sdk/s3-request-presigner. Install it with: npm install @aws-sdk/s3-request-presigner")}}async ensureBucket(){let e=await this.getS3(),t=await this.getClient();try{await t.send(new e.HeadBucketCommand({Bucket:this.config.bucket}))}catch{await t.send(new e.CreateBucketCommand({Bucket:this.config.bucket}))}}},vr=class{config=null;disks=new Map;configure(e){this.config=e}disk(e){let t=e??this.config?.default??"local";if(this.disks.has(t))return this.disks.get(t);if(!this.config)throw new Error("Storage not configured. Call Storage.configure() first.");let s=this.config.disks[t];if(!s)throw new Error(`Storage disk "${t}" is not defined.`);let r=this.createDisk(s);return this.disks.set(t,r),r}async get(e){return this.disk().get(e)}async getText(e){return this.disk().getText(e)}async put(e,t){return this.disk().put(e,t)}async append(e,t){return this.disk().append(e,t)}async exists(e){return this.disk().exists(e)}async delete(e){return this.disk().delete(e)}async copy(e,t){return this.disk().copy(e,t)}async move(e,t){return this.disk().move(e,t)}async files(e){return this.disk().files(e)}async allFiles(e){return this.disk().allFiles(e)}async directories(e){return this.disk().directories(e)}async makeDirectory(e){return this.disk().makeDirectory(e)}async deleteDirectory(e){return this.disk().deleteDirectory(e)}async size(e){return this.disk().size(e)}async lastModified(e){return this.disk().lastModified(e)}url(e){return this.disk().url(e)}createDisk(e){switch(e.driver){case"local":return new yr(e);case"s3":return new as(e);default:throw new Error(`Unknown storage driver: ${e.driver}`)}}s3Disk(e){let t=this.disk(e);if(!(t instanceof as))throw new Error(`Disk "${e??this.config?.default}" is not an S3 disk.`);return t}},Ii=P("svelar.storage",()=>new vr)});import{readFile as $o,writeFile as Ao,unlink as Oi,mkdir as qi}from"fs/promises";import{join as Do,dirname as Lo}from"path";import{createHash as _o}from"crypto";var wr,Cr,xr,Pr,Ui,Fi=C(()=>{"use strict";E();wr=class{store=new Map;async get(e){let t=this.store.get(e);return t?t.expiresAt&&Date.now()>t.expiresAt?(this.store.delete(e),null):t.value:null}async put(e,t,s){this.store.set(e,{value:t,expiresAt:s?Date.now()+s*1e3:null})}async forget(e){return this.store.delete(e)}async flush(){this.store.clear()}async has(e){let t=this.store.get(e);return t?t.expiresAt&&Date.now()>t.expiresAt?(this.store.delete(e),!1):!0:!1}async increment(e,t=1){let r=(await this.get(e)??0)+t,i=this.store.get(e);return await this.put(e,r,i?.expiresAt?Math.ceil((i.expiresAt-Date.now())/1e3):void 0),r}async decrement(e,t=1){return this.increment(e,-t)}},Cr=class{basePath;constructor(e){this.basePath=e.path??"storage/cache"}filePath(e){let t=_o("md5").update(e).digest("hex");return Do(this.basePath,t.slice(0,2),t)}async get(e){let t=this.filePath(e);try{let s=await $o(t,"utf-8"),r=JSON.parse(s);return r.expiresAt&&Date.now()>r.expiresAt?(await Oi(t).catch(()=>{}),null):r.value}catch{return null}}async put(e,t,s){let r=this.filePath(e),i={value:t,expiresAt:s?Date.now()+s*1e3:null};await qi(Lo(r),{recursive:!0}),await Ao(r,JSON.stringify(i))}async forget(e){try{return await Oi(this.filePath(e)),!0}catch{return!1}}async flush(){let{rm:e}=await import("fs/promises");await e(this.basePath,{recursive:!0,force:!0}),await qi(this.basePath,{recursive:!0})}async has(e){return await this.get(e)!==null}async increment(e,t=1){let r=(await this.get(e)??0)+t;return await this.put(e,r),r}async decrement(e,t=1){return this.increment(e,-t)}},xr=class{async get(){return null}async put(){}async forget(){return!0}async flush(){}async has(){return!1}async increment(){return 0}async decrement(){return 0}},Pr=class{config={default:"memory",stores:{memory:{driver:"memory"}}};stores=new Map;configure(e){this.config=e,this.stores.clear()}store(e){let t=e??this.config.default;if(this.stores.has(t))return this.stores.get(t);let s=this.config.stores[t];if(!s)throw new Error(`Cache store "${t}" is not defined.`);let r=this.createStore(s);return this.stores.set(t,r),r}async get(e,t){let s=this.store();return await s.has(e)?s.get(e):t??null}async put(e,t,s){return this.store().put(e,t,s??this.config.stores[this.config.default]?.ttl)}async forget(e){return this.store().forget(e)}async flush(){return this.store().flush()}async has(e){return this.store().has(e)}async increment(e,t){return this.store().increment(e,t)}async decrement(e,t){return this.store().decrement(e,t)}async remember(e,t,s){let r=await this.store().get(e);if(r!==null)return r;let i=await s();return await this.store().put(e,i,t),i}async rememberForever(e,t){let s=await this.store().get(e);if(s!==null)return s;let r=await t();return await this.store().put(e,r),r}async pull(e,t){let s=await this.get(e,t);return await this.forget(e),s}createStore(e){switch(e.driver){case"memory":return new wr;case"file":return new Cr(e);case"null":return new xr;case"redis":throw new Error("Redis cache requires ioredis. Install: npm install ioredis");default:throw new Error(`Unknown cache driver: ${e.driver}`)}}},Ui=P("svelar.cache",()=>new Pr)});var ns,Sr,Rr,Tr,Bi,Hi=C(()=>{"use strict";E();ns=class{},Sr=class{async send(e,t){if(!t.toMail)return;let s=t.toMail(e),r=e.routeNotificationForMail?.()??e.getAttribute("email");if(!r){console.warn("[Notifications] No email address for notifiable.");return}try{let{Mailer:i}=await Promise.resolve().then(()=>(Vt(),er));await i.send({to:r,subject:s.subject,html:s.html,text:s.text,from:s.from})}catch(i){console.error("[Notifications] Failed to send mail notification:",i)}}},Rr=class{table;constructor(e="notifications"){this.table=e}async send(e,t){if(!t.toDatabase)return;let s=t.toDatabase(e);try{let{Connection:r}=await Promise.resolve().then(()=>(S(),R));await r.raw(`INSERT INTO ${this.table} (id, notifiable_id, type, data, read_at, created_at)
141
+ VALUES (?, ?, ?, ?, NULL, ?)`,[crypto.randomUUID(),e.getAttribute("id"),s.type,JSON.stringify(s.data),new Date().toISOString()])}catch(r){console.error("[Notifications] Failed to store database notification:",r)}}},Tr=class{channels=new Map;constructor(){this.channels.set("mail",new Sr),this.channels.set("database",new Rr)}extend(e,t){this.channels.set(e,t)}async send(e,t){let s=Array.isArray(e)?e:[e];for(let r of s){let i=t.via(r);for(let a of i){let n=this.channels.get(a);if(n)try{await n.send(r,t)}catch(l){console.error(`[Notifications] Channel "${a}" failed:`,l)}else console.warn(`[Notifications] Unknown channel: ${a}`)}}}async sendVia(e,t,s){for(let r of s){let i=this.channels.get(r);i&&await i.send(e,t)}}},Bi=P("svelar.notifier",()=>new Tr)});function kr(o){return o.startsWith("private-")?"private":o.startsWith("presence-")?"presence":"public"}var Er,os,$r,Ar,zi,Ki=C(()=>{"use strict";E();Er=class{subscribers=[];name;type;constructor(e){this.name=e,this.type=kr(e)}stream(e,t){let s=this,r=new ReadableStream({start(i){let a={channel:s.name};s.type==="presence"&&(a.members=s.getMembers());let n=`event: connected
142
142
  data: ${JSON.stringify(a)}
143
143
  id: ${Date.now()}
144
144
 
@@ -156,9 +156,9 @@ id: ${Date.now()}
156
156
  data: ${JSON.stringify(t)}
157
157
  id: ${Date.now()}
158
158
 
159
- `,i=new TextEncoder().encode(r);for(let a of this.subscribers)if(a.userId!==s)try{a.controller.enqueue(i)}catch{}}},as=class{config;constructor(e){this.config=e}async send(e,t,s){let r=Array.isArray(e)?e:[e],i=JSON.stringify({name:t,channels:r,data:JSON.stringify(s)}),a=Math.floor(Date.now()/1e3).toString(),n=await this.md5(i),l=["POST",`/apps/${this.config.appId}/events`,[`auth_key=${this.config.key}`,`auth_timestamp=${a}`,"auth_version=1.0",`body_md5=${n}`].join("&")].join(`
160
- `),c=await this.hmacSha256(this.config.secret,l),m=this.config.useTLS!==!1?"https":"http",p=this.config.host??`api-${this.config.cluster??"mt1"}.pusher.com`,h=this.config.port??(this.config.useTLS!==!1?443:80),u=`${m}://${p}:${h}/apps/${this.config.appId}/events?auth_key=${this.config.key}&auth_timestamp=${a}&auth_version=1.0&body_md5=${n}&auth_signature=${c}`,b=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},body:i});if(!b.ok){let y=await b.text();throw new Error(`Pusher API error (${b.status}): ${y}`)}}async authenticate(e,t,s){let r=`${e}:${t}`,i;s&&(i=JSON.stringify(s),r+=`:${i}`);let a=await this.hmacSha256(this.config.secret,r),n=`${this.config.key}:${a}`;return i?{auth:n,channel_data:i}:{auth:n}}get key(){return this.config.key}clientConfig(){let e={key:this.config.key,cluster:this.config.cluster??"mt1"};return this.config.host&&(e.wsHost=this.config.host,e.wsPort=this.config.port??6001,e.wssPort=this.config.port??6001,e.forceTLS=this.config.useTLS??!1,e.enabledTransports=["ws","wss"],e.disableStats=!0),e}async md5(e){let{createHash:t}=await import("crypto");return t("md5").update(e).digest("hex")}async hmacSha256(e,t){let{createHmac:s}=await import("crypto");return s("sha256",e).update(t).digest("hex")}},kr=class{constructor(e,t,s){this.manager=e;this.eventName=t;this.eventData=s}channels=[];on(...e){return this.channels.push(...e),this}async send(){for(let e of this.channels)await this.manager.sendToChannel(e,this.eventName,this.eventData)}},Er=class{config={default:"sse",drivers:{sse:{driver:"sse"}}};sseChannels=new Map;channelAuth=new Map;pusherDriver=null;configure(e){this.config=e;let t=Object.values(e.drivers).find(s=>s.driver==="pusher");t&&t.driver==="pusher"&&(this.pusherDriver=new as(t))}channel(e,t){if(t){this.channelAuth.set(e,t);return}return this.sseChannels.has(e)||this.sseChannels.set(e,new Tr(e)),this.sseChannels.get(e)}async authorize(e,t){if(Rr(e)==="public")return!0;for(let[r,i]of this.channelAuth){let a=this.matchPattern(r,e);if(a!==null)return await i(t,a)}return!1}async authenticatePusher(e,t,s){if(!this.pusherDriver)throw new Error("Pusher driver is not configured. Call Broadcast.configure() first.");let r=Rr(e);if(r==="public")return!1;let i=await this.authorize(e,s);if(i===!1)return!1;if(r==="presence"){let a=typeof i=="object"?{user_id:i.id??s.id,user_info:i}:{user_id:s.id,user_info:{id:s.id}};return this.pusherDriver.authenticate(t,e,a)}return this.pusherDriver.authenticate(t,e)}event(e,t){return new kr(this,e,t)}to(e,t){return{send:async(s,r)=>{await this.sendToChannel(e,s,r,t)}}}async sendToChannel(e,t,s,r){let i=this.config.drivers[this.config.default];switch(i?.driver){case"pusher":this.pusherDriver||(this.pusherDriver=new as(i)),await this.pusherDriver.send(e,t,s);break;case"log":console.log(`[Broadcast] ${e} \u2192 ${t}:`,JSON.stringify(s));break;default:for(let[,a]of this.sseChannels)a.name===e&&a.send(t,s,r);break}}subscribe(e,t,s){return this.channel(e).stream(t,s)}members(e){let t=this.sseChannels.get(e);return t?t.getMembers():[]}pusher(){if(!this.pusherDriver)throw new Error("Pusher driver is not configured.");return this.pusherDriver}activeChannels(){return[...new Set([...this.sseChannels.values()].map(e=>e.name))]}totalSubscribers(){let e=0;for(let t of this.sseChannels.values())e+=t.subscriberCount();return e}prune(){for(let[e,t]of this.sseChannels)t.subscriberCount()===0&&this.sseChannels.delete(e)}matchPattern(e,t){let s=[],r=e.replace(/[.*+?^${}()|[\]\\]/g,l=>l==="{"||l==="}"?l:`\\${l}`).replace(/\\\{(\w+)\\\}/g,(l,c)=>(s.push(c),"([^.]+)")).replace(/\{(\w+)\}/g,(l,c)=>(s.push(c),"([^.]+)")),i=new RegExp(`^${r}$`),a=t.match(i);if(!a)return null;let n={};for(let l=0;l<s.length;l++)n[s[l]]=a[l+1];return n}},Ui=S("svelar.broadcast",()=>new Er)});function ns(o,e,t){Bi&&Bi(o,e,{description:t})}async function Hi(o,e={}){let{csrfCookieName:t="XSRF-TOKEN",csrfHeaderName:s="X-CSRF-Token",showToast:r=!0,errorMessages:i={},...a}=e,n=(a.method||"GET").toUpperCase(),l=new Headers(a.headers);if(["POST","PUT","PATCH","DELETE"].includes(n)){let c=Ar(t);c&&l.set(s,c)}a.body&&typeof a.body=="string"&&!l.has("Content-Type")&&l.set("Content-Type","application/json"),l.has("Accept")||l.set("Accept","application/json");try{let c=await fetch(o,{...a,headers:l});return!c.ok&&r&&await xo(c,{...Co,...i}),c}catch(c){throw r&&ns("error","Network Error","Unable to connect. Check your internet connection."),c}}async function xo(o,e){let t="";try{if((o.headers.get("content-type")??"").includes("application/json")){let a=await o.clone().json();if(t=a.message??"",o.status===422&&a.errors){let n=Object.entries(a.errors).map(([l,c])=>`${l}: ${c.join(", ")}`).slice(0,3).join(`
161
- `);ns("warning",e[422]??"Validation Error",n);return}}}catch{}let s=t||e[o.status]||`Error ${o.status}`,r=o.status>=500?"error":o.status===429?"warning":"error";if(o.status===401){ns("warning",s,"Please sign in to continue.");return}ns(r,s)}function Ar(o="XSRF-TOKEN"){if(typeof document>"u")return null;let e=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t=document.cookie.match(new RegExp(`(?:^|;\\s*)${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}function zi(o,e){if(!e)return o;let t=new URL(o,"http://localhost");for(let[s,r]of Object.entries(e))r!=null&&t.searchParams.set(s,String(r));return t.pathname+t.search}var Co,Bi,$r,we,Nu,Ki=w(()=>{"use strict";Co={400:"Invalid request. Please check your input.",401:"Your session has expired. Please sign in again.",403:"You don't have permission to do this.",404:"The requested resource was not found.",405:"This action is not allowed.",409:"A conflict occurred. Please refresh and try again.",419:"Page expired. Please refresh and try again.",422:"The submitted data is invalid.",429:"Too many requests. Please wait a moment.",500:"Something went wrong on our end.",502:"Service temporarily unavailable. Try again shortly.",503:"Service is under maintenance. Try again shortly.",504:"Request timed out. Please try again."},Bi=null;$r=class o{_baseUrl="";_headers={};_timeout=3e4;_retries=0;_retryDelay=1e3;_query={};constructor(e){e?.baseUrl&&(this._baseUrl=e.baseUrl),e?.headers&&(this._headers={...e.headers}),e?.timeout&&(this._timeout=e.timeout),e?.retries&&(this._retries=e.retries),e?.retryDelay&&(this._retryDelay=e.retryDelay)}clone(){let e=new o;return e._baseUrl=this._baseUrl,e._headers={...this._headers},e._timeout=this._timeout,e._retries=this._retries,e._retryDelay=this._retryDelay,e._query={...this._query},e}baseUrl(e){let t=this.clone();return t._baseUrl=e,t}withHeaders(e){let t=this.clone();return t._headers={...t._headers,...e},t}withToken(e,t="Bearer"){return this.withHeaders({Authorization:`${t} ${e}`})}withBasicAuth(e,t){let s=Buffer.from(`${e}:${t}`).toString("base64");return this.withHeaders({Authorization:`Basic ${s}`})}accept(e){return this.withHeaders({Accept:e})}contentType(e){return this.withHeaders({"Content-Type":e})}timeout(e){let t=this.clone();return t._timeout=e,t}retry(e,t=1e3){let s=this.clone();return s._retries=e,s._retryDelay=t,s}query(e){let t=this.clone();for(let[s,r]of Object.entries(e))r!=null&&(t._query[s]=String(r));return t}async get(e){return this.request("GET",e)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async request(e,t,s){let r=this.buildFullUrl(t),i={...this._headers},a;s!==void 0&&(i["Content-Type"]||(i["Content-Type"]="application/json"),a=typeof s=="string"?s:JSON.stringify(s)),i.Accept||(i.Accept="application/json");let n=null,l=1+this._retries;for(let c=0;c<l;c++){c>0&&await new Promise(m=>setTimeout(m,this._retryDelay*c));try{let m=new AbortController,p=setTimeout(()=>m.abort(),this._timeout),h=await fetch(r,{method:e,headers:i,body:a,signal:m.signal});if(clearTimeout(p),!h.ok&&h.status<500&&c<l-1,!h.ok&&h.status>=500&&c<l-1){n=new we(`HTTP ${h.status}: ${h.statusText}`,h.status,await h.text());continue}let u=h.headers.get("content-type")??"",b;if(u.includes("application/json")?b=await h.json():b=await h.text(),!h.ok)throw new we(`HTTP ${h.status}: ${typeof b=="string"?b:JSON.stringify(b)}`,h.status,b);return{data:b,status:h.status,headers:h.headers,ok:!0}}catch(m){if(m instanceof we)throw m;if(n=m,m.name==="AbortError"&&(n=new we("Request timed out",0,null)),c>=l-1)break}}throw n??new Error("HTTP request failed")}buildFullUrl(e){let t=this._baseUrl?`${this._baseUrl.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`:e,s=Object.entries(this._query);if(s.length>0){let r=new URL(t);for(let[i,a]of s)r.searchParams.set(i,a);t=r.toString()}return t}},we=class extends Error{constructor(t,s,r){super(t);this.status=s;this.body=r;this.name="HttpRequestError"}},Nu=new $r});function Wi(o){let{paraglideMiddleware:e,getTextDirection:t=()=>"ltr",langPlaceholder:s="%lang%",dirPlaceholder:r="%dir%"}=o;return({event:i,resolve:a})=>e(i.request,({request:n,locale:l})=>(i.request=n,a(i,{transformPageChunk:({html:c})=>c.replace(s,l).replace(r,t(l))})))}function Ji(o){return e=>o.deLocalizeUrl(e.url).pathname}var Vi=w(()=>{"use strict"});function Qi(o,e,t={}){return async s=>{let{superValidate:r,fail:i,message:a}=await import("sveltekit-superforms"),{zod:n}=await import("sveltekit-superforms/adapters"),l=await r(s,n(o));if(!l.valid)return i(400,{form:l});try{let c=await e(l.data,s);if(t.redirectTo){let{redirect:m}=await import("@sveltejs/kit");throw m(303,t.redirectTo)}return c??{form:l}}catch(c){if(c?.status>=300&&c?.status<400)throw c;return a(l,t.errorMessage||c.message||"An error occurred",{status:c.status||400})}}}async function Gi(o,e){let{superValidate:t}=await import("sveltekit-superforms"),{zod:s}=await import("sveltekit-superforms/adapters");return t(e??null,s(o))}async function Yi(o,e){let t=await o.request.formData(),s={};for(let[i,a]of t.entries())s[i]=a;let r=e.safeParse(s);if(!r.success){let{FormValidationError:i}=await Promise.resolve().then(()=>(ts(),$i));throw new i(r.error.flatten().fieldErrors)}return r.data}var Zi=w(()=>{"use strict";ts()});var Xi={};L(Xi,{Application:()=>jt,AuthManager:()=>Jt,AuthenticateMiddleware:()=>be,BelongsTo:()=>ie,BelongsToMany:()=>ae,Broadcast:()=>Ui,Cache:()=>Ii,ColumnBuilder:()=>F,Connection:()=>f,Container:()=>J,Controller:()=>Ft,CorsMiddleware:()=>Ot,CsrfMiddleware:()=>le,DatabaseSessionStore:()=>Bt,ErrorHandler:()=>ye,Event:()=>ne,EventDispatcher:()=>Me,FileSessionStore:()=>Ht,ForbiddenError:()=>je,FormAuthorizationError:()=>G,FormRequest:()=>ve,FormValidationError:()=>Q,HasMany:()=>re,HasOne:()=>se,Hash:()=>Hs,HttpError:()=>N,Job:()=>X,Log:()=>Gt,LoggingMiddleware:()=>qt,Mailable:()=>Fe,Mailer:()=>Ys,MemorySessionStore:()=>V,Middleware:()=>$,MiddlewareStack:()=>H,Migration:()=>Te,Migrator:()=>ke,Model:()=>Nt,ModelNotFoundError:()=>Xt,NotFoundError:()=>Ne,Notification:()=>is,Notifier:()=>Oi,OriginMiddleware:()=>ce,QueryBuilder:()=>j,Queue:()=>Ns,RateLimitMiddleware:()=>oe,RedisSessionStore:()=>zt,RequireAuthMiddleware:()=>Vt,Schema:()=>B,Seeder:()=>It,ServiceProvider:()=>_e,Session:()=>pe,SessionMiddleware:()=>he,SignatureMiddleware:()=>Ut,Storage:()=>Li,TableBuilder:()=>Y,ThrottleMiddleware:()=>de,UnauthorizedError:()=>Ie,ValidationError:()=>z,abort:()=>es,abortIf:()=>wi,abortUnless:()=>Ci,apiFetch:()=>Hi,buildUrl:()=>zi,config:()=>Pi,container:()=>li,createFormAction:()=>Qi,createI18nHandle:()=>Wi,createReroute:()=>Ji,createSvelarApp:()=>xi,createSvelarHooks:()=>ur,env:()=>Si,getCsrfToken:()=>Ar,loadForm:()=>Gi,resource:()=>di,rules:()=>Ti,schema:()=>Gr,sequence:()=>mr,signJwt:()=>Xs,validate:()=>ki,validateForm:()=>Yi,verifyJwt:()=>er,z:()=>T});var ea=w(()=>{"use strict";ni();Is();js();P();Ps();Rs();oi();qs();Os();ci();ue();ui();pr();Ri();Ei();tr();ge();Us();dr();Mt();ts();_i();or();ji();ee();Wt();qi();Fi();Ki();Vi();Zi();pr()});var _r={};L(_r,{PluginRegistry:()=>ms});var Lr,ms,ps=w(()=>{"use strict";E();Lr=class{plugins=new Map;enabledPlugins=new Set;async discover(){let{join:e}=await import("path"),{existsSync:t,readdirSync:s}=await import("fs"),{readFile:r}=await import("fs/promises"),i=[],a=e(process.cwd(),"node_modules");if(!t(a))return i;try{let n=s(a,{withFileTypes:!0});for(let l of n){if(!l.isDirectory())continue;let c=l.name;if(c.startsWith("."))continue;let m=c.startsWith("svelar-");if(!m)continue;let p=e(a,c,"package.json");if(t(p))try{let h=await r(p,"utf-8"),u=JSON.parse(h),b=u.keywords?.includes("svelar-plugin");if(!m&&!b)continue;let y={name:u.name||c,version:u.version||"0.0.0",description:u.description||"",packageName:c,installed:!0,enabled:!1,hasConfig:!!u.svelar?.config,hasMigrations:!!u.svelar?.migrations};i.push(y),this.plugins.set(y.name,y)}catch{}}}catch{}return i}enable(e){let t=this.plugins.get(e);if(!t)throw new Error(`Plugin "${e}" not found in registry.`);this.enabledPlugins.add(e),t.enabled=!0}disable(e){this.enabledPlugins.delete(e);let t=this.plugins.get(e);t&&(t.enabled=!1)}isEnabled(e){return this.enabledPlugins.has(e)}list(){return[...this.plugins.values()]}listEnabled(){return[...this.plugins.values()].filter(e=>this.enabledPlugins.has(e.name))}get(e){return this.plugins.get(e)}register(e){this.plugins.set(e.name,e)}},ms=S("svelar.pluginRegistry",()=>new Lr)});var ra={};L(ra,{PluginPublisher:()=>Nr});var Mr,Nr,Ir=w(()=>{"use strict";E();Mr=class{async publish(e,t){let{mkdir:s,copyFile:r}=await import("fs/promises"),{join:i,dirname:a}=await import("path"),{existsSync:n}=await import("fs"),l={configs:[],migrations:[],assets:[]},c=e.publishables?.()||{};for(let[m,p]of Object.entries(c))for(let h of p){if(t?.only&&h.type!==t.only)continue;let u=i(process.cwd(),h.dest),b=a(u);if(!(n(u)&&!t?.force))try{await s(b,{recursive:!0}),await r(h.source,u),h.type==="config"?l.configs.push(u):h.type==="migration"?l.migrations.push(u):h.type==="asset"&&l.assets.push(u)}catch(y){console.warn(`Failed to publish ${h.source} to ${u}:`,y)}}return l}async preview(e){let t={configs:[],migrations:[],assets:[]},s=e.publishables?.()||{};for(let[r,i]of Object.entries(s))for(let a of i){let n=Qe("path").join(process.cwd(),a.dest);a.type==="config"?t.configs.push(n):a.type==="migration"?t.migrations.push(n):a.type==="asset"&&t.assets.push(n)}return t}},Nr=S("svelar.pluginPublisher",()=>new Mr)});var ia={};L(ia,{PluginInstaller:()=>$o});var jr,$o,aa=w(()=>{"use strict";E();ps();Ir();jr=class{async install(e,t){let{spawn:s}=await import("child_process"),{promisify:r}=await import("util"),{join:i}=await import("path"),{readFile:a}=await import("fs/promises"),{existsSync:n}=await import("fs");try{await this.runNpmInstall(e);let l=ms,c=await l.discover(),m;for(let h of c)if(h.packageName===e||h.name===e){m=h;break}if(!m)return{success:!1,pluginName:e,version:"0.0.0",published:null,error:`Plugin not found after installation. Make sure ${e} is a valid Svelar plugin.`};l.enable(m.name);let p=null;if(t?.publish!==!1)try{let h=await this.loadPluginClass(m.packageName);h&&(p=await Nr.publish(new h))}catch(h){console.warn("Failed to publish plugin assets:",h)}return{success:!0,pluginName:m.name,version:m.version,published:p}}catch(l){return{success:!1,pluginName:e,version:"0.0.0",published:null,error:l?.message??String(l)}}}async uninstall(e){try{let t=ms,s=t.get(e);return s?(t.disable(e),await this.runNpmUninstall(s.packageName),!0):!1}catch(t){return console.error("Failed to uninstall plugin:",t),!1}}async runNpmInstall(e){return new Promise((t,s)=>{let{spawn:r}=Qe("child_process"),i=r("npm",["install",e],{cwd:process.cwd(),stdio:"inherit"});i.on("close",a=>{a===0?t():s(new Error(`npm install exited with code ${a}`))}),i.on("error",s)})}async runNpmUninstall(e){return new Promise((t,s)=>{let{spawn:r}=Qe("child_process"),i=r("npm",["uninstall",e],{cwd:process.cwd(),stdio:"inherit"});i.on("close",a=>{a===0?t():s(new Error(`npm uninstall exited with code ${a}`))}),i.on("error",s)})}async loadPluginClass(e){try{let t=await import(e);return t.default||Object.values(t)[0]}catch{return null}}},$o=S("svelar.pluginInstaller",()=>new jr)});import{dirname as oa,join as Or}from"path";import{fileURLToPath as la,pathToFileURL as Ao}from"url";import{register as Do}from"module";import{readFileSync as ca,existsSync as Lo}from"fs";var Ge=class{commands=new Map;version;constructor(e="0.1.0"){this.version=e}register(e){let t=new e;return this.commands.set(t.name,t),this}add(e){return this.commands.set(e.name,e),this}async run(e=process.argv.slice(2)){let[t,...s]=e;if(!t||t==="--help"||t==="-h"){this.showHelp();return}if(t==="--version"||t==="-v"){console.log(`Svelar v${this.version}`);return}let r=this.commands.get(t);if(r||(console.error(`\x1B[31mUnknown command:\x1B[0m ${t}`),console.log("Run \x1B[36msvelar --help\x1B[0m for available commands."),process.exit(1)),s.includes("--help")||s.includes("-h")){this.showCommandHelp(r);return}let{args:i,flags:a}=this.parseArgs(s,r);try{await r.handle(i,a)}catch(n){let l=n instanceof Error?n.message:String(n);console.error(`\x1B[31mError:\x1B[0m ${l}`),n?.stack&&console.error(n.stack),process.exit(1)}}parseArgs(e,t){let s=[],r={};for(let i of t.flags)i.default!==void 0&&(r[i.name]=i.default);for(let i=0;i<e.length;i++){let a=e[i];if(a.startsWith("--")){let n=a.slice(2),l=n.indexOf("=");if(l!==-1){let p=n.slice(0,l);r[p]=n.slice(l+1);continue}let c=n;t.flags.find(p=>p.name===c)?.type==="boolean"?r[c]=!0:i+1<e.length&&!e[i+1].startsWith("-")?r[c]=e[++i]:r[c]=!0}else if(a.startsWith("-")&&a.length===2){let n=a.slice(1),l=t.flags.find(c=>c.alias===n);l&&(l.type==="boolean"?r[l.name]=!0:i+1<e.length&&(r[l.name]=e[++i]))}else s.push(a)}return{args:s,flags:r}}showCommandHelp(e){if(console.log(`
159
+ `,i=new TextEncoder().encode(r);for(let a of this.subscribers)if(a.userId!==s)try{a.controller.enqueue(i)}catch{}}},os=class{config;constructor(e){this.config=e}async send(e,t,s){let r=Array.isArray(e)?e:[e],i=JSON.stringify({name:t,channels:r,data:JSON.stringify(s)}),a=Math.floor(Date.now()/1e3).toString(),n=await this.md5(i),l=["POST",`/apps/${this.config.appId}/events`,[`auth_key=${this.config.key}`,`auth_timestamp=${a}`,"auth_version=1.0",`body_md5=${n}`].join("&")].join(`
160
+ `),c=await this.hmacSha256(this.config.secret,l),m=this.config.useTLS!==!1?"https":"http",p=this.config.host??`api-${this.config.cluster??"mt1"}.pusher.com`,h=this.config.port??(this.config.useTLS!==!1?443:80),u=`${m}://${p}:${h}/apps/${this.config.appId}/events?auth_key=${this.config.key}&auth_timestamp=${a}&auth_version=1.0&body_md5=${n}&auth_signature=${c}`,b=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},body:i});if(!b.ok){let y=await b.text();throw new Error(`Pusher API error (${b.status}): ${y}`)}}async authenticate(e,t,s){let r=`${e}:${t}`,i;s&&(i=JSON.stringify(s),r+=`:${i}`);let a=await this.hmacSha256(this.config.secret,r),n=`${this.config.key}:${a}`;return i?{auth:n,channel_data:i}:{auth:n}}get key(){return this.config.key}clientConfig(){let e={key:this.config.key,cluster:this.config.cluster??"mt1"};return this.config.host&&(e.wsHost=this.config.host,e.wsPort=this.config.port??6001,e.wssPort=this.config.port??6001,e.forceTLS=this.config.useTLS??!1,e.enabledTransports=["ws","wss"],e.disableStats=!0),e}async md5(e){let{createHash:t}=await import("crypto");return t("md5").update(e).digest("hex")}async hmacSha256(e,t){let{createHmac:s}=await import("crypto");return s("sha256",e).update(t).digest("hex")}},$r=class{constructor(e,t,s){this.manager=e;this.eventName=t;this.eventData=s}channels=[];on(...e){return this.channels.push(...e),this}async send(){for(let e of this.channels)await this.manager.sendToChannel(e,this.eventName,this.eventData)}},Ar=class{config={default:"sse",drivers:{sse:{driver:"sse"}}};sseChannels=new Map;channelAuth=new Map;pusherDriver=null;configure(e){this.config=e;let t=Object.values(e.drivers).find(s=>s.driver==="pusher");t&&t.driver==="pusher"&&(this.pusherDriver=new os(t))}channel(e,t){if(t){this.channelAuth.set(e,t);return}return this.sseChannels.has(e)||this.sseChannels.set(e,new Er(e)),this.sseChannels.get(e)}async authorize(e,t){if(kr(e)==="public")return!0;for(let[r,i]of this.channelAuth){let a=this.matchPattern(r,e);if(a!==null)return await i(t,a)}return!1}async authenticatePusher(e,t,s){if(!this.pusherDriver)throw new Error("Pusher driver is not configured. Call Broadcast.configure() first.");let r=kr(e);if(r==="public")return!1;let i=await this.authorize(e,s);if(i===!1)return!1;if(r==="presence"){let a=typeof i=="object"?{user_id:i.id??s.id,user_info:i}:{user_id:s.id,user_info:{id:s.id}};return this.pusherDriver.authenticate(t,e,a)}return this.pusherDriver.authenticate(t,e)}event(e,t){return new $r(this,e,t)}to(e,t){return{send:async(s,r)=>{await this.sendToChannel(e,s,r,t)}}}async sendToChannel(e,t,s,r){let i=this.config.drivers[this.config.default];switch(i?.driver){case"pusher":this.pusherDriver||(this.pusherDriver=new os(i)),await this.pusherDriver.send(e,t,s);break;case"log":console.log(`[Broadcast] ${e} \u2192 ${t}:`,JSON.stringify(s));break;default:for(let[,a]of this.sseChannels)a.name===e&&a.send(t,s,r);break}}subscribe(e,t,s){return this.channel(e).stream(t,s)}members(e){let t=this.sseChannels.get(e);return t?t.getMembers():[]}pusher(){if(!this.pusherDriver)throw new Error("Pusher driver is not configured.");return this.pusherDriver}activeChannels(){return[...new Set([...this.sseChannels.values()].map(e=>e.name))]}totalSubscribers(){let e=0;for(let t of this.sseChannels.values())e+=t.subscriberCount();return e}prune(){for(let[e,t]of this.sseChannels)t.subscriberCount()===0&&this.sseChannels.delete(e)}matchPattern(e,t){let s=[],r=e.replace(/[.*+?^${}()|[\]\\]/g,l=>l==="{"||l==="}"?l:`\\${l}`).replace(/\\\{(\w+)\\\}/g,(l,c)=>(s.push(c),"([^.]+)")).replace(/\{(\w+)\}/g,(l,c)=>(s.push(c),"([^.]+)")),i=new RegExp(`^${r}$`),a=t.match(i);if(!a)return null;let n={};for(let l=0;l<s.length;l++)n[s[l]]=a[l+1];return n}},zi=P("svelar.broadcast",()=>new Ar)});function ls(o,e,t){Wi&&Wi(o,e,{description:t})}async function Ji(o,e={}){let{csrfCookieName:t="XSRF-TOKEN",csrfHeaderName:s="X-CSRF-Token",showToast:r=!0,errorMessages:i={},...a}=e,n=(a.method||"GET").toUpperCase(),l=new Headers(a.headers);if(["POST","PUT","PATCH","DELETE"].includes(n)){let c=Lr(t);c&&l.set(s,c)}a.body&&typeof a.body=="string"&&!l.has("Content-Type")&&l.set("Content-Type","application/json"),l.has("Accept")||l.set("Accept","application/json");try{let c=await fetch(o,{...a,headers:l});return!c.ok&&r&&await No(c,{...Mo,...i}),c}catch(c){throw r&&ls("error","Network Error","Unable to connect. Check your internet connection."),c}}async function No(o,e){let t="";try{if((o.headers.get("content-type")??"").includes("application/json")){let a=await o.clone().json();if(t=a.message??"",o.status===422&&a.errors){let n=Object.entries(a.errors).map(([l,c])=>`${l}: ${c.join(", ")}`).slice(0,3).join(`
161
+ `);ls("warning",e[422]??"Validation Error",n);return}}}catch{}let s=t||e[o.status]||`Error ${o.status}`,r=o.status>=500?"error":o.status===429?"warning":"error";if(o.status===401){ls("warning",s,"Please sign in to continue.");return}ls(r,s)}function Lr(o="XSRF-TOKEN"){if(typeof document>"u")return null;let e=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t=document.cookie.match(new RegExp(`(?:^|;\\s*)${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}function Vi(o,e){if(!e)return o;let t=new URL(o,"http://localhost");for(let[s,r]of Object.entries(e))r!=null&&t.searchParams.set(s,String(r));return t.pathname+t.search}var Mo,Wi,Dr,we,sm,Qi=C(()=>{"use strict";Mo={400:"Invalid request. Please check your input.",401:"Your session has expired. Please sign in again.",403:"You don't have permission to do this.",404:"The requested resource was not found.",405:"This action is not allowed.",409:"A conflict occurred. Please refresh and try again.",419:"Page expired. Please refresh and try again.",422:"The submitted data is invalid.",429:"Too many requests. Please wait a moment.",500:"Something went wrong on our end.",502:"Service temporarily unavailable. Try again shortly.",503:"Service is under maintenance. Try again shortly.",504:"Request timed out. Please try again."},Wi=null;Dr=class o{_baseUrl="";_headers={};_timeout=3e4;_retries=0;_retryDelay=1e3;_query={};constructor(e){e?.baseUrl&&(this._baseUrl=e.baseUrl),e?.headers&&(this._headers={...e.headers}),e?.timeout&&(this._timeout=e.timeout),e?.retries&&(this._retries=e.retries),e?.retryDelay&&(this._retryDelay=e.retryDelay)}clone(){let e=new o;return e._baseUrl=this._baseUrl,e._headers={...this._headers},e._timeout=this._timeout,e._retries=this._retries,e._retryDelay=this._retryDelay,e._query={...this._query},e}baseUrl(e){let t=this.clone();return t._baseUrl=e,t}withHeaders(e){let t=this.clone();return t._headers={...t._headers,...e},t}withToken(e,t="Bearer"){return this.withHeaders({Authorization:`${t} ${e}`})}withBasicAuth(e,t){let s=Buffer.from(`${e}:${t}`).toString("base64");return this.withHeaders({Authorization:`Basic ${s}`})}accept(e){return this.withHeaders({Accept:e})}contentType(e){return this.withHeaders({"Content-Type":e})}timeout(e){let t=this.clone();return t._timeout=e,t}retry(e,t=1e3){let s=this.clone();return s._retries=e,s._retryDelay=t,s}query(e){let t=this.clone();for(let[s,r]of Object.entries(e))r!=null&&(t._query[s]=String(r));return t}async get(e){return this.request("GET",e)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async request(e,t,s){let r=this.buildFullUrl(t),i={...this._headers},a;s!==void 0&&(i["Content-Type"]||(i["Content-Type"]="application/json"),a=typeof s=="string"?s:JSON.stringify(s)),i.Accept||(i.Accept="application/json");let n=null,l=1+this._retries;for(let c=0;c<l;c++){c>0&&await new Promise(m=>setTimeout(m,this._retryDelay*c));try{let m=new AbortController,p=setTimeout(()=>m.abort(),this._timeout),h=await fetch(r,{method:e,headers:i,body:a,signal:m.signal});if(clearTimeout(p),!h.ok&&h.status<500&&c<l-1,!h.ok&&h.status>=500&&c<l-1){n=new we(`HTTP ${h.status}: ${h.statusText}`,h.status,await h.text());continue}let u=h.headers.get("content-type")??"",b;if(u.includes("application/json")?b=await h.json():b=await h.text(),!h.ok)throw new we(`HTTP ${h.status}: ${typeof b=="string"?b:JSON.stringify(b)}`,h.status,b);return{data:b,status:h.status,headers:h.headers,ok:!0}}catch(m){if(m instanceof we)throw m;if(n=m,m.name==="AbortError"&&(n=new we("Request timed out",0,null)),c>=l-1)break}}throw n??new Error("HTTP request failed")}buildFullUrl(e){let t=this._baseUrl?`${this._baseUrl.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`:e,s=Object.entries(this._query);if(s.length>0){let r=new URL(t);for(let[i,a]of s)r.searchParams.set(i,a);t=r.toString()}return t}},we=class extends Error{constructor(t,s,r){super(t);this.status=s;this.body=r;this.name="HttpRequestError"}},sm=new Dr});function Gi(o){let{paraglideMiddleware:e,getTextDirection:t=()=>"ltr",langPlaceholder:s="%lang%",dirPlaceholder:r="%dir%"}=o;return({event:i,resolve:a})=>e(i.request,({request:n,locale:l})=>(i.request=n,a(i,{transformPageChunk:({html:c})=>c.replace(s,l).replace(r,t(l))})))}function Yi(o){return e=>o.deLocalizeUrl(e.url).pathname}var Zi=C(()=>{"use strict"});function Xi(o,e,t={}){return async s=>{let{superValidate:r,fail:i,message:a}=await import("sveltekit-superforms"),{zod:n}=await import("sveltekit-superforms/adapters"),l=await r(s,n(o));if(!l.valid)return i(400,{form:l});try{let c=await e(l.data,s);if(t.redirectTo){let{redirect:m}=await import("@sveltejs/kit");throw m(303,t.redirectTo)}return c??{form:l}}catch(c){if(c?.status>=300&&c?.status<400)throw c;return a(l,t.errorMessage||c.message||"An error occurred",{status:c.status||400})}}}async function ea(o,e){let{superValidate:t}=await import("sveltekit-superforms"),{zod:s}=await import("sveltekit-superforms/adapters");return t(e??null,s(o))}async function ta(o,e){let t=await o.request.formData(),s={};for(let[i,a]of t.entries())s[i]=a;let r=e.safeParse(s);if(!r.success){let{FormValidationError:i}=await Promise.resolve().then(()=>(rs(),_i));throw new i(r.error.flatten().fieldErrors)}return r.data}var sa=C(()=>{"use strict";rs()});var ra={};L(ra,{Application:()=>qt,AuthManager:()=>Qt,AuthenticateMiddleware:()=>be,BelongsTo:()=>ie,BelongsToMany:()=>ae,Broadcast:()=>zi,Cache:()=>Ui,ColumnBuilder:()=>F,Connection:()=>f,Container:()=>J,Controller:()=>Ht,CorsMiddleware:()=>Ut,CsrfMiddleware:()=>le,DatabaseSessionStore:()=>zt,ErrorHandler:()=>ye,Event:()=>ne,EventDispatcher:()=>Me,FileSessionStore:()=>Kt,ForbiddenError:()=>je,FormAuthorizationError:()=>G,FormRequest:()=>ve,FormValidationError:()=>Q,HasMany:()=>re,HasOne:()=>se,Hash:()=>Ks,HttpError:()=>N,Job:()=>X,Log:()=>Zt,LoggingMiddleware:()=>Ft,Mailable:()=>Fe,Mailer:()=>Xs,MemorySessionStore:()=>V,Middleware:()=>$,MiddlewareStack:()=>H,Migration:()=>Te,Migrator:()=>ke,Model:()=>jt,ModelNotFoundError:()=>ts,NotFoundError:()=>Ne,Notification:()=>ns,Notifier:()=>Bi,OriginMiddleware:()=>ce,QueryBuilder:()=>j,Queue:()=>js,RateLimitMiddleware:()=>oe,RedisSessionStore:()=>Wt,RequireAuthMiddleware:()=>Gt,Schema:()=>B,Seeder:()=>Ot,ServiceProvider:()=>_e,Session:()=>pe,SessionMiddleware:()=>he,SignatureMiddleware:()=>Bt,Storage:()=>Ii,TableBuilder:()=>Y,ThrottleMiddleware:()=>de,UnauthorizedError:()=>Ie,ValidationError:()=>z,abort:()=>ss,abortIf:()=>Si,abortUnless:()=>Ri,apiFetch:()=>Ji,buildUrl:()=>Vi,config:()=>Ei,container:()=>mi,createFormAction:()=>Xi,createI18nHandle:()=>Gi,createReroute:()=>Yi,createSvelarApp:()=>Ti,createSvelarHooks:()=>pr,env:()=>ki,getCsrfToken:()=>Lr,loadForm:()=>ea,resource:()=>hi,rules:()=>Ai,schema:()=>ei,sequence:()=>hr,signJwt:()=>tr,validate:()=>Di,validateForm:()=>ta,verifyJwt:()=>sr,z:()=>T});var ia=C(()=>{"use strict";di();Os();qs();S();Ts();ks();ui();Fs();Us();pi();ue();gi();gr();$i();Li();rr();ge();Bs();mr();It();rs();ji();cr();Fi();ee();Vt();Hi();Ki();Qi();Zi();sa();gr()});var Nr={};L(Nr,{PluginRegistry:()=>hs});var Mr,hs,gs=C(()=>{"use strict";E();Mr=class{plugins=new Map;enabledPlugins=new Set;async discover(){let{join:e}=await import("path"),{existsSync:t,readdirSync:s}=await import("fs"),{readFile:r}=await import("fs/promises"),i=[],a=e(process.cwd(),"node_modules");if(!t(a))return i;try{let n=s(a,{withFileTypes:!0});for(let l of n){if(!l.isDirectory())continue;let c=l.name;if(c.startsWith("."))continue;let m=c.startsWith("svelar-");if(!m)continue;let p=e(a,c,"package.json");if(t(p))try{let h=await r(p,"utf-8"),u=JSON.parse(h),b=u.keywords?.includes("svelar-plugin");if(!m&&!b)continue;let y={name:u.name||c,version:u.version||"0.0.0",description:u.description||"",packageName:c,installed:!0,enabled:!1,hasConfig:!!u.svelar?.config,hasMigrations:!!u.svelar?.migrations};i.push(y),this.plugins.set(y.name,y)}catch{}}}catch{}return i}enable(e){let t=this.plugins.get(e);if(!t)throw new Error(`Plugin "${e}" not found in registry.`);this.enabledPlugins.add(e),t.enabled=!0}disable(e){this.enabledPlugins.delete(e);let t=this.plugins.get(e);t&&(t.enabled=!1)}isEnabled(e){return this.enabledPlugins.has(e)}list(){return[...this.plugins.values()]}listEnabled(){return[...this.plugins.values()].filter(e=>this.enabledPlugins.has(e.name))}get(e){return this.plugins.get(e)}register(e){this.plugins.set(e.name,e)}},hs=P("svelar.pluginRegistry",()=>new Mr)});var oa={};L(oa,{PluginPublisher:()=>jr});var Ir,jr,Or=C(()=>{"use strict";E();Ir=class{async publish(e,t){let{mkdir:s,copyFile:r}=await import("fs/promises"),{join:i,dirname:a}=await import("path"),{existsSync:n}=await import("fs"),l={configs:[],migrations:[],assets:[]},c=e.publishables?.()||{};for(let[m,p]of Object.entries(c))for(let h of p){if(t?.only&&h.type!==t.only)continue;let u=i(process.cwd(),h.dest),b=a(u);if(!(n(u)&&!t?.force))try{await s(b,{recursive:!0}),await r(h.source,u),h.type==="config"?l.configs.push(u):h.type==="migration"?l.migrations.push(u):h.type==="asset"&&l.assets.push(u)}catch(y){console.warn(`Failed to publish ${h.source} to ${u}:`,y)}}return l}async preview(e){let t={configs:[],migrations:[],assets:[]},s=e.publishables?.()||{};for(let[r,i]of Object.entries(s))for(let a of i){let n=Qe("path").join(process.cwd(),a.dest);a.type==="config"?t.configs.push(n):a.type==="migration"?t.migrations.push(n):a.type==="asset"&&t.assets.push(n)}return t}},jr=P("svelar.pluginPublisher",()=>new Ir)});var la={};L(la,{PluginInstaller:()=>Bo});var qr,Bo,ca=C(()=>{"use strict";E();gs();Or();qr=class{async install(e,t){let{spawn:s}=await import("child_process"),{promisify:r}=await import("util"),{join:i}=await import("path"),{readFile:a}=await import("fs/promises"),{existsSync:n}=await import("fs");try{await this.runNpmInstall(e);let l=hs,c=await l.discover(),m;for(let h of c)if(h.packageName===e||h.name===e){m=h;break}if(!m)return{success:!1,pluginName:e,version:"0.0.0",published:null,error:`Plugin not found after installation. Make sure ${e} is a valid Svelar plugin.`};l.enable(m.name);let p=null;if(t?.publish!==!1)try{let h=await this.loadPluginClass(m.packageName);h&&(p=await jr.publish(new h))}catch(h){console.warn("Failed to publish plugin assets:",h)}return{success:!0,pluginName:m.name,version:m.version,published:p}}catch(l){return{success:!1,pluginName:e,version:"0.0.0",published:null,error:l?.message??String(l)}}}async uninstall(e){try{let t=hs,s=t.get(e);return s?(t.disable(e),await this.runNpmUninstall(s.packageName),!0):!1}catch(t){return console.error("Failed to uninstall plugin:",t),!1}}async runNpmInstall(e){return new Promise((t,s)=>{let{spawn:r}=Qe("child_process"),i=r("npm",["install",e],{cwd:process.cwd(),stdio:"inherit"});i.on("close",a=>{a===0?t():s(new Error(`npm install exited with code ${a}`))}),i.on("error",s)})}async runNpmUninstall(e){return new Promise((t,s)=>{let{spawn:r}=Qe("child_process"),i=r("npm",["uninstall",e],{cwd:process.cwd(),stdio:"inherit"});i.on("close",a=>{a===0?t():s(new Error(`npm uninstall exited with code ${a}`))}),i.on("error",s)})}async loadPluginClass(e){try{let t=await import(e);return t.default||Object.values(t)[0]}catch{return null}}},Bo=P("svelar.pluginInstaller",()=>new qr)});import{dirname as ua,join as Ur}from"path";import{fileURLToPath as ma,pathToFileURL as Ho}from"url";import{register as zo}from"module";import{readFileSync as pa,existsSync as Ko}from"fs";var Ge=class{commands=new Map;version;constructor(e="0.1.0"){this.version=e}register(e){let t=new e;return this.commands.set(t.name,t),this}add(e){return this.commands.set(e.name,e),this}async run(e=process.argv.slice(2)){let[t,...s]=e;if(!t||t==="--help"||t==="-h"){this.showHelp();return}if(t==="--version"||t==="-v"){console.log(`Svelar v${this.version}`);return}let r=this.commands.get(t);if(r||(console.error(`\x1B[31mUnknown command:\x1B[0m ${t}`),console.log("Run \x1B[36msvelar --help\x1B[0m for available commands."),process.exit(1)),s.includes("--help")||s.includes("-h")){this.showCommandHelp(r);return}let{args:i,flags:a}=this.parseArgs(s,r);try{await r.handle(i,a)}catch(n){let l=n instanceof Error?n.message:String(n);console.error(`\x1B[31mError:\x1B[0m ${l}`),n?.stack&&console.error(n.stack),process.exit(1)}}parseArgs(e,t){let s=[],r={};for(let i of t.flags)i.default!==void 0&&(r[i.name]=i.default);for(let i=0;i<e.length;i++){let a=e[i];if(a.startsWith("--")){let n=a.slice(2),l=n.indexOf("=");if(l!==-1){let p=n.slice(0,l);r[p]=n.slice(l+1);continue}let c=n;t.flags.find(p=>p.name===c)?.type==="boolean"?r[c]=!0:i+1<e.length&&!e[i+1].startsWith("-")?r[c]=e[++i]:r[c]=!0}else if(a.startsWith("-")&&a.length===2){let n=a.slice(1),l=t.flags.find(c=>c.alias===n);l&&(l.type==="boolean"?r[l.name]=!0:i+1<e.length&&(r[l.name]=e[++i]))}else s.push(a)}return{args:s,flags:r}}showCommandHelp(e){if(console.log(`
162
162
  \x1B[33mDescription:\x1B[0m`),console.log(` ${e.description}
163
163
  `),console.log("\x1B[33mUsage:\x1B[0m"),console.log(` svelar ${e.name} [options]
164
164
  `),e.flags.length>0){console.log("\x1B[33mOptions:\x1B[0m");for(let t of e.flags){let s=t.alias?`-${t.alias}, `:" ",r=`--${t.name}`,i=24-s.length-r.length;console.log(` ${s}${r}${" ".repeat(Math.max(1,i))}${t.description}`)}console.log()}}showHelp(){console.log(`
@@ -172,7 +172,7 @@ id: ${Date.now()}
172
172
  svelar <command> [arguments] [options]
173
173
 
174
174
  \x1B[33mAvailable Commands:\x1B[0m`);let e=new Map;for(let[,t]of this.commands){let s=t.name.includes(":")?t.name.split(":")[0]:"general";e.has(s)||e.set(s,[]),e.get(s).push(t)}for(let[t,s]of e){console.log(`
175
- \x1B[32m${t}\x1B[0m`);for(let r of s){let i=30-r.name.length;console.log(` \x1B[36m${r.name}\x1B[0m${" ".repeat(Math.max(1,i))}${r.description}`)}}console.log()}};import{existsSync as ua}from"fs";import{join as Pe}from"path";var g=class{arguments=[];flags=[];async bootstrap(){let{join:e}=await import("path"),{existsSync:t,readFileSync:s}=await import("fs"),{Connection:r}=await Promise.resolve().then(()=>(P(),R)),i=process.cwd();try{r.getDriver();return}catch{}let a=e(i,"svelar.database.json");if(t(a))try{let c=s(a,"utf-8"),m=JSON.parse(c);r.configure(m),this.info("Database configured from svelar.database.json");return}catch(c){this.warn(`Failed to parse svelar.database.json: ${String(c?.message??c)}`)}let n=process.env.DB_DRIVER??"sqlite",l=process.env.DB_PATH??"database.db";r.configure({default:n,connections:{[n]:{driver:n,filename:l,host:process.env.DB_HOST,port:process.env.DB_PORT?parseInt(process.env.DB_PORT):void 0,database:process.env.DB_NAME,user:process.env.DB_USER,password:process.env.DB_PASSWORD}}}),this.info(`Using ${n} database${n==="sqlite"?`: ${l}`:""}`)}log(e){console.log(e)}info(e){console.log(`\x1B[34mINFO\x1B[0m ${e}`)}success(e){console.log(`\x1B[32m\u2713\x1B[0m ${e}`)}warn(e){console.log(`\x1B[33mWARN\x1B[0m ${e}`)}error(e){console.error(`\x1B[31mERROR\x1B[0m ${e}`)}table(e,t){let s=e.map((a,n)=>Math.max(a.length,...t.map(l=>(l[n]??"").length))),r=s.map(a=>"\u2500".repeat(a+2)).join("\u253C"),i=a=>a.map((n,l)=>` ${(n??"").padEnd(s[l])} `).join("\u2502");console.log(i(e)),console.log(r);for(let a of t)console.log(i(a))}newLine(){console.log()}isDDD(){return ua(Pe(process.cwd(),"src","lib","modules"))}sharedDir(e){return this.isDDD()?Pe(process.cwd(),"src","lib","shared",e):Pe(process.cwd(),"src","lib",e)}moduleDir(e,t){return this.isDDD()?Pe(process.cwd(),"src","lib","modules",e):Pe(process.cwd(),"src","lib",t)}};import{writeFileSync as vs,mkdirSync as ws,existsSync as ma}from"fs";import{join as Ye}from"path";var Ze=class extends g{name="make:model";description="Create a new model class";arguments=["name"];flags=[{name:"migration",alias:"m",description:"Also create a migration",type:"boolean"},{name:"controller",alias:"c",description:"Also create a controller",type:"boolean"},{name:"resource",alias:"r",description:"Create a resource controller",type:"boolean"},{name:"all",alias:"a",description:"Create model, migration, and controller",type:"boolean"},{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a model name.");return}let r=this.toSnakeCase(this.pluralize(s)),i=t.module||this.toSnakeCase(this.pluralize(s));!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${i}" as module. Consider: --module ${i}`);let a=this.moduleDir(i,"models");ws(a,{recursive:!0});let n=Ye(a,`${s}.ts`);if(ma(n)){this.warn(`Model ${s} already exists at ${n}`);return}let l=`import { Model } from '@beeblock/svelar/orm';
175
+ \x1B[32m${t}\x1B[0m`);for(let r of s){let i=30-r.name.length;console.log(` \x1B[36m${r.name}\x1B[0m${" ".repeat(Math.max(1,i))}${r.description}`)}}console.log()}};import{existsSync as ga}from"fs";import{join as Se}from"path";var g=class{arguments=[];flags=[];async bootstrap(){let{join:e}=await import("path"),{existsSync:t,readFileSync:s}=await import("fs"),{Connection:r}=await Promise.resolve().then(()=>(S(),R)),i=process.cwd();try{r.getDriver();return}catch{}let a=e(i,"svelar.database.json");if(t(a))try{let c=s(a,"utf-8"),m=JSON.parse(c);r.configure(m),this.info("Database configured from svelar.database.json");return}catch(c){this.warn(`Failed to parse svelar.database.json: ${String(c?.message??c)}`)}let n=process.env.DB_DRIVER??"sqlite",l=process.env.DB_PATH??"database.db";r.configure({default:n,connections:{[n]:{driver:n,filename:l,host:process.env.DB_HOST,port:process.env.DB_PORT?parseInt(process.env.DB_PORT):void 0,database:process.env.DB_NAME,user:process.env.DB_USER,password:process.env.DB_PASSWORD}}}),this.info(`Using ${n} database${n==="sqlite"?`: ${l}`:""}`)}log(e){console.log(e)}info(e){console.log(`\x1B[34mINFO\x1B[0m ${e}`)}success(e){console.log(`\x1B[32m\u2713\x1B[0m ${e}`)}warn(e){console.log(`\x1B[33mWARN\x1B[0m ${e}`)}error(e){console.error(`\x1B[31mERROR\x1B[0m ${e}`)}table(e,t){let s=e.map((a,n)=>Math.max(a.length,...t.map(l=>(l[n]??"").length))),r=s.map(a=>"\u2500".repeat(a+2)).join("\u253C"),i=a=>a.map((n,l)=>` ${(n??"").padEnd(s[l])} `).join("\u2502");console.log(i(e)),console.log(r);for(let a of t)console.log(i(a))}newLine(){console.log()}isDDD(){return ga(Se(process.cwd(),"src","lib","modules"))}sharedDir(e){return this.isDDD()?Se(process.cwd(),"src","lib","shared",e):Se(process.cwd(),"src","lib",e)}moduleDir(e,t){return this.isDDD()?Se(process.cwd(),"src","lib","modules",e):Se(process.cwd(),"src","lib",t)}};import{writeFileSync as Cs,mkdirSync as xs,existsSync as fa}from"fs";import{join as Ye}from"path";var Ze=class extends g{name="make:model";description="Create a new model class";arguments=["name"];flags=[{name:"migration",alias:"m",description:"Also create a migration",type:"boolean"},{name:"controller",alias:"c",description:"Also create a controller",type:"boolean"},{name:"resource",alias:"r",description:"Create a resource controller",type:"boolean"},{name:"all",alias:"a",description:"Create model, migration, and controller",type:"boolean"},{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a model name.");return}let r=this.toSnakeCase(this.pluralize(s)),i=t.module||this.toSnakeCase(this.pluralize(s));!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${i}" as module. Consider: --module ${i}`);let a=this.moduleDir(i,"models");xs(a,{recursive:!0});let n=Ye(a,`${s}.ts`);if(fa(n)){this.warn(`Model ${s} already exists at ${n}`);return}let l=`import { Model } from '@beeblock/svelar/orm';
176
176
 
177
177
  export class ${s} extends Model {
178
178
  static table = '${r}';
@@ -189,7 +189,7 @@ export class ${s} extends Model {
189
189
  // return this.hasMany(Post, 'user_id');
190
190
  // }
191
191
  }
192
- `;vs(n,l);let c=this.isDDD()?`src/lib/modules/${i}`:"src/lib/models";if(this.success(`Model created: ${c}/${s}.ts`),t.migration||t.all){let p=`${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}_create_${r}_table`,h=Ye(process.cwd(),"src","lib","database","migrations");ws(h,{recursive:!0});let u=`import { Migration } from '@beeblock/svelar/database';
192
+ `;Cs(n,l);let c=this.isDDD()?`src/lib/modules/${i}`:"src/lib/models";if(this.success(`Model created: ${c}/${s}.ts`),t.migration||t.all){let p=`${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}_create_${r}_table`,h=Ye(process.cwd(),"src","lib","database","migrations");xs(h,{recursive:!0});let u=`import { Migration } from '@beeblock/svelar/database';
193
193
 
194
194
  export default class Create${s}sTable extends Migration {
195
195
  async up() {
@@ -206,7 +206,7 @@ export default class Create${s}sTable extends Migration {
206
206
  await this.schema.dropTable('${r}');
207
207
  }
208
208
  }
209
- `;vs(Ye(h,`${p}.ts`),u),this.success(`Migration created: src/lib/database/migrations/${p}.ts`)}if(t.controller||t.resource||t.all){let m=`${s}Controller`,p=this.moduleDir(i,"controllers");ws(p,{recursive:!0});let h=t.resource||t.all,u=this.isDDD()?`./${s}.js`:`../models/${s}.js`,b=h?this.generateResourceController(s,m,u):this.generateBasicController(s,m,u);vs(Ye(p,`${m}.ts`),b);let y=this.isDDD()?`src/lib/modules/${i}`:"src/lib/controllers";this.success(`Controller created: ${y}/${m}.ts`)}}generateResourceController(e,t,s=`./${e}.js`){return`import { Controller, type RequestEvent } from '@beeblock/svelar/routing';
209
+ `;Cs(Ye(h,`${p}.ts`),u),this.success(`Migration created: src/lib/database/migrations/${p}.ts`)}if(t.controller||t.resource||t.all){let m=`${s}Controller`,p=this.moduleDir(i,"controllers");xs(p,{recursive:!0});let h=t.resource||t.all,u=this.isDDD()?`./${s}.js`:`../models/${s}.js`,b=h?this.generateResourceController(s,m,u):this.generateBasicController(s,m,u);Cs(Ye(p,`${m}.ts`),b);let y=this.isDDD()?`src/lib/modules/${i}`:"src/lib/controllers";this.success(`Controller created: ${y}/${m}.ts`)}}generateResourceController(e,t,s=`./${e}.js`){return`import { Controller, type RequestEvent } from '@beeblock/svelar/routing';
210
210
  import { z } from '@beeblock/svelar/validation';
211
211
  import { ${e} } from '${s}';
212
212
 
@@ -258,7 +258,7 @@ export class ${t} extends Controller {
258
258
  return this.json(items);
259
259
  }
260
260
  }
261
- `}toSnakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}pluralize(e){return e.endsWith("y")?e.slice(0,-1)+"ies":e.endsWith("s")||e.endsWith("x")||e.endsWith("z")||e.endsWith("ch")||e.endsWith("sh")?e+"es":e+"s"}};import{writeFileSync as pa,mkdirSync as ha}from"fs";import{join as Ur}from"path";var Xe=class extends g{name="make:migration";description="Create a new migration file";arguments=["name"];flags=[{name:"create",description:"Table to create",type:"string"},{name:"table",description:"Table to modify",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a migration name (e.g. create_users_table).");return}let r=Ur(process.cwd(),"src","lib","database","migrations");ha(r,{recursive:!0});let a=`${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}_${s}`,n=this.toPascalCase(s),l=t.create??this.detectTableName(s,"create"),c=t.table??this.detectTableName(s,"add"),m;l?m=`import { Migration } from '@beeblock/svelar/database';
261
+ `}toSnakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}pluralize(e){return e.endsWith("y")?e.slice(0,-1)+"ies":e.endsWith("s")||e.endsWith("x")||e.endsWith("z")||e.endsWith("ch")||e.endsWith("sh")?e+"es":e+"s"}};import{writeFileSync as ba,mkdirSync as ya}from"fs";import{join as Br}from"path";var Xe=class extends g{name="make:migration";description="Create a new migration file";arguments=["name"];flags=[{name:"create",description:"Table to create",type:"string"},{name:"table",description:"Table to modify",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a migration name (e.g. create_users_table).");return}let r=Br(process.cwd(),"src","lib","database","migrations");ya(r,{recursive:!0});let a=`${new Date().toISOString().replace(/[^0-9]/g,"").slice(0,14)}_${s}`,n=this.toPascalCase(s),l=t.create??this.detectTableName(s,"create"),c=t.table??this.detectTableName(s,"add"),m;l?m=`import { Migration } from '@beeblock/svelar/database';
262
262
 
263
263
  export default class ${n} extends Migration {
264
264
  async up() {
@@ -298,7 +298,7 @@ export default class ${n} extends Migration {
298
298
  // Reverse the migration
299
299
  }
300
300
  }
301
- `,pa(Ur(r,`${a}.ts`),m),this.success(`Migration created: src/lib/database/migrations/${a}.ts`)}detectTableName(e,t){let s=e.match(new RegExp(`${t}_(.+?)_table`));return s?s[1]:null}toPascalCase(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}};import{writeFileSync as ga,mkdirSync as fa,existsSync as ba}from"fs";import{join as ya}from"path";var et=class extends g{name="make:controller";description="Create a new controller class";arguments=["name"];flags=[{name:"resource",alias:"r",description:"Create a resource controller with CRUD methods",type:"boolean"},{name:"model",alias:"m",description:"Model name for resource controller",type:"string"},{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a controller name.");return}let r=s.endsWith("Controller")?s:`${s}Controller`,i=r.replace(/Controller$/,""),a=t.module||i.toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${a}" as module. Consider: --module ${a}`);let n=this.moduleDir(a,"controllers");fa(n,{recursive:!0});let l=ya(n,`${r}.ts`);if(ba(l)){this.warn(`Controller ${r} already exists.`);return}let c=t.model?this.isDDD()?`./${t.model}.js`:`../models/${t.model}.js`:void 0,m=t.resource?this.generateResourceController(r,t.model,c):this.generateBasicController(r);ga(l,m);let p=this.isDDD()?`src/lib/modules/${a}`:"src/lib/controllers";this.success(`Controller created: ${p}/${r}.ts`)}generateResourceController(e,t,s){return`import { Controller, type RequestEvent } from '@beeblock/svelar/routing';
301
+ `,ba(Br(r,`${a}.ts`),m),this.success(`Migration created: src/lib/database/migrations/${a}.ts`)}detectTableName(e,t){let s=e.match(new RegExp(`${t}_(.+?)_table`));return s?s[1]:null}toPascalCase(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}};import{writeFileSync as va,mkdirSync as wa,existsSync as Ca}from"fs";import{join as xa}from"path";var et=class extends g{name="make:controller";description="Create a new controller class";arguments=["name"];flags=[{name:"resource",alias:"r",description:"Create a resource controller with CRUD methods",type:"boolean"},{name:"model",alias:"m",description:"Model name for resource controller",type:"string"},{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a controller name.");return}let r=s.endsWith("Controller")?s:`${s}Controller`,i=r.replace(/Controller$/,""),a=t.module||i.toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${a}" as module. Consider: --module ${a}`);let n=this.moduleDir(a,"controllers");wa(n,{recursive:!0});let l=xa(n,`${r}.ts`);if(Ca(l)){this.warn(`Controller ${r} already exists.`);return}let c=t.model?this.isDDD()?`./${t.model}.js`:`../models/${t.model}.js`:void 0,m=t.resource?this.generateResourceController(r,t.model,c):this.generateBasicController(r);va(l,m);let p=this.isDDD()?`src/lib/modules/${a}`:"src/lib/controllers";this.success(`Controller created: ${p}/${r}.ts`)}generateResourceController(e,t,s){return`import { Controller, type RequestEvent } from '@beeblock/svelar/routing';
302
302
  import { z } from '@beeblock/svelar/validation';
303
303
  ${t&&s?`import { ${t} } from '${s}';
304
304
  `:""}
@@ -344,7 +344,7 @@ export class ${e} extends Controller {
344
344
  return this.json({ message: 'Hello from ${e}' });
345
345
  }
346
346
  }
347
- `}};import{writeFileSync as va,mkdirSync as wa,existsSync as Ca}from"fs";import{join as xa}from"path";var tt=class extends g{name="make:middleware";description="Create a new middleware class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a middleware name.");return}let s=t.endsWith("Middleware")?t:`${t}Middleware`,r=this.sharedDir("middleware");wa(r,{recursive:!0});let i=xa(r,`${s}.ts`);if(Ca(i)){this.warn(`Middleware ${s} already exists.`);return}let a=`import { Middleware, type MiddlewareContext, type NextFunction } from '@beeblock/svelar/middleware';
347
+ `}};import{writeFileSync as Pa,mkdirSync as Sa,existsSync as Ra}from"fs";import{join as Ta}from"path";var tt=class extends g{name="make:middleware";description="Create a new middleware class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a middleware name.");return}let s=t.endsWith("Middleware")?t:`${t}Middleware`,r=this.sharedDir("middleware");Sa(r,{recursive:!0});let i=Ta(r,`${s}.ts`);if(Ra(i)){this.warn(`Middleware ${s} already exists.`);return}let a=`import { Middleware, type MiddlewareContext, type NextFunction } from '@beeblock/svelar/middleware';
348
348
 
349
349
  export class ${s} extends Middleware {
350
350
  async handle(ctx: MiddlewareContext, next: NextFunction): Promise<Response | void> {
@@ -357,7 +357,7 @@ export class ${s} extends Middleware {
357
357
  return response;
358
358
  }
359
359
  }
360
- `;va(i,a);let n=this.isDDD()?`src/lib/shared/middleware/${s}.ts`:`src/lib/middleware/${s}.ts`;this.success(`Middleware created: ${n}`)}};import{writeFileSync as Sa,mkdirSync as Pa,existsSync as Ra}from"fs";import{join as Ta}from"path";var st=class extends g{name="make:provider";description="Create a new service provider class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a provider name.");return}let s=t.endsWith("ServiceProvider")?t:`${t}ServiceProvider`,r=this.sharedDir("providers");Pa(r,{recursive:!0});let i=Ta(r,`${s}.ts`);if(Ra(i)){this.warn(`Provider ${s} already exists.`);return}let a=`import { ServiceProvider } from '@beeblock/svelar/container';
360
+ `;Pa(i,a);let n=this.isDDD()?`src/lib/shared/middleware/${s}.ts`:`src/lib/middleware/${s}.ts`;this.success(`Middleware created: ${n}`)}};import{writeFileSync as ka,mkdirSync as Ea,existsSync as $a}from"fs";import{join as Aa}from"path";var st=class extends g{name="make:provider";description="Create a new service provider class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a provider name.");return}let s=t.endsWith("ServiceProvider")?t:`${t}ServiceProvider`,r=this.sharedDir("providers");Ea(r,{recursive:!0});let i=Aa(r,`${s}.ts`);if($a(i)){this.warn(`Provider ${s} already exists.`);return}let a=`import { ServiceProvider } from '@beeblock/svelar/container';
361
361
  import type { Container } from '@beeblock/svelar/container';
362
362
 
363
363
  export class ${s} extends ServiceProvider {
@@ -378,7 +378,7 @@ export class ${s} extends ServiceProvider {
378
378
  // Initialization logic here
379
379
  }
380
380
  }
381
- `;Sa(i,a);let n=this.isDDD()?`src/lib/shared/providers/${s}.ts`:`src/lib/providers/${s}.ts`;this.success(`Provider created: ${n}`)}};import{writeFileSync as ka,mkdirSync as Ea,existsSync as $a}from"fs";import{join as Fr}from"path";var rt=class extends g{name="make:seeder";description="Create a new database seeder class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a seeder name.");return}let s=t.endsWith("Seeder")?t:`${t}Seeder`,r=Fr(process.cwd(),"src","lib","database","seeders");Ea(r,{recursive:!0});let i=Fr(r,`${s}.ts`);if($a(i)){this.warn(`Seeder ${s} already exists.`);return}let a=`import { Seeder } from '@beeblock/svelar/database';
381
+ `;ka(i,a);let n=this.isDDD()?`src/lib/shared/providers/${s}.ts`:`src/lib/providers/${s}.ts`;this.success(`Provider created: ${n}`)}};import{writeFileSync as Da,mkdirSync as La,existsSync as _a}from"fs";import{join as Hr}from"path";var rt=class extends g{name="make:seeder";description="Create a new database seeder class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a seeder name.");return}let s=t.endsWith("Seeder")?t:`${t}Seeder`,r=Hr(process.cwd(),"src","lib","database","seeders");La(r,{recursive:!0});let i=Hr(r,`${s}.ts`);if(_a(i)){this.warn(`Seeder ${s} already exists.`);return}let a=`import { Seeder } from '@beeblock/svelar/database';
382
382
 
383
383
  export class ${s} extends Seeder {
384
384
  async run(): Promise<void> {
@@ -387,7 +387,7 @@ export class ${s} extends Seeder {
387
387
  // await User.create({ name: 'Admin', email: 'admin@example.com' });
388
388
  }
389
389
  }
390
- `;ka(i,a),this.success(`Seeder created: src/lib/database/seeders/${s}.ts`)}};import{writeFileSync as Aa,mkdirSync as Da,existsSync as La}from"fs";import{join as _a}from"path";var it=class extends g{name="make:service";description="Create a new service class";arguments=["name"];flags=[{name:"crud",description:"Create a CRUD service with model",type:"boolean"},{name:"model",alias:"m",description:"Model name for CRUD service",type:"string"},{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a service name.");return}let r=s.endsWith("Service")?s:`${s}Service`,i=r.replace(/Service$/,""),a=t.module||i.toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${a}" as module. Consider: --module ${a}`);let n=this.moduleDir(a,"services");Da(n,{recursive:!0});let l=_a(n,`${r}.ts`);if(La(l)){this.warn(`Service ${r} already exists.`);return}let c=t.model?this.isDDD()?`./${t.model}.js`:`../models/${t.model}.js`:void 0,m=t.crud?this.generateCrudService(r,t.model,c):this.generateBasicService(r);Aa(l,m);let p=this.isDDD()?`src/lib/modules/${a}`:"src/lib/services";this.success(`Service created: ${p}/${r}.ts`)}generateCrudService(e,t,s){let r=t||"Model",i=s||`./${r}.js`;return`import { CrudService, type ServiceResult } from '@beeblock/svelar/services';
390
+ `;Da(i,a),this.success(`Seeder created: src/lib/database/seeders/${s}.ts`)}};import{writeFileSync as Ma,mkdirSync as Na,existsSync as Ia}from"fs";import{join as ja}from"path";var it=class extends g{name="make:service";description="Create a new service class";arguments=["name"];flags=[{name:"crud",description:"Create a CRUD service with model",type:"boolean"},{name:"model",alias:"m",description:"Model name for CRUD service",type:"string"},{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a service name.");return}let r=s.endsWith("Service")?s:`${s}Service`,i=r.replace(/Service$/,""),a=t.module||i.toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${a}" as module. Consider: --module ${a}`);let n=this.moduleDir(a,"services");Na(n,{recursive:!0});let l=ja(n,`${r}.ts`);if(Ia(l)){this.warn(`Service ${r} already exists.`);return}let c=t.model?this.isDDD()?`./${t.model}.js`:`../models/${t.model}.js`:void 0,m=t.crud?this.generateCrudService(r,t.model,c):this.generateBasicService(r);Ma(l,m);let p=this.isDDD()?`src/lib/modules/${a}`:"src/lib/services";this.success(`Service created: ${p}/${r}.ts`)}generateCrudService(e,t,s){let r=t||"Model",i=s||`./${r}.js`;return`import { CrudService, type ServiceResult } from '@beeblock/svelar/services';
391
391
  import { ${r} } from '${i}';
392
392
 
393
393
  export class ${e} extends CrudService<${r}> {
@@ -412,7 +412,7 @@ export class ${e} extends Service {
412
412
  }
413
413
  }
414
414
  }
415
- `}};import{writeFileSync as Ma,mkdirSync as Na,existsSync as Ia}from"fs";import{join as ja}from"path";var at=class extends g{name="make:repository";description="Create a new repository class";arguments=["name"];flags=[{name:"model",alias:"m",description:"Model name for the repository",type:"string"},{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a repository name.");return}let r=s.endsWith("Repository")?s:`${s}Repository`,i=r.replace(/Repository$/,""),a=t.module||i.toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${a}" as module. Consider: --module ${a}`);let n=this.moduleDir(a,"repositories");Na(n,{recursive:!0});let l=ja(n,`${r}.ts`);if(Ia(l)){this.warn(`Repository ${r} already exists.`);return}let c=t.model||this.inferModelName(r),m=this.isDDD()?`./${c}.js`:`../models/${c}.js`,p=`import { Repository } from '@beeblock/svelar/repositories';
415
+ `}};import{writeFileSync as Oa,mkdirSync as qa,existsSync as Ua}from"fs";import{join as Fa}from"path";var at=class extends g{name="make:repository";description="Create a new repository class";arguments=["name"];flags=[{name:"model",alias:"m",description:"Model name for the repository",type:"string"},{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a repository name.");return}let r=s.endsWith("Repository")?s:`${s}Repository`,i=r.replace(/Repository$/,""),a=t.module||i.toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${a}" as module. Consider: --module ${a}`);let n=this.moduleDir(a,"repositories");qa(n,{recursive:!0});let l=Fa(n,`${r}.ts`);if(Ua(l)){this.warn(`Repository ${r} already exists.`);return}let c=t.model||this.inferModelName(r),m=this.isDDD()?`./${c}.js`:`../models/${c}.js`,p=`import { Repository } from '@beeblock/svelar/repositories';
416
416
  import { ${c} } from '${m}';
417
417
 
418
418
  export class ${r} extends Repository<${c}> {
@@ -429,7 +429,7 @@ export class ${r} extends Repository<${c}> {
429
429
  // return ${c}.where('active', true).orderBy('name').get();
430
430
  // }
431
431
  }
432
- `;Ma(l,p);let h=this.isDDD()?`src/lib/modules/${a}`:"src/lib/repositories";this.success(`Repository created: ${h}/${r}.ts`)}inferModelName(e){return e.replace("Repository","")||"Model"}};import{writeFileSync as Oa,mkdirSync as qa,existsSync as Ua}from"fs";import{join as Fa}from"path";var nt=class extends g{name="make:action";description="Create a new action class";arguments=["name"];flags=[{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide an action name.");return}let r=s.endsWith("Action")?s:`${s}Action`,i=r.replace(/Action$/,""),a=t.module||i.toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${a}" as module. Consider: --module ${a}`);let n=this.moduleDir(a,"actions");qa(n,{recursive:!0});let l=Fa(n,`${r}.ts`);if(Ua(l)){this.warn(`Action ${r} already exists.`);return}let c=`import { Action } from '@beeblock/svelar/actions';
432
+ `;Oa(l,p);let h=this.isDDD()?`src/lib/modules/${a}`:"src/lib/repositories";this.success(`Repository created: ${h}/${r}.ts`)}inferModelName(e){return e.replace("Repository","")||"Model"}};import{writeFileSync as Ba,mkdirSync as Ha,existsSync as za}from"fs";import{join as Ka}from"path";var nt=class extends g{name="make:action";description="Create a new action class";arguments=["name"];flags=[{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide an action name.");return}let r=s.endsWith("Action")?s:`${s}Action`,i=r.replace(/Action$/,""),a=t.module||i.toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${a}" as module. Consider: --module ${a}`);let n=this.moduleDir(a,"actions");Ha(n,{recursive:!0});let l=Ka(n,`${r}.ts`);if(za(l)){this.warn(`Action ${r} already exists.`);return}let c=`import { Action } from '@beeblock/svelar/actions';
433
433
 
434
434
  interface ${r}Input {
435
435
  // Define input type
@@ -445,7 +445,7 @@ export class ${r} extends Action<${r}Input, ${r}Output> {
445
445
  throw new Error('Not implemented');
446
446
  }
447
447
  }
448
- `;Oa(l,c);let m=this.isDDD()?`src/lib/modules/${a}`:"src/lib/actions";this.success(`Action created: ${m}/${r}.ts`)}};import{writeFileSync as Ba,mkdirSync as Ha,existsSync as za}from"fs";import{join as Ka}from"path";var ot=class extends g{name="make:request";description="Create a new FormRequest validation class";arguments=["name"];flags=[{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a request name.");return}let r=s.endsWith("Request")?s:`${s}Request`,i=r.replace(/Request$/,""),a=t.module||i.toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${a}" as module. Consider: --module ${a}`);let n=this.moduleDir(a,"dtos");Ha(n,{recursive:!0});let l=Ka(n,`${r}.ts`);if(za(l)){this.warn(`Request ${r} already exists.`);return}let c=`import { FormRequest } from '@beeblock/svelar/routing';
448
+ `;Ba(l,c);let m=this.isDDD()?`src/lib/modules/${a}`:"src/lib/actions";this.success(`Action created: ${m}/${r}.ts`)}};import{writeFileSync as Wa,mkdirSync as Ja,existsSync as Va}from"fs";import{join as Qa}from"path";var ot=class extends g{name="make:request";description="Create a new FormRequest validation class";arguments=["name"];flags=[{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a request name.");return}let r=s.endsWith("Request")?s:`${s}Request`,i=r.replace(/Request$/,""),a=t.module||i.toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${a}" as module. Consider: --module ${a}`);let n=this.moduleDir(a,"dtos");Ja(n,{recursive:!0});let l=Qa(n,`${r}.ts`);if(Va(l)){this.warn(`Request ${r} already exists.`);return}let c=`import { FormRequest } from '@beeblock/svelar/routing';
449
449
  import { z } from '@beeblock/svelar/validation';
450
450
 
451
451
  export class ${r} extends FormRequest {
@@ -474,7 +474,7 @@ export class ${r} extends FormRequest {
474
474
  return data;
475
475
  }
476
476
  }
477
- `;Ba(l,c);let m=this.isDDD()?`src/lib/modules/${a}`:"src/lib/dtos";this.success(`Request created: ${m}/${r}.ts`)}};import{writeFileSync as Wa,mkdirSync as Ja,existsSync as Va}from"fs";import{join as Qa}from"path";var lt=class extends g{name="make:plugin";description="Create a new plugin class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a plugin name.");return}let s=t.endsWith("Plugin")?t:`${t}Plugin`,r=this.sharedDir("plugins");Ja(r,{recursive:!0});let i=Qa(r,`${s}.ts`);if(Va(i)){this.warn(`Plugin ${s} already exists.`);return}let a=s.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),n=`import { Plugin } from '@beeblock/svelar/plugins';
477
+ `;Wa(l,c);let m=this.isDDD()?`src/lib/modules/${a}`:"src/lib/dtos";this.success(`Request created: ${m}/${r}.ts`)}};import{writeFileSync as Ga,mkdirSync as Ya,existsSync as Za}from"fs";import{join as Xa}from"path";var lt=class extends g{name="make:plugin";description="Create a new plugin class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a plugin name.");return}let s=t.endsWith("Plugin")?t:`${t}Plugin`,r=this.sharedDir("plugins");Ya(r,{recursive:!0});let i=Xa(r,`${s}.ts`);if(Za(i)){this.warn(`Plugin ${s} already exists.`);return}let a=s.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),n=`import { Plugin } from '@beeblock/svelar/plugins';
478
478
  import type { Container } from '@beeblock/svelar/container';
479
479
 
480
480
  export class ${s} extends Plugin {
@@ -496,7 +496,7 @@ export class ${s} extends Plugin {
496
496
  // Clean up resources
497
497
  }
498
498
  }
499
- `;Wa(i,n);let l=this.isDDD()?`src/lib/shared/plugins/${s}.ts`:`src/lib/plugins/${s}.ts`;this.success(`Plugin created: ${l}`)}};import{writeFileSync as Ga,mkdirSync as Ya,existsSync as Za}from"fs";import{join as Xa}from"path";var ct=class extends g{name="make:task";description="Create a new scheduled task class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a task name.");return}let s=(t.endsWith("Task"),t),r=this.sharedDir("scheduler");Ya(r,{recursive:!0});let i=Xa(r,`${s}.ts`);if(Za(i)){this.warn(`Task ${s} already exists.`);return}let a=`import { ScheduledTask } from '@beeblock/svelar/scheduler';
499
+ `;Ga(i,n);let l=this.isDDD()?`src/lib/shared/plugins/${s}.ts`:`src/lib/plugins/${s}.ts`;this.success(`Plugin created: ${l}`)}};import{writeFileSync as en,mkdirSync as tn,existsSync as sn}from"fs";import{join as rn}from"path";var ct=class extends g{name="make:task";description="Create a new scheduled task class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a task name.");return}let s=(t.endsWith("Task"),t),r=this.sharedDir("scheduler");tn(r,{recursive:!0});let i=rn(r,`${s}.ts`);if(sn(i)){this.warn(`Task ${s} already exists.`);return}let a=`import { ScheduledTask } from '@beeblock/svelar/scheduler';
500
500
 
501
501
  export class ${s} extends ScheduledTask {
502
502
  name = '${this.toKebabCase(s)}';
@@ -529,7 +529,7 @@ export class ${s} extends ScheduledTask {
529
529
  console.error('${s} failed:', error.message);
530
530
  }
531
531
  }
532
- `;Ga(i,a);let n=this.isDDD()?`src/lib/shared/scheduler/${s}.ts`:`src/lib/scheduler/${s}.ts`;this.success(`Scheduled task created: ${n}`)}toKebabCase(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,"")}};import{writeFileSync as en,mkdirSync as tn,existsSync as sn}from"fs";import{join as rn}from"path";var dt=class extends g{name="make:job";description="Create a new queue job class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a job name.");return}let s=(t.endsWith("Job"),t),r=this.sharedDir("jobs");tn(r,{recursive:!0});let i=rn(r,`${s}.ts`);if(sn(i)){this.warn(`Job ${s} already exists.`);return}let a=`import { Job } from '@beeblock/svelar/queue';
532
+ `;en(i,a);let n=this.isDDD()?`src/lib/shared/scheduler/${s}.ts`:`src/lib/scheduler/${s}.ts`;this.success(`Scheduled task created: ${n}`)}toKebabCase(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,"")}};import{writeFileSync as an,mkdirSync as nn,existsSync as on}from"fs";import{join as ln}from"path";var dt=class extends g{name="make:job";description="Create a new queue job class";arguments=["name"];flags=[];async handle(e){let t=e[0];if(!t){this.error("Please provide a job name.");return}let s=(t.endsWith("Job"),t),r=this.sharedDir("jobs");nn(r,{recursive:!0});let i=ln(r,`${s}.ts`);if(on(i)){this.warn(`Job ${s} already exists.`);return}let a=`import { Job } from '@beeblock/svelar/queue';
533
533
 
534
534
  export class ${s} extends Job {
535
535
  maxAttempts = 3; // Retry up to 3 times
@@ -556,7 +556,7 @@ export class ${s} extends Job {
556
556
  console.log('${s} retrying, attempt', attempt);
557
557
  }
558
558
  }
559
- `;en(i,a);let n=this.isDDD()?`src/lib/shared/jobs/${s}.ts`:`src/lib/jobs/${s}.ts`;this.success(`Job created: ${n}`)}};import{writeFileSync as an,mkdirSync as nn,existsSync as on}from"fs";import{join as ln}from"path";var ut=class extends g{name="make:command";description="Create a new custom CLI command";arguments=["name"];flags=[{name:"command",description:'The terminal command name (e.g. "app:sync")',type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a command class name. Example: npx svelar make:command SyncUsers");return}let r=s.endsWith("Command")?s:`${s}Command`,i=this.sharedDir("commands");nn(i,{recursive:!0});let a=ln(i,`${r}.ts`);if(on(a)){this.warn(`Command ${r} already exists.`);return}let n=t.command??this.deriveCommandName(r),l=`import { Command } from '@beeblock/svelar/cli';
559
+ `;an(i,a);let n=this.isDDD()?`src/lib/shared/jobs/${s}.ts`:`src/lib/jobs/${s}.ts`;this.success(`Job created: ${n}`)}};import{writeFileSync as cn,mkdirSync as dn,existsSync as un}from"fs";import{join as mn}from"path";var ut=class extends g{name="make:command";description="Create a new custom CLI command";arguments=["name"];flags=[{name:"command",description:'The terminal command name (e.g. "app:sync")',type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a command class name. Example: npx svelar make:command SyncUsers");return}let r=s.endsWith("Command")?s:`${s}Command`,i=this.sharedDir("commands");dn(i,{recursive:!0});let a=mn(i,`${r}.ts`);if(un(a)){this.warn(`Command ${r} already exists.`);return}let n=t.command??this.deriveCommandName(r),l=`import { Command } from '@beeblock/svelar/cli';
560
560
 
561
561
  export class ${r} extends Command {
562
562
  name = '${n}';
@@ -579,7 +579,7 @@ export class ${r} extends Command {
579
579
  this.success('Done!');
580
580
  }
581
581
  }
582
- `;an(a,l);let c=this.isDDD()?`src/lib/shared/commands/${r}.ts`:`src/lib/commands/${r}.ts`;this.success(`Command created: ${c}`),this.info(`Command name: ${n}`),this.newLine(),this.info("Your command will be auto-discovered. Run it with:"),this.log(` npx svelar ${n}`)}deriveCommandName(e){return`app:${e.replace(/Command$/,"").replace(/([a-z])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").toLowerCase()}`}};import{writeFileSync as cn,mkdirSync as dn,existsSync as un}from"fs";import{join as Br}from"path";var mt=class extends g{name="make:config";description="Create a new config file";arguments=["name"];flags=[];templates={app:`import { env } from 'svelar/config';
582
+ `;cn(a,l);let c=this.isDDD()?`src/lib/shared/commands/${r}.ts`:`src/lib/commands/${r}.ts`;this.success(`Command created: ${c}`),this.info(`Command name: ${n}`),this.newLine(),this.info("Your command will be auto-discovered. Run it with:"),this.log(` npx svelar ${n}`)}deriveCommandName(e){return`app:${e.replace(/Command$/,"").replace(/([a-z])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").toLowerCase()}`}};import{writeFileSync as pn,mkdirSync as hn,existsSync as gn}from"fs";import{join as zr}from"path";var mt=class extends g{name="make:config";description="Create a new config file";arguments=["name"];flags=[];templates={app:`import { env } from 'svelar/config';
583
583
 
584
584
  export default {
585
585
  name: env('APP_NAME', 'Svelar'),
@@ -788,7 +788,7 @@ export default {
788
788
  },
789
789
  },
790
790
  };
791
- `};async handle(e){let t=e[0];if(!t){this.error("Please provide a config file name. Example: npx svelar make:config database"),this.newLine(),this.info("Available presets: app, database, auth, mail, cache, queue, storage, broadcasting, logging");return}let s=Br(process.cwd(),"config");dn(s,{recursive:!0});let r=t.toLowerCase().replace(/\s+/g,"-"),i=Br(s,`${r}.ts`);if(un(i)){this.warn(`Config file config/${r}.ts already exists.`);return}let a=this.templates[r]??this.blankTemplate(r);cn(i,a),this.success(`Config created: config/${r}.ts`),this.newLine(),this.info("Access it with:"),this.log(` config.get('${r}.key')`)}blankTemplate(e){return`import { env } from 'svelar/config';
791
+ `};async handle(e){let t=e[0];if(!t){this.error("Please provide a config file name. Example: npx svelar make:config database"),this.newLine(),this.info("Available presets: app, database, auth, mail, cache, queue, storage, broadcasting, logging");return}let s=zr(process.cwd(),"config");hn(s,{recursive:!0});let r=t.toLowerCase().replace(/\s+/g,"-"),i=zr(s,`${r}.ts`);if(gn(i)){this.warn(`Config file config/${r}.ts already exists.`);return}let a=this.templates[r]??this.blankTemplate(r);pn(i,a),this.success(`Config created: config/${r}.ts`),this.newLine(),this.info("Access it with:"),this.log(` config.get('${r}.key')`)}blankTemplate(e){return`import { env } from 'svelar/config';
792
792
 
793
793
  export default {
794
794
  // Add your ${e} configuration here
@@ -797,7 +797,7 @@ export default {
797
797
  // env<number>('MY_PORT', 3000)
798
798
  // env<boolean>('MY_FLAG', false)
799
799
  };
800
- `}};import{writeFileSync as mn,mkdirSync as pn,existsSync as hn}from"fs";import{join as gn}from"path";var pt=class extends g{name="make:channel";description="Create a new broadcast channel authorization";arguments=["name"];flags=[{name:"presence",alias:"p",description:"Create a presence channel",type:"boolean"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a channel name. Example: npx svelar make:channel OrderChannel");return}let r=s.endsWith("Channel")?s:`${s}Channel`,i=this.sharedDir("channels");pn(i,{recursive:!0});let a=gn(i,`${r}.ts`);if(hn(a)){this.warn(`Channel ${r} already exists.`);return}let n=r.replace(/Channel$/,""),l=n.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),c=n.charAt(0).toLowerCase()+n.slice(1)+"Id",m=t.presence,h=`${m?"presence":"private"}-${l}.{${c}}`,u=m?this.presenceTemplate(r,h,c):this.privateTemplate(r,h,c);mn(a,u);let b=this.isDDD()?"src/lib/shared/channels":"src/lib/channels";this.success(`Channel created: ${b}/${r}.ts`),this.info(`Channel pattern: ${h}`),this.newLine(),this.info("Register it in src/app.ts or a service provider:"),this.log(` import { register${r} } from './${b.replace("src/","")}/${r}.js';`),this.log(` register${r}();`)}privateTemplate(e,t,s){let r=e.replace(/Channel$/,"");return`import { Broadcast } from '@beeblock/svelar/broadcasting';
800
+ `}};import{writeFileSync as fn,mkdirSync as bn,existsSync as yn}from"fs";import{join as vn}from"path";var pt=class extends g{name="make:channel";description="Create a new broadcast channel authorization";arguments=["name"];flags=[{name:"presence",alias:"p",description:"Create a presence channel",type:"boolean"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a channel name. Example: npx svelar make:channel OrderChannel");return}let r=s.endsWith("Channel")?s:`${s}Channel`,i=this.sharedDir("channels");bn(i,{recursive:!0});let a=vn(i,`${r}.ts`);if(yn(a)){this.warn(`Channel ${r} already exists.`);return}let n=r.replace(/Channel$/,""),l=n.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),c=n.charAt(0).toLowerCase()+n.slice(1)+"Id",m=t.presence,h=`${m?"presence":"private"}-${l}.{${c}}`,u=m?this.presenceTemplate(r,h,c):this.privateTemplate(r,h,c);fn(a,u);let b=this.isDDD()?"src/lib/shared/channels":"src/lib/channels";this.success(`Channel created: ${b}/${r}.ts`),this.info(`Channel pattern: ${h}`),this.newLine(),this.info("Register it in src/app.ts or a service provider:"),this.log(` import { register${r} } from './${b.replace("src/","")}/${r}.js';`),this.log(` register${r}();`)}privateTemplate(e,t,s){let r=e.replace(/Channel$/,"");return`import { Broadcast } from '@beeblock/svelar/broadcasting';
801
801
 
802
802
  /**
803
803
  * ${e}
@@ -840,7 +840,7 @@ export function register${e}(): void {
840
840
  };
841
841
  });
842
842
  }
843
- `}};import{writeFileSync as fn,mkdirSync as bn,existsSync as yn}from"fs";import{join as Re}from"path";var ht=class extends g{name="make:docker";description="Scaffold Docker deployment files (Dockerfile, docker-compose.yml, PM2 config)";arguments=[];flags=[{name:"db",alias:"d",description:"Database driver: postgres, mysql, sqlite (default: postgres)",type:"string"},{name:"soketi",alias:"s",description:"Include Soketi WebSocket server",type:"boolean"},{name:"redis",alias:"r",description:"Include Redis service",type:"boolean"},{name:"gotenberg",alias:"g",description:"Include Gotenberg PDF service (default: true)",type:"boolean"},{name:"rustfs",description:"Include RustFS S3-compatible object storage (default: true)",type:"boolean"},{name:"meilisearch",alias:"m",description:"Include Meilisearch full-text search engine",type:"boolean"},{name:"force",alias:"f",description:"Overwrite existing files",type:"boolean"}];async handle(e,t){let s=process.cwd(),r=t.db??"postgres",i=t.soketi??!0,a=t.redis??!0,n=t.gotenberg??!0,l=t.rustfs??!0,c=t.meilisearch??!1,m=t.force??!1,p=["postgres","mysql","sqlite"];if(!p.includes(r)){this.error(`Unknown database driver: ${r}. Use one of: ${p.join(", ")}`);return}let h=[{path:Re(s,"Dockerfile"),content:this.dockerfileTemplate(),label:"Dockerfile"},{path:Re(s,"docker-compose.yml"),content:this.composeTemplate(r,i,a,n,l,c),label:"docker-compose.yml"},{path:Re(s,".dockerignore"),content:this.dockerignoreTemplate(),label:".dockerignore"},{path:Re(s,"ecosystem.config.cjs"),content:this.pm2Template(),label:"ecosystem.config.cjs"}],u=0,b=0;for(let y of h){if(yn(y.path)&&!m){this.warn(`${y.label} already exists (use --force to overwrite)`),b++;continue}fn(y.path,y.content),this.success(`Created ${y.label}`),u++}if(r!=="sqlite"){let y=Re(s,"docker");bn(y,{recursive:!0})}this.newLine(),u>0?this.info(`${u} file(s) created${b>0?`, ${b} skipped`:""}`):this.info("No files created (all exist already)"),this.newLine(),this.info("Quick start:"),this.log(" # Build and start all services"),this.log(" docker compose up -d --build"),this.newLine(),this.log(" # Run migrations inside the container"),this.log(" docker compose exec app npx svelar migrate"),this.newLine(),this.log(" # View logs"),this.log(" docker compose logs -f app"),this.newLine(),this.log(" # Stop services"),this.log(" docker compose down"),this.newLine(),this.info("Make sure to update .env with production values before deploying.")}dockerfileTemplate(){return`# \u2500\u2500 Svelar Production Dockerfile \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
843
+ `}};import{writeFileSync as wn,mkdirSync as Cn,existsSync as xn}from"fs";import{join as Re}from"path";var ht=class extends g{name="make:docker";description="Scaffold Docker deployment files (Dockerfile, docker-compose.yml, PM2 config)";arguments=[];flags=[{name:"db",alias:"d",description:"Database driver: postgres, mysql, sqlite (default: postgres)",type:"string"},{name:"soketi",alias:"s",description:"Include Soketi WebSocket server",type:"boolean"},{name:"redis",alias:"r",description:"Include Redis service",type:"boolean"},{name:"gotenberg",alias:"g",description:"Include Gotenberg PDF service (default: true)",type:"boolean"},{name:"rustfs",description:"Include RustFS S3-compatible object storage (default: true)",type:"boolean"},{name:"meilisearch",alias:"m",description:"Include Meilisearch full-text search engine",type:"boolean"},{name:"force",alias:"f",description:"Overwrite existing files",type:"boolean"}];async handle(e,t){let s=process.cwd(),r=t.db??"postgres",i=t.soketi??!0,a=t.redis??!0,n=t.gotenberg??!0,l=t.rustfs??!0,c=t.meilisearch??!1,m=t.force??!1,p=["postgres","mysql","sqlite"];if(!p.includes(r)){this.error(`Unknown database driver: ${r}. Use one of: ${p.join(", ")}`);return}let h=[{path:Re(s,"Dockerfile"),content:this.dockerfileTemplate(),label:"Dockerfile"},{path:Re(s,"docker-compose.yml"),content:this.composeTemplate(r,i,a,n,l,c),label:"docker-compose.yml"},{path:Re(s,".dockerignore"),content:this.dockerignoreTemplate(),label:".dockerignore"},{path:Re(s,"ecosystem.config.cjs"),content:this.pm2Template(),label:"ecosystem.config.cjs"}],u=0,b=0;for(let y of h){if(xn(y.path)&&!m){this.warn(`${y.label} already exists (use --force to overwrite)`),b++;continue}wn(y.path,y.content),this.success(`Created ${y.label}`),u++}if(r!=="sqlite"){let y=Re(s,"docker");Cn(y,{recursive:!0})}this.newLine(),u>0?this.info(`${u} file(s) created${b>0?`, ${b} skipped`:""}`):this.info("No files created (all exist already)"),this.newLine(),this.info("Quick start:"),this.log(" # Build and start all services"),this.log(" docker compose up -d --build"),this.newLine(),this.log(" # Run migrations inside the container"),this.log(" docker compose exec app npx svelar migrate"),this.newLine(),this.log(" # View logs"),this.log(" docker compose logs -f app"),this.newLine(),this.log(" # Stop services"),this.log(" docker compose down"),this.newLine(),this.info("Make sure to update .env with production values before deploying.")}dockerfileTemplate(){return`# \u2500\u2500 Svelar Production Dockerfile \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
844
844
  # Multi-stage build for a lean production image.
845
845
 
846
846
  # Stage 1: Install dependencies & build
@@ -1016,7 +1016,7 @@ module.exports = {
1016
1016
  },
1017
1017
  ],
1018
1018
  };
1019
- `}};import{writeFileSync as vn,mkdirSync as wn,existsSync as Hr}from"fs";import{join as U}from"path";var gt=class extends g{name="make:broadcasting";description="Scaffold broadcasting routes (Pusher auth, SSE stream, client init)";arguments=[];flags=[{name:"sse",description:"Only scaffold SSE routes (no Pusher auth)",type:"boolean"},{name:"pusher",description:"Only scaffold Pusher/Soketi routes",type:"boolean"},{name:"force",alias:"f",description:"Overwrite existing files",type:"boolean"}];async handle(e,t){let s=process.cwd(),r=t.force??!1,i=t.sse??!1,a=t.pusher??!1,n=!i&&!a,l=[];(n||a)&&l.push({path:U(s,"src/routes/api/broadcasting/auth/+server.ts"),content:this.pusherAuthRoute(),label:"src/routes/api/broadcasting/auth/+server.ts",dirs:[U(s,"src/routes/api/broadcasting/auth")]}),(n||i)&&l.push({path:U(s,"src/routes/api/broadcasting/[channel]/+server.ts"),content:this.sseRoute(),label:"src/routes/api/broadcasting/[channel]/+server.ts",dirs:[U(s,"src/routes/api/broadcasting/[channel]")]}),l.push({path:U(s,"src/lib/broadcasting.ts"),content:n||a?this.clientPusher():this.clientSSE(),label:"src/lib/broadcasting.ts",dirs:[U(s,"src/lib")]});let c=U(s,"config/broadcasting.ts");Hr(c)||l.push({path:c,content:this.configTemplate(),label:"config/broadcasting.ts",dirs:[U(s,"config")]});let m=0,p=0;for(let h of l){if(Hr(h.path)&&!r){this.warn(`${h.label} already exists (use --force to overwrite)`),p++;continue}for(let u of h.dirs)wn(u,{recursive:!0});vn(h.path,h.content),this.success(`Created ${h.label}`),m++}this.newLine(),m>0?this.info(`${m} file(s) created${p>0?`, ${p} skipped`:""}`):this.info("No files created (all exist already)"),this.newLine(),this.info("Next steps:"),n||a?(this.log(" 1. Install pusher-js: npm install pusher-js"),this.log(" 2. Add Pusher env vars to .env:"),this.log(" BROADCAST_DRIVER=pusher"),this.log(" PUSHER_KEY=svelar-key"),this.log(" PUSHER_SECRET=svelar-secret"),this.log(" PUSHER_APP_ID=svelar-app"),this.log(' PUSHER_HOST=localhost # or "soketi" in Docker'),this.log(" PUSHER_PORT=6001"),this.log(" 3. Import broadcasting in your root layout:"),this.log(" import '$lib/broadcasting';")):(this.log(" 1. Import broadcasting in your root layout:"),this.log(" import '$lib/broadcasting';")),this.log(" 4. Register channel authorizations in src/app.ts"),this.log(" 5. Run 'npx svelar make:docker' for Soketi in Docker Compose")}pusherAuthRoute(){return`/**
1019
+ `}};import{writeFileSync as Pn,mkdirSync as Sn,existsSync as Kr}from"fs";import{join as U}from"path";var gt=class extends g{name="make:broadcasting";description="Scaffold broadcasting routes (Pusher auth, SSE stream, client init)";arguments=[];flags=[{name:"sse",description:"Only scaffold SSE routes (no Pusher auth)",type:"boolean"},{name:"pusher",description:"Only scaffold Pusher/Soketi routes",type:"boolean"},{name:"force",alias:"f",description:"Overwrite existing files",type:"boolean"}];async handle(e,t){let s=process.cwd(),r=t.force??!1,i=t.sse??!1,a=t.pusher??!1,n=!i&&!a,l=[];(n||a)&&l.push({path:U(s,"src/routes/api/broadcasting/auth/+server.ts"),content:this.pusherAuthRoute(),label:"src/routes/api/broadcasting/auth/+server.ts",dirs:[U(s,"src/routes/api/broadcasting/auth")]}),(n||i)&&l.push({path:U(s,"src/routes/api/broadcasting/[channel]/+server.ts"),content:this.sseRoute(),label:"src/routes/api/broadcasting/[channel]/+server.ts",dirs:[U(s,"src/routes/api/broadcasting/[channel]")]}),l.push({path:U(s,"src/lib/broadcasting.ts"),content:n||a?this.clientPusher():this.clientSSE(),label:"src/lib/broadcasting.ts",dirs:[U(s,"src/lib")]});let c=U(s,"config/broadcasting.ts");Kr(c)||l.push({path:c,content:this.configTemplate(),label:"config/broadcasting.ts",dirs:[U(s,"config")]});let m=0,p=0;for(let h of l){if(Kr(h.path)&&!r){this.warn(`${h.label} already exists (use --force to overwrite)`),p++;continue}for(let u of h.dirs)Sn(u,{recursive:!0});Pn(h.path,h.content),this.success(`Created ${h.label}`),m++}this.newLine(),m>0?this.info(`${m} file(s) created${p>0?`, ${p} skipped`:""}`):this.info("No files created (all exist already)"),this.newLine(),this.info("Next steps:"),n||a?(this.log(" 1. Install pusher-js: npm install pusher-js"),this.log(" 2. Add Pusher env vars to .env:"),this.log(" BROADCAST_DRIVER=pusher"),this.log(" PUSHER_KEY=svelar-key"),this.log(" PUSHER_SECRET=svelar-secret"),this.log(" PUSHER_APP_ID=svelar-app"),this.log(' PUSHER_HOST=localhost # or "soketi" in Docker'),this.log(" PUSHER_PORT=6001"),this.log(" 3. Import broadcasting in your root layout:"),this.log(" import '$lib/broadcasting';")):(this.log(" 1. Import broadcasting in your root layout:"),this.log(" import '$lib/broadcasting';")),this.log(" 4. Register channel authorizations in src/app.ts"),this.log(" 5. Run 'npx svelar make:docker' for Soketi in Docker Compose")}pusherAuthRoute(){return`/**
1020
1020
  * Pusher/Soketi Channel Authorization Endpoint
1021
1021
  *
1022
1022
  * This route authenticates channel subscriptions from pusher-js.
@@ -1170,7 +1170,50 @@ export default {
1170
1170
  },
1171
1171
  },
1172
1172
  };
1173
- `}};import{writeFileSync as zr,mkdirSync as Cn,existsSync as Kr}from"fs";import{join as Wr}from"path";var ft=class extends g{name="make:resource";description="Create a new API resource (response transformer)";arguments=["name"];flags=[{name:"module",description:"Module name (e.g. auth, billing)",type:"string"},{name:"model",alias:"m",description:"Model name to transform",type:"string"},{name:"collection",alias:"c",description:"Also generate a collection resource",type:"boolean"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a resource name.");return}let r=s.endsWith("Resource")?s:`${s}Resource`,i=t.module||this.deriveModuleName(r);!t.module&&this.isDDD()&&this.warn(`No --module specified, using "${i}". Use --module=<name> to target a specific module.`);let a=this.moduleDir(i,"resources");Cn(a,{recursive:!0});let n=Wr(a,`${r}.ts`);if(Kr(n)){this.warn(`Resource ${r} already exists.`);return}let l=t.model||this.inferModelName(r),c=this.isDDD()?`./${l}.js`:`../models/${l}.js`,m=this.generateResource(r,l,c);zr(n,m);let p=this.isDDD()?`src/lib/modules/${i}`:"src/lib/resources";if(this.success(`Resource created: ${p}/${r}.ts`),t.collection){let h=r.replace("Resource","CollectionResource"),u=Wr(a,`${h}.ts`);if(!Kr(u)){let b=this.isDDD()?`./${l}.js`:`../models/${l}.js`,y=this.generateCollectionResource(h,r,l,b);zr(u,y);let v=this.isDDD()?`src/lib/modules/${i}`:"src/lib/resources";this.success(`Collection resource created: ${v}/${h}.ts`)}}}generateResource(e,t,s=`./${t}.js`){let r=`${t}Data`;return`import { Resource } from '@beeblock/svelar/routing';
1173
+ `}};import{writeFileSync as Rn,mkdirSync as Tn,existsSync as kn}from"fs";import{join as Wr}from"path";var ft=class extends g{name="make:test";description="Create a new test file";arguments=["name"];flags=[{name:"unit",alias:"u",description:"Create a unit test (default)",type:"boolean",default:!1},{name:"feature",alias:"f",description:"Create a feature test",type:"boolean",default:!1},{name:"e2e",alias:"e",description:"Create an e2e (Playwright) test",type:"boolean",default:!1}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a test name.");return}let r="unit";t.feature&&(r="feature"),t.e2e&&(r="e2e");let i=r==="e2e"?".spec.ts":".test.ts",a=Wr(process.cwd(),"tests",r);Tn(a,{recursive:!0});let n=s.endsWith(i)?s:`${s}${i}`,l=Wr(a,n);if(kn(l)){this.warn(`Test file already exists: tests/${r}/${n}`);return}let c;switch(r){case"unit":c=En(s);break;case"feature":c=$n(s);break;case"e2e":c=An(s);break}Rn(l,c),this.success(`Test created: tests/${r}/${n}`)}};function En(o){return`import { describe, it, expect } from 'vitest';
1174
+
1175
+ describe('${o}', () => {
1176
+ it('should work', () => {
1177
+ expect(true).toBe(true);
1178
+ });
1179
+ });
1180
+ `}function $n(o){return`import { describe, it, expect } from 'vitest';
1181
+ import { useSvelarTest, assertDatabaseHas } from '@beeblock/svelar/testing';
1182
+
1183
+ describe('${o}', () => {
1184
+ useSvelarTest({ refreshDatabase: true });
1185
+
1186
+ it('should work', async () => {
1187
+ expect(true).toBe(true);
1188
+ });
1189
+ });
1190
+ `}function An(o){return`import { test, expect } from '@playwright/test';
1191
+
1192
+ test.describe('${o}', () => {
1193
+ test('should load the page', async ({ page }) => {
1194
+ await page.goto('/');
1195
+ await expect(page).toHaveTitle(/.*/);
1196
+ });
1197
+ });
1198
+ `}import{writeFileSync as Dn,mkdirSync as Ln,existsSync as _n}from"fs";import{join as Jr}from"path";var bt=class extends g{name="make:factory";description="Create a new model factory for testing";arguments=["name"];flags=[{name:"model",alias:"m",description:"The model class name",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a factory name.");return}let r=s.endsWith("Factory")?s:`${s}Factory`,i=t.model||s.replace(/Factory$/,""),a=Jr(process.cwd(),"src","lib","factories");Ln(a,{recursive:!0});let n=Jr(a,`${r}.ts`);if(_n(n)){this.warn(`Factory ${r} already exists.`);return}let l=this.resolveModelImport(i),c=`import { Factory } from '@beeblock/svelar/testing';
1199
+ import { ${i} } from '${l}';
1200
+
1201
+ export class ${r} extends Factory<${i}> {
1202
+ model() {
1203
+ return ${i};
1204
+ }
1205
+
1206
+ definition() {
1207
+ return {
1208
+ name: \`${i} \${this.sequence}\`,
1209
+ email: \`${i.toLowerCase()}\${this.sequence}@test.com\`,
1210
+ };
1211
+ }
1212
+ }
1213
+
1214
+ // Singleton instance for convenience
1215
+ export default new ${r}();
1216
+ `;Dn(n,c),this.success(`Factory created: src/lib/factories/${r}.ts`)}resolveModelImport(e){if(this.isDDD()){let t=e.toLowerCase();return`$lib/modules/${{User:"auth",Post:"posts"}[e]||t}/${e}`}return`$lib/models/${e}`}};import{writeFileSync as Vr,mkdirSync as Mn,existsSync as Qr}from"fs";import{join as Gr}from"path";var yt=class extends g{name="make:resource";description="Create a new API resource (response transformer)";arguments=["name"];flags=[{name:"module",description:"Module name (e.g. auth, billing)",type:"string"},{name:"model",alias:"m",description:"Model name to transform",type:"string"},{name:"collection",alias:"c",description:"Also generate a collection resource",type:"boolean"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a resource name.");return}let r=s.endsWith("Resource")?s:`${s}Resource`,i=t.module||this.deriveModuleName(r);!t.module&&this.isDDD()&&this.warn(`No --module specified, using "${i}". Use --module=<name> to target a specific module.`);let a=this.moduleDir(i,"resources");Mn(a,{recursive:!0});let n=Gr(a,`${r}.ts`);if(Qr(n)){this.warn(`Resource ${r} already exists.`);return}let l=t.model||this.inferModelName(r),c=this.isDDD()?`./${l}.js`:`../models/${l}.js`,m=this.generateResource(r,l,c);Vr(n,m);let p=this.isDDD()?`src/lib/modules/${i}`:"src/lib/resources";if(this.success(`Resource created: ${p}/${r}.ts`),t.collection){let h=r.replace("Resource","CollectionResource"),u=Gr(a,`${h}.ts`);if(!Qr(u)){let b=this.isDDD()?`./${l}.js`:`../models/${l}.js`,y=this.generateCollectionResource(h,r,l,b);Vr(u,y);let v=this.isDDD()?`src/lib/modules/${i}`:"src/lib/resources";this.success(`Collection resource created: ${v}/${h}.ts`)}}}generateResource(e,t,s=`./${t}.js`){let r=`${t}Data`;return`import { Resource } from '@beeblock/svelar/routing';
1174
1217
  import type { ${t} } from '${s}';
1175
1218
 
1176
1219
  // \u2500\u2500 API Contract \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
@@ -1248,7 +1291,7 @@ export class ${e} {
1248
1291
  .toObject();
1249
1292
  }
1250
1293
  }
1251
- `}deriveModuleName(e){return e.replace(/Resource$/,"").replace(/Collection$/,"").toLowerCase()}inferModelName(e){return e.replace(/Resource$/,"")||"Model"}};import{writeFileSync as xn,mkdirSync as Sn,existsSync as Pn}from"fs";import{join as Rn}from"path";var bt=class extends g{name="make:schema";description="Create a contract schema (Zod schemas + shared types)";arguments=["name"];flags=[{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a schema name (e.g. User, Post, Invoice).");return}let r=s.charAt(0).toUpperCase()+s.slice(1),i=this.toKebab(s)+".schema",a=t.module||s.toLowerCase(),n=this.moduleDir(a,"schemas");Sn(n,{recursive:!0});let l=Rn(n,`${i}.ts`);if(Pn(l)){let h=this.isDDD()?`src/lib/modules/${a}`:"src/lib/schemas";this.warn(`Schema already exists: ${h}/${i}.ts`);return}let c=this.generateSchema(r);xn(l,c);let m=this.isDDD()?`src/lib/modules/${a}`:"src/lib/schemas";this.success(`Schema created: ${m}/${i}.ts`),this.info(""),this.info(" Use this schema across your entire stack:"),this.info(""),this.info(` Resource: extends Resource<${r}, ${r}Data>`),this.info(` FormRequest: uses create${r}Schema / update${r}Schema`);let p=this.isDDD()?`$lib/modules/${a}/${i}`:`$lib/schemas/${i}`;this.info(` Frontend: import type { ${r}Data } from '${p}'`)}generateSchema(e){let t=e.charAt(0).toLowerCase()+e.slice(1),s=this.toKebab(e);return`import { z } from 'zod';
1294
+ `}deriveModuleName(e){return e.replace(/Resource$/,"").replace(/Collection$/,"").toLowerCase()}inferModelName(e){return e.replace(/Resource$/,"")||"Model"}};import{writeFileSync as Nn,mkdirSync as In,existsSync as jn}from"fs";import{join as On}from"path";var vt=class extends g{name="make:schema";description="Create a contract schema (Zod schemas + shared types)";arguments=["name"];flags=[{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a schema name (e.g. User, Post, Invoice).");return}let r=s.charAt(0).toUpperCase()+s.slice(1),i=this.toKebab(s)+".schema",a=t.module||s.toLowerCase(),n=this.moduleDir(a,"schemas");In(n,{recursive:!0});let l=On(n,`${i}.ts`);if(jn(l)){let h=this.isDDD()?`src/lib/modules/${a}`:"src/lib/schemas";this.warn(`Schema already exists: ${h}/${i}.ts`);return}let c=this.generateSchema(r);Nn(l,c);let m=this.isDDD()?`src/lib/modules/${a}`:"src/lib/schemas";this.success(`Schema created: ${m}/${i}.ts`),this.info(""),this.info(" Use this schema across your entire stack:"),this.info(""),this.info(` Resource: extends Resource<${r}, ${r}Data>`),this.info(` FormRequest: uses create${r}Schema / update${r}Schema`);let p=this.isDDD()?`$lib/modules/${a}/${i}`:`$lib/schemas/${i}`;this.info(` Frontend: import type { ${r}Data } from '${p}'`)}generateSchema(e){let t=e.charAt(0).toLowerCase()+e.slice(1),s=this.toKebab(e);return`import { z } from 'zod';
1252
1295
 
1253
1296
  // \u2500\u2500 ${e} Contract Schema \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1254
1297
  //
@@ -1283,7 +1326,7 @@ export const update${e}Schema = create${e}Schema.partial();
1283
1326
  export type ${e}Data = z.infer<typeof ${t}Schema>;
1284
1327
  export type Create${e}Input = z.infer<typeof create${e}Schema>;
1285
1328
  export type Update${e}Input = z.infer<typeof update${e}Schema>;
1286
- `}toKebab(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").toLowerCase()}};import{writeFileSync as Tn,mkdirSync as kn,existsSync as En}from"fs";import{join as $n}from"path";var yt=class extends g{name="make:observer";description="Create a new model observer class";arguments=["name"];flags=[{name:"model",alias:"m",description:"The model class to observe",type:"string"},{name:"module",description:"Module name (e.g. users, posts)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide an observer name (e.g. UserObserver).");return}let r=t.model||s.replace(/Observer$/,""),i=t.module||this.toSnakeCase(this.pluralize(r)),a=this.moduleDir(i,"observers");kn(a,{recursive:!0});let n=$n(a,`${s}.ts`);if(En(n)){this.warn(`Observer ${s} already exists at ${n}`);return}let l=this.isDDD()?`./${r}.js`:`../models/${r}.js`,c=`import { ModelObserver } from '@beeblock/svelar/orm';
1329
+ `}toKebab(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").toLowerCase()}};import{writeFileSync as qn,mkdirSync as Un,existsSync as Fn}from"fs";import{join as Bn}from"path";var wt=class extends g{name="make:observer";description="Create a new model observer class";arguments=["name"];flags=[{name:"model",alias:"m",description:"The model class to observe",type:"string"},{name:"module",description:"Module name (e.g. users, posts)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide an observer name (e.g. UserObserver).");return}let r=t.model||s.replace(/Observer$/,""),i=t.module||this.toSnakeCase(this.pluralize(r)),a=this.moduleDir(i,"observers");Un(a,{recursive:!0});let n=Bn(a,`${s}.ts`);if(Fn(n)){this.warn(`Observer ${s} already exists at ${n}`);return}let l=this.isDDD()?`./${r}.js`:`../models/${r}.js`,c=`import { ModelObserver } from '@beeblock/svelar/orm';
1287
1330
  import type { ${r} } from '${l}';
1288
1331
 
1289
1332
  export class ${s} extends ModelObserver {
@@ -1321,7 +1364,7 @@ export class ${s} extends ModelObserver {
1321
1364
  // async deleted(${r.toLowerCase()}: ${r}) {
1322
1365
  // }
1323
1366
  }
1324
- `;Tn(n,c);let m=this.isDDD()?`src/lib/modules/${i}`:"src/lib/observers";this.success(`Observer created: ${m}/${s}.ts`),this.info(`Register it in your app: ${r}.observe(new ${s}());`)}toSnakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}pluralize(e){return e.endsWith("y")?e.slice(0,-1)+"ies":e.endsWith("s")||e.endsWith("x")||e.endsWith("z")||e.endsWith("ch")||e.endsWith("sh")?e+"es":e+"s"}};import{writeFileSync as An,mkdirSync as Dn,existsSync as Ln}from"fs";import{join as _n}from"path";var vt=class extends g{name="make:event";description="Create a new event class";arguments=["name"];flags=[{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide an event name (e.g. UserRegistered).");return}let r=t.module||s.replace(/([A-Z])/g," $1").trim().split(" ")[0].toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${r}" as module. Consider: --module ${r}`);let i=this.moduleDir(r,"events");Dn(i,{recursive:!0});let a=_n(i,`${s}.ts`);if(Ln(a)){this.warn(`Event ${s} already exists at ${a}`);return}let n=`/**
1367
+ `;qn(n,c);let m=this.isDDD()?`src/lib/modules/${i}`:"src/lib/observers";this.success(`Observer created: ${m}/${s}.ts`),this.info(`Register it in your app: ${r}.observe(new ${s}());`)}toSnakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}pluralize(e){return e.endsWith("y")?e.slice(0,-1)+"ies":e.endsWith("s")||e.endsWith("x")||e.endsWith("z")||e.endsWith("ch")||e.endsWith("sh")?e+"es":e+"s"}};import{writeFileSync as Hn,mkdirSync as zn,existsSync as Kn}from"fs";import{join as Wn}from"path";var Ct=class extends g{name="make:event";description="Create a new event class";arguments=["name"];flags=[{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide an event name (e.g. UserRegistered).");return}let r=t.module||s.replace(/([A-Z])/g," $1").trim().split(" ")[0].toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${r}" as module. Consider: --module ${r}`);let i=this.moduleDir(r,"events");zn(i,{recursive:!0});let a=Wn(i,`${s}.ts`);if(Kn(a)){this.warn(`Event ${s} already exists at ${a}`);return}let n=`/**
1325
1368
  * ${s} Event
1326
1369
  *
1327
1370
  * Dispatched when ... (describe when this event fires).
@@ -1339,7 +1382,7 @@ export class ${s} {
1339
1382
  // public readonly metadata?: Record<string, any>,
1340
1383
  ) {}
1341
1384
  }
1342
- `;An(a,n);let l=this.isDDD()?`src/lib/modules/${r}`:"src/lib/events";this.success(`Event created: ${l}/${s}.ts`)}};import{writeFileSync as Mn,mkdirSync as Nn,existsSync as In}from"fs";import{join as jn}from"path";var wt=class extends g{name="make:listener";description="Create a new event listener class";arguments=["name"];flags=[{name:"event",alias:"e",description:"The event class this listener handles",type:"string"},{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a listener name (e.g. SendWelcomeEmail).");return}let r=t.module||s.replace(/([A-Z])/g," $1").trim().split(" ")[0].toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${r}" as module. Consider: --module ${r}`);let i=this.moduleDir(r,"listeners");Nn(i,{recursive:!0});let a=jn(i,`${s}.ts`);if(In(a)){this.warn(`Listener ${s} already exists at ${a}`);return}let n=t.event||"any",l=t.event?this.isDDD()?`./${t.event}.js`:`../events/${t.event}.js`:"",c=t.event?`import type { ${t.event} } from '${l}';
1385
+ `;Hn(a,n);let l=this.isDDD()?`src/lib/modules/${r}`:"src/lib/events";this.success(`Event created: ${l}/${s}.ts`)}};import{writeFileSync as Jn,mkdirSync as Vn,existsSync as Qn}from"fs";import{join as Gn}from"path";var xt=class extends g{name="make:listener";description="Create a new event listener class";arguments=["name"];flags=[{name:"event",alias:"e",description:"The event class this listener handles",type:"string"},{name:"module",description:"Module name (e.g. auth, billing)",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a listener name (e.g. SendWelcomeEmail).");return}let r=t.module||s.replace(/([A-Z])/g," $1").trim().split(" ")[0].toLowerCase();!t.module&&this.isDDD()&&this.warn(`No --module specified. Using "${r}" as module. Consider: --module ${r}`);let i=this.moduleDir(r,"listeners");Vn(i,{recursive:!0});let a=Gn(i,`${s}.ts`);if(Qn(a)){this.warn(`Listener ${s} already exists at ${a}`);return}let n=t.event||"any",l=t.event?this.isDDD()?`./${t.event}.js`:`../events/${t.event}.js`:"",c=t.event?`import type { ${t.event} } from '${l}';
1343
1386
 
1344
1387
  `:"",m=t.event||"any",p=`import { Listener } from '@beeblock/svelar/events';
1345
1388
  ${c}export class ${s} extends Listener<${m}> {
@@ -1353,16 +1396,16 @@ ${c}export class ${s} extends Listener<${m}> {
1353
1396
  // return true;
1354
1397
  // }
1355
1398
  }
1356
- `;Mn(a,p);let h=this.isDDD()?`src/lib/modules/${r}`:"src/lib/listeners";this.success(`Listener created: ${h}/${s}.ts`),t.event&&(this.info("Don't forget to register it in your EventServiceProvider:"),this.info(` [${t.event}.name]: [${s}]`))}};import{writeFileSync as On,mkdirSync as qn,existsSync as Un}from"fs";import{join as Jr}from"path";var Ct=class extends g{name="make:route";description="Create route files with controller bindings";arguments=["path"];flags=[{name:"controller",alias:"c",description:"Controller class name",type:"string"},{name:"resource",alias:"r",description:"Generate full CRUD resource routes",type:"boolean"},{name:"api",description:"Prefix path with /api",type:"boolean"},{name:"methods",alias:"m",description:"HTTP methods (comma-separated: GET,POST,PUT,DELETE)",type:"string"},{name:"module",description:"Module name for controller import path",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a route path (e.g. posts, users/[id], admin/settings).");return}let r=s.replace(/^\//,"");t.api&&!r.startsWith("api/")&&(r="api/"+r);let i=t.controller||this.inferControllerName(r),a=t.module||this.inferModuleName(r);t.resource?this.generateResourceRoutes(r,i,a):this.generateRoute(r,i,a,t.methods)}generateResourceRoutes(e,t,s){this.generateRouteFile(e,t,s,[{method:"GET",handler:"index"},{method:"POST",handler:"store"}]);let r=this.inferParamName(e);this.generateRouteFile(`${e}/[${r}]`,t,s,[{method:"GET",handler:"show"},{method:"PUT",handler:"update"},{method:"DELETE",handler:"destroy"}])}generateRoute(e,t,s,r){let a=(r?r.split(",").map(n=>n.trim().toUpperCase()):["GET"]).map(n=>({method:n,handler:this.defaultHandler(n)}));this.generateRouteFile(e,t,s,a)}generateRouteFile(e,t,s,r){let i=Jr(process.cwd(),"src","routes",...e.split("/"));qn(i,{recursive:!0});let a=Jr(i,"+server.ts");if(Un(a)){this.warn(`Route already exists: src/routes/${e}/+server.ts (skipped)`);return}let n=this.isDDD()?`$lib/modules/${s}/${t}.js`:`$lib/controllers/${t}.js`,l=r.map(m=>`export const ${m.method} = ctrl.handle('${m.handler}');`).join(`
1399
+ `;Jn(a,p);let h=this.isDDD()?`src/lib/modules/${r}`:"src/lib/listeners";this.success(`Listener created: ${h}/${s}.ts`),t.event&&(this.info("Don't forget to register it in your EventServiceProvider:"),this.info(` [${t.event}.name]: [${s}]`))}};import{writeFileSync as Yn,mkdirSync as Zn,existsSync as Xn}from"fs";import{join as Yr}from"path";var Pt=class extends g{name="make:route";description="Create route files with controller bindings";arguments=["path"];flags=[{name:"controller",alias:"c",description:"Controller class name",type:"string"},{name:"resource",alias:"r",description:"Generate full CRUD resource routes",type:"boolean"},{name:"api",description:"Prefix path with /api",type:"boolean"},{name:"methods",alias:"m",description:"HTTP methods (comma-separated: GET,POST,PUT,DELETE)",type:"string"},{name:"module",description:"Module name for controller import path",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a route path (e.g. posts, users/[id], admin/settings).");return}let r=s.replace(/^\//,"");t.api&&!r.startsWith("api/")&&(r="api/"+r);let i=t.controller||this.inferControllerName(r),a=t.module||this.inferModuleName(r);t.resource?this.generateResourceRoutes(r,i,a):this.generateRoute(r,i,a,t.methods)}generateResourceRoutes(e,t,s){this.generateRouteFile(e,t,s,[{method:"GET",handler:"index"},{method:"POST",handler:"store"}]);let r=this.inferParamName(e);this.generateRouteFile(`${e}/[${r}]`,t,s,[{method:"GET",handler:"show"},{method:"PUT",handler:"update"},{method:"DELETE",handler:"destroy"}])}generateRoute(e,t,s,r){let a=(r?r.split(",").map(n=>n.trim().toUpperCase()):["GET"]).map(n=>({method:n,handler:this.defaultHandler(n)}));this.generateRouteFile(e,t,s,a)}generateRouteFile(e,t,s,r){let i=Yr(process.cwd(),"src","routes",...e.split("/"));Zn(i,{recursive:!0});let a=Yr(i,"+server.ts");if(Xn(a)){this.warn(`Route already exists: src/routes/${e}/+server.ts (skipped)`);return}let n=this.isDDD()?`$lib/modules/${s}/${t}.js`:`$lib/controllers/${t}.js`,l=r.map(m=>`export const ${m.method} = ctrl.handle('${m.handler}');`).join(`
1357
1400
  `),c=`import { ${t} } from '${n}';
1358
1401
 
1359
1402
  const ctrl = new ${t}();
1360
1403
  ${l}
1361
- `;On(a,c),this.success(`Route created: src/routes/${e}/+server.ts`);for(let m of r)this.info(` ${m.method} /${e} \u2192 ${t}.${m.handler}()`)}inferControllerName(e){let t=e.replace(/^api\//,"").split("/").filter(a=>!a.startsWith("[")),s=t[t.length-1]||t[0]||"Index",r=this.singularize(s);return`${r.charAt(0).toUpperCase()+r.slice(1)}Controller`}inferModuleName(e){return e.replace(/^api\//,"").split("/").filter(s=>!s.startsWith("["))[0]||"app"}inferParamName(e){return"id"}defaultHandler(e){return{GET:"index",POST:"store",PUT:"update",PATCH:"update",DELETE:"destroy"}[e]||e.toLowerCase()}singularize(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")||e.endsWith("ches")||e.endsWith("shes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}};import{join as Vr,relative as Cs,sep as xs}from"path";import{existsSync as Fn,readdirSync as Bn,readFileSync as Qr,statSync as Hn}from"fs";var xt=class extends g{name="routes:list";description="List all registered routes";arguments=[];flags=[{name:"json",description:"Output as JSON",type:"boolean"},{name:"api",description:"Show only API routes",type:"boolean"},{name:"method",alias:"m",description:"Filter by HTTP method (GET, POST, etc.)",type:"string"}];async handle(e,t){let s=Vr(process.cwd(),"src","routes");if(!Fn(s)){this.error("No src/routes/ directory found.");return}let i=this.scanRoutes(s,s);if(t.api&&(i=i.filter(m=>m.path.startsWith("/api"))),t.method){let m=t.method.toUpperCase();i=i.filter(p=>p.method===m)}if(i.sort((m,p)=>m.path.localeCompare(p.path)||m.method.localeCompare(p.method)),i.length===0){this.warn("No routes found.");return}if(t.json){this.log(JSON.stringify(i,null,2));return}this.log(""),this.log(` \x1B[1mApplication Routes\x1B[0m (${i.length} routes)
1362
- `);let a=Math.max(6,...i.map(m=>m.method.length)),n=Math.max(4,...i.map(m=>m.path.length)),l=Math.max(7,...i.map(m=>m.handler.length)),c=` ${"METHOD".padEnd(a)} ${"PATH".padEnd(n)} ${"HANDLER".padEnd(l)} FILE`;this.log(`\x1B[2m${c}\x1B[0m`),this.log(`\x1B[2m ${"\u2500".repeat(a)} ${"\u2500".repeat(n)} ${"\u2500".repeat(l)} ${"\u2500".repeat(20)}\x1B[0m`);for(let m of i){let h=`${this.getMethodColor(m.method)}${m.method.padEnd(a)}\x1B[0m`,u=m.path.padEnd(n),b=`\x1B[2m${m.handler.padEnd(l)}\x1B[0m`,y=`\x1B[2m${m.file}\x1B[0m`;this.log(` ${h} ${u} ${b} ${y}`)}this.log("")}scanRoutes(e,t){let s=[],r=Bn(e);for(let i of r){let a=Vr(e,i);if(Hn(a).isDirectory()){s.push(...this.scanRoutes(a,t));continue}i==="+server.ts"||i==="+server.js"?s.push(...this.parseServerFile(a,t)):(i==="+page.server.ts"||i==="+page.server.js")&&s.push(...this.parsePageServerFile(a,t))}return s}parseServerFile(e,t){let s=[],r=Qr(e,"utf-8"),i=this.filePathToUrl(e,t),a=Cs(process.cwd(),e).split(xs).join("/"),n=/export\s+(?:const|function)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g,l;for(;(l=n.exec(r))!==null;){let c=l[1],m=this.extractHandler(r,c);s.push({method:c,path:i,handler:m,file:a})}return s}parsePageServerFile(e,t){let s=[],r=Qr(e,"utf-8"),i=this.filePathToUrl(e,t),a=Cs(process.cwd(),e).split(xs).join("/");/export\s+(const|async\s+function)\s+load\b/.test(r)&&s.push({method:"GET",path:i,handler:"load()",file:a});let n=r.match(/export\s+const\s+actions\s*=\s*\{([^}]+)\}/);if(n){let l=n[1].split(",").map(c=>c.trim().split(":")[0].split("(")[0].trim()).filter(Boolean);for(let c of l)s.push({method:"POST",path:c==="default"?i:`${i}?/${c}`,handler:`actions.${c}()`,file:a})}return s}filePathToUrl(e,t){let s=Cs(t,e).split(xs).join("/");return s=s.replace(/\/?\+(?:server|page\.server)\.[tj]s$/,""),s=s.replace(/\[\.\.\.(\w+)\]/g,"*$1").replace(/\[\[(\w+)\]\]/g,":$1?").replace(/\[(\w+)\]/g,":$1"),s=s.replace(/\([^)]+\)\//g,""),"/"+s||"/"}extractHandler(e,t){let s=new RegExp(`export\\s+const\\s+${t}\\s*=\\s*(\\w+)\\.handle\\(['"]([^'"]+)['"]\\)`),r=e.match(s);if(r)return`${r[1]}.${r[2]}()`;let i=new RegExp(`const\\s*\\{[^}]*${t}[^}]*\\}\\s*=\\s*resource\\(\\s*(\\w+)`),a=e.match(i);return a?`${a[1]}.${{GET:"index/show",POST:"store",PUT:"update",PATCH:"update",DELETE:"destroy"}[t]??t.toLowerCase()}()`:new RegExp(`export\\s+(?:const|async\\s+function)\\s+${t}\\s*(?:=\\s*async)?`).test(e)?"inline handler":"handler"}getMethodColor(e){return{GET:"\x1B[32m",POST:"\x1B[33m",PUT:"\x1B[34m",PATCH:"\x1B[34m",DELETE:"\x1B[31m",HEAD:"\x1B[2m",OPTIONS:"\x1B[2m"}[e]||""}};import{readdirSync as zn}from"fs";import{join as Zr}from"path";import{pathToFileURL as Kn}from"url";var St=class extends g{name="migrate";description="Run pending database migrations";flags=[{name:"rollback",description:"Rollback the last batch of migrations",type:"boolean"},{name:"reset",description:"Reset all migrations",type:"boolean"},{name:"refresh",description:"Reset and re-run all migrations",type:"boolean"},{name:"fresh",description:"Drop all tables and re-run all migrations",type:"boolean"},{name:"status",description:"Show migration status",type:"boolean"},{name:"seed",description:"Run seeders after migrating",type:"boolean"},{name:"force",description:"Force destructive operations in production",type:"boolean"}];destructiveFlags=["reset","refresh","fresh"];async handle(e,t){await this.bootstrap();let s=this.destructiveFlags.find(c=>t[c]);s&&this.isProduction()&&!t.force&&(this.error(`The --${s} flag is destructive and cannot be run in production.`),this.error(`Use --force to run this command in production: npx svelar migrate --${s} --force`),process.exit(1));let{Migrator:r}=await Promise.resolve().then(()=>(Rs(),Yr)),i=new r,a=Zr(process.cwd(),"src","lib","database","migrations"),n=await this.loadMigrations(a);if(t.status){let c=await i.status(n);this.table(["Migration","Status","Batch"],c.map(m=>[m.name,m.ran?"\x1B[32mRan\x1B[0m":"\x1B[33mPending\x1B[0m",m.batch?.toString()??"-"]));return}if(t.rollback){this.info("Rolling back last batch...");let c=await i.rollback(n);if(c.length===0)this.info("Nothing to rollback.");else for(let m of c)this.success(`Rolled back: ${m}`);return}if(t.reset){this.warnDestructive("reset"),this.info("Resetting all migrations...");let c=await i.reset(n);if(c.length===0)this.info("Nothing to reset.");else for(let m of c)this.success(`Rolled back: ${m}`);return}if(t.refresh){this.warnDestructive("refresh"),this.info("Refreshing migrations...");let c=await i.refresh(n);for(let m of c.reset)this.success(`Rolled back: ${m}`);for(let m of c.migrated)this.success(`Migrated: ${m}`);return}if(t.fresh){this.warnDestructive("fresh"),this.info("Dropping all tables...");let c=await i.fresh(n);if(c.dropped.length>0)for(let m of c.dropped)this.success(`Dropped table: ${m}`);this.newLine(),this.info("Re-running all migrations...");for(let m of c.migrated)this.success(`Migrated: ${m}`);return}this.info("Running migrations...");let l=await i.run(n);if(l.length===0)this.info("Nothing to migrate.");else for(let c of l)this.success(`Migrated: ${c}`)}isProduction(){return(process.env.NODE_ENV||process.env.APP_ENV||"development")==="production"}warnDestructive(e){this.isProduction()&&this.warn(`Running --${e} in PRODUCTION with --force.`)}async loadMigrations(e){let t;try{t=zn(e).filter(r=>r.endsWith(".ts")||r.endsWith(".js")).sort()}catch{return this.warn(`Migrations directory not found: ${e}`),[]}let s=[];for(let r of t){let i=Zr(e,r);try{let a=await import(Kn(i).href),n=a.default??Object.values(a).find(l=>typeof l=="function"&&l.prototype&&typeof l.prototype.up=="function");n?s.push({name:r.replace(/\.(ts|js)$/,""),timestamp:r.split("_")[0],path:i,migration:new n}):this.warn(`No migration class found in: ${r}`)}catch(a){let n;try{n=a instanceof Error?a.message:String(a)}catch{n=JSON.stringify(a)??"Unknown error (non-stringifiable object)"}this.error(`Failed to load migration ${r}: ${n}`)}}return s}};import{join as Ts}from"path";import{pathToFileURL as Wn}from"url";import{existsSync as Xr}from"fs";var Pt=class extends g{name="seed:run";description="Run database seeders";flags=[{name:"class",description:"Specific seeder class to run",type:"string"}];async handle(e,t){await this.bootstrap();let s=Ts(process.cwd(),"src","lib","database","seeders"),r=t.class?Ts(s,`${t.class}.ts`):Ts(s,"DatabaseSeeder.ts"),i=r;Xr(i)||(i=i.replace(/\.ts$/,".js")),Xr(i)||(this.error(`Seeder not found: ${r}`),process.exit(1)),this.info("Running seeders...");try{let a=await import(Wn(i).href),n=a.default??a.DatabaseSeeder??Object.values(a).find(c=>typeof c=="function"&&c.prototype&&typeof c.prototype.run=="function");(!n||typeof n!="function")&&(this.error("No seeder class found in file."),process.exit(1)),await new n().run(),this.success("Database seeded successfully.")}catch(a){let n=a instanceof Error?a.message:String(a);this.error(`Seeding failed: ${n}`),a?.stack&&console.error(a.stack),process.exit(1)}}};import{existsSync as Gn,readdirSync as Yn}from"fs";import{join as $s}from"path";import{pathToFileURL as Zn}from"url";var kt=class extends g{name="schedule:run";description="Run the task scheduler";flags=[{name:"once",description:"Run due tasks once and exit",type:"boolean"}];async handle(e,t){await this.bootstrap();let{Scheduler:s}=await Promise.resolve().then(()=>(ri(),si)),r=new s;r.persistToDatabase();let i=$s(process.cwd(),"src","lib","shared","scheduler"),a=$s(process.cwd(),"src","lib","scheduler"),n=Gn(i)?i:a,l=await this.loadTasks(n);if(l.length===0){this.warn("No scheduled tasks found in src/lib/shared/scheduler/ or src/lib/scheduler/");return}for(let p of l)r.register(p),this.info(`Registered task: ${p.name}`);if(this.newLine(),t.once){this.info("Running due tasks (once)...");let p=await r.run();if(p.length===0)this.info("No tasks were due.");else for(let h of p)h.success?this.success(`${h.task}: completed in ${h.duration}ms`):this.error(`${h.task}: failed \u2014 ${h.error}`);return}this.info("Scheduler running. Press Ctrl+C to stop."),this.newLine();let c=async()=>{let p=await r.run();for(let h of p){let u=new Date().toISOString().replace("T"," ").slice(0,19);h.success?this.success(`[${u}] ${h.task}: completed in ${h.duration}ms`):this.error(`[${u}] ${h.task}: failed \u2014 ${h.error}`)}};await c();let m=6e4-Date.now()%6e4;this.info(`Next tick aligned to minute boundary in ${Math.round(m/1e3)}s.`),await new Promise(p=>setTimeout(p,m)),await c(),setInterval(c,6e4),await new Promise(()=>{})}async loadTasks(e){let t;try{t=Yn(e).filter(r=>(r.endsWith(".ts")||r.endsWith(".js"))&&!r.startsWith("index")).sort()}catch{return[]}let s=[];for(let r of t){let i=$s(e,r);try{let a=await import(Zn(i).href),n=a.default??Object.values(a).find(l=>typeof l=="function"&&l.prototype&&typeof l.prototype.handle=="function");if(n){let l=new n;l.schedule(),s.push(l)}}catch(a){this.error(`Failed to load task ${r}: ${a.message??a}`)}}return s}};var At=class extends g{name="queue:work";description="Process queued jobs";flags=[{name:"queue",description:'Queue name to process (default: "default")',type:"string",default:"default"},{name:"max-jobs",description:"Stop after processing N jobs",type:"string"},{name:"max-time",description:"Stop after N seconds",type:"string"},{name:"sleep",description:"Sleep N milliseconds between polls (default: 1000)",type:"string",default:"1000"},{name:"once",description:"Process a single job and exit",type:"boolean"}];async handle(e,t){await this.bootstrap();let{Queue:s}=await Promise.resolve().then(()=>(ee(),Le)),r=t.queue??"default",i=t["max-jobs"]?parseInt(t["max-jobs"]):void 0,a=t["max-time"]?parseInt(t["max-time"]):void 0,n=t.sleep?parseInt(t.sleep):1e3;if(this.info(`Processing queue "${r}"...`),i&&this.info(`Will stop after ${i} jobs.`),a&&this.info(`Will stop after ${a} seconds.`),this.newLine(),t.once){let m=await s.work({queue:r,maxJobs:1,sleep:0});m===0?this.info("No jobs to process."):this.success(`Processed ${m} job(s).`);return}this.info(`Worker running on "${r}". Press Ctrl+C to stop.`),this.newLine();let l=Date.now(),c=0;for(;;){if(a&&(Date.now()-l)/1e3>=a){this.info(`Max time (${a}s) reached. Stopping.`);break}if(i&&c>=i){this.info(`Max jobs (${i}) reached. Stopping.`);break}let m=await s.work({queue:r,maxJobs:1,sleep:0});if(m>0){c+=m;let p=new Date().toISOString().replace("T"," ").slice(0,19);this.success(`[${p}] Processed ${m} job(s) (total: ${c})`)}else await new Promise(p=>setTimeout(p,n))}this.newLine(),this.info(`Worker stopped. Total jobs processed: ${c}`)}};var Dt=class extends g{name="queue:failed";description="List all failed jobs";async handle(e,t){await this.bootstrap();let{Queue:s}=await Promise.resolve().then(()=>(ee(),Le)),r=await s.failed();if(r.length===0){this.info("No failed jobs.");return}this.info(`Found ${r.length} failed job(s):
1404
+ `;Yn(a,c),this.success(`Route created: src/routes/${e}/+server.ts`);for(let m of r)this.info(` ${m.method} /${e} \u2192 ${t}.${m.handler}()`)}inferControllerName(e){let t=e.replace(/^api\//,"").split("/").filter(a=>!a.startsWith("[")),s=t[t.length-1]||t[0]||"Index",r=this.singularize(s);return`${r.charAt(0).toUpperCase()+r.slice(1)}Controller`}inferModuleName(e){return e.replace(/^api\//,"").split("/").filter(s=>!s.startsWith("["))[0]||"app"}inferParamName(e){return"id"}defaultHandler(e){return{GET:"index",POST:"store",PUT:"update",PATCH:"update",DELETE:"destroy"}[e]||e.toLowerCase()}singularize(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")||e.endsWith("ches")||e.endsWith("shes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}};import{join as Zr,relative as Ps,sep as Ss}from"path";import{existsSync as eo,readdirSync as to,readFileSync as Xr,statSync as so}from"fs";var St=class extends g{name="routes:list";description="List all registered routes";arguments=[];flags=[{name:"json",description:"Output as JSON",type:"boolean"},{name:"api",description:"Show only API routes",type:"boolean"},{name:"method",alias:"m",description:"Filter by HTTP method (GET, POST, etc.)",type:"string"}];async handle(e,t){let s=Zr(process.cwd(),"src","routes");if(!eo(s)){this.error("No src/routes/ directory found.");return}let i=this.scanRoutes(s,s);if(t.api&&(i=i.filter(m=>m.path.startsWith("/api"))),t.method){let m=t.method.toUpperCase();i=i.filter(p=>p.method===m)}if(i.sort((m,p)=>m.path.localeCompare(p.path)||m.method.localeCompare(p.method)),i.length===0){this.warn("No routes found.");return}if(t.json){this.log(JSON.stringify(i,null,2));return}this.log(""),this.log(` \x1B[1mApplication Routes\x1B[0m (${i.length} routes)
1405
+ `);let a=Math.max(6,...i.map(m=>m.method.length)),n=Math.max(4,...i.map(m=>m.path.length)),l=Math.max(7,...i.map(m=>m.handler.length)),c=` ${"METHOD".padEnd(a)} ${"PATH".padEnd(n)} ${"HANDLER".padEnd(l)} FILE`;this.log(`\x1B[2m${c}\x1B[0m`),this.log(`\x1B[2m ${"\u2500".repeat(a)} ${"\u2500".repeat(n)} ${"\u2500".repeat(l)} ${"\u2500".repeat(20)}\x1B[0m`);for(let m of i){let h=`${this.getMethodColor(m.method)}${m.method.padEnd(a)}\x1B[0m`,u=m.path.padEnd(n),b=`\x1B[2m${m.handler.padEnd(l)}\x1B[0m`,y=`\x1B[2m${m.file}\x1B[0m`;this.log(` ${h} ${u} ${b} ${y}`)}this.log("")}scanRoutes(e,t){let s=[],r=to(e);for(let i of r){let a=Zr(e,i);if(so(a).isDirectory()){s.push(...this.scanRoutes(a,t));continue}i==="+server.ts"||i==="+server.js"?s.push(...this.parseServerFile(a,t)):(i==="+page.server.ts"||i==="+page.server.js")&&s.push(...this.parsePageServerFile(a,t))}return s}parseServerFile(e,t){let s=[],r=Xr(e,"utf-8"),i=this.filePathToUrl(e,t),a=Ps(process.cwd(),e).split(Ss).join("/"),n=/export\s+(?:const|function)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g,l;for(;(l=n.exec(r))!==null;){let c=l[1],m=this.extractHandler(r,c);s.push({method:c,path:i,handler:m,file:a})}return s}parsePageServerFile(e,t){let s=[],r=Xr(e,"utf-8"),i=this.filePathToUrl(e,t),a=Ps(process.cwd(),e).split(Ss).join("/");/export\s+(const|async\s+function)\s+load\b/.test(r)&&s.push({method:"GET",path:i,handler:"load()",file:a});let n=r.match(/export\s+const\s+actions\s*=\s*\{([^}]+)\}/);if(n){let l=n[1].split(",").map(c=>c.trim().split(":")[0].split("(")[0].trim()).filter(Boolean);for(let c of l)s.push({method:"POST",path:c==="default"?i:`${i}?/${c}`,handler:`actions.${c}()`,file:a})}return s}filePathToUrl(e,t){let s=Ps(t,e).split(Ss).join("/");return s=s.replace(/\/?\+(?:server|page\.server)\.[tj]s$/,""),s=s.replace(/\[\.\.\.(\w+)\]/g,"*$1").replace(/\[\[(\w+)\]\]/g,":$1?").replace(/\[(\w+)\]/g,":$1"),s=s.replace(/\([^)]+\)\//g,""),"/"+s||"/"}extractHandler(e,t){let s=new RegExp(`export\\s+const\\s+${t}\\s*=\\s*(\\w+)\\.handle\\(['"]([^'"]+)['"]\\)`),r=e.match(s);if(r)return`${r[1]}.${r[2]}()`;let i=new RegExp(`const\\s*\\{[^}]*${t}[^}]*\\}\\s*=\\s*resource\\(\\s*(\\w+)`),a=e.match(i);return a?`${a[1]}.${{GET:"index/show",POST:"store",PUT:"update",PATCH:"update",DELETE:"destroy"}[t]??t.toLowerCase()}()`:new RegExp(`export\\s+(?:const|async\\s+function)\\s+${t}\\s*(?:=\\s*async)?`).test(e)?"inline handler":"handler"}getMethodColor(e){return{GET:"\x1B[32m",POST:"\x1B[33m",PUT:"\x1B[34m",PATCH:"\x1B[34m",DELETE:"\x1B[31m",HEAD:"\x1B[2m",OPTIONS:"\x1B[2m"}[e]||""}};import{readdirSync as ro}from"fs";import{join as si}from"path";import{pathToFileURL as io}from"url";var Rt=class extends g{name="migrate";description="Run pending database migrations";flags=[{name:"rollback",description:"Rollback the last batch of migrations",type:"boolean"},{name:"reset",description:"Reset all migrations",type:"boolean"},{name:"refresh",description:"Reset and re-run all migrations",type:"boolean"},{name:"fresh",description:"Drop all tables and re-run all migrations",type:"boolean"},{name:"status",description:"Show migration status",type:"boolean"},{name:"seed",description:"Run seeders after migrating",type:"boolean"},{name:"force",description:"Force destructive operations in production",type:"boolean"}];destructiveFlags=["reset","refresh","fresh"];async handle(e,t){await this.bootstrap();let s=this.destructiveFlags.find(c=>t[c]);s&&this.isProduction()&&!t.force&&(this.error(`The --${s} flag is destructive and cannot be run in production.`),this.error(`Use --force to run this command in production: npx svelar migrate --${s} --force`),process.exit(1));let{Migrator:r}=await Promise.resolve().then(()=>(ks(),ti)),i=new r,a=si(process.cwd(),"src","lib","database","migrations"),n=await this.loadMigrations(a);if(t.status){let c=await i.status(n);this.table(["Migration","Status","Batch"],c.map(m=>[m.name,m.ran?"\x1B[32mRan\x1B[0m":"\x1B[33mPending\x1B[0m",m.batch?.toString()??"-"]));return}if(t.rollback){this.info("Rolling back last batch...");let c=await i.rollback(n);if(c.length===0)this.info("Nothing to rollback.");else for(let m of c)this.success(`Rolled back: ${m}`);return}if(t.reset){this.warnDestructive("reset"),this.info("Resetting all migrations...");let c=await i.reset(n);if(c.length===0)this.info("Nothing to reset.");else for(let m of c)this.success(`Rolled back: ${m}`);return}if(t.refresh){this.warnDestructive("refresh"),this.info("Refreshing migrations...");let c=await i.refresh(n);for(let m of c.reset)this.success(`Rolled back: ${m}`);for(let m of c.migrated)this.success(`Migrated: ${m}`);return}if(t.fresh){this.warnDestructive("fresh"),this.info("Dropping all tables...");let c=await i.fresh(n);if(c.dropped.length>0)for(let m of c.dropped)this.success(`Dropped table: ${m}`);this.newLine(),this.info("Re-running all migrations...");for(let m of c.migrated)this.success(`Migrated: ${m}`);return}this.info("Running migrations...");let l=await i.run(n);if(l.length===0)this.info("Nothing to migrate.");else for(let c of l)this.success(`Migrated: ${c}`)}isProduction(){return(process.env.NODE_ENV||process.env.APP_ENV||"development")==="production"}warnDestructive(e){this.isProduction()&&this.warn(`Running --${e} in PRODUCTION with --force.`)}async loadMigrations(e){let t;try{t=ro(e).filter(r=>r.endsWith(".ts")||r.endsWith(".js")).sort()}catch{return this.warn(`Migrations directory not found: ${e}`),[]}let s=[];for(let r of t){let i=si(e,r);try{let a=await import(io(i).href),n=a.default??Object.values(a).find(l=>typeof l=="function"&&l.prototype&&typeof l.prototype.up=="function");n?s.push({name:r.replace(/\.(ts|js)$/,""),timestamp:r.split("_")[0],path:i,migration:new n}):this.warn(`No migration class found in: ${r}`)}catch(a){let n;try{n=a instanceof Error?a.message:String(a)}catch{n=JSON.stringify(a)??"Unknown error (non-stringifiable object)"}this.error(`Failed to load migration ${r}: ${n}`)}}return s}};import{join as Es}from"path";import{pathToFileURL as ao}from"url";import{existsSync as ri}from"fs";var Tt=class extends g{name="seed:run";description="Run database seeders";flags=[{name:"class",description:"Specific seeder class to run",type:"string"}];async handle(e,t){await this.bootstrap();let s=Es(process.cwd(),"src","lib","database","seeders"),r=t.class?Es(s,`${t.class}.ts`):Es(s,"DatabaseSeeder.ts"),i=r;ri(i)||(i=i.replace(/\.ts$/,".js")),ri(i)||(this.error(`Seeder not found: ${r}`),process.exit(1)),this.info("Running seeders...");try{let a=await import(ao(i).href),n=a.default??a.DatabaseSeeder??Object.values(a).find(c=>typeof c=="function"&&c.prototype&&typeof c.prototype.run=="function");(!n||typeof n!="function")&&(this.error("No seeder class found in file."),process.exit(1)),await new n().run(),this.success("Database seeded successfully.")}catch(a){let n=a instanceof Error?a.message:String(a);this.error(`Seeding failed: ${n}`),a?.stack&&console.error(a.stack),process.exit(1)}}};import{existsSync as co,readdirSync as uo}from"fs";import{join as Ds}from"path";import{pathToFileURL as mo}from"url";var $t=class extends g{name="schedule:run";description="Run the task scheduler";flags=[{name:"once",description:"Run due tasks once and exit",type:"boolean"}];async handle(e,t){await this.bootstrap();let{Scheduler:s}=await Promise.resolve().then(()=>(oi(),ni)),r=new s;r.persistToDatabase();let i=Ds(process.cwd(),"src","lib","shared","scheduler"),a=Ds(process.cwd(),"src","lib","scheduler"),n=co(i)?i:a,l=await this.loadTasks(n);if(l.length===0){this.warn("No scheduled tasks found in src/lib/shared/scheduler/ or src/lib/scheduler/");return}for(let p of l)r.register(p),this.info(`Registered task: ${p.name}`);if(this.newLine(),t.once){this.info("Running due tasks (once)...");let p=await r.run();if(p.length===0)this.info("No tasks were due.");else for(let h of p)h.success?this.success(`${h.task}: completed in ${h.duration}ms`):this.error(`${h.task}: failed \u2014 ${h.error}`);return}this.info("Scheduler running. Press Ctrl+C to stop."),this.newLine();let c=async()=>{let p=await r.run();for(let h of p){let u=new Date().toISOString().replace("T"," ").slice(0,19);h.success?this.success(`[${u}] ${h.task}: completed in ${h.duration}ms`):this.error(`[${u}] ${h.task}: failed \u2014 ${h.error}`)}};await c();let m=6e4-Date.now()%6e4;this.info(`Next tick aligned to minute boundary in ${Math.round(m/1e3)}s.`),await new Promise(p=>setTimeout(p,m)),await c(),setInterval(c,6e4),await new Promise(()=>{})}async loadTasks(e){let t;try{t=uo(e).filter(r=>(r.endsWith(".ts")||r.endsWith(".js"))&&!r.startsWith("index")).sort()}catch{return[]}let s=[];for(let r of t){let i=Ds(e,r);try{let a=await import(mo(i).href),n=a.default??Object.values(a).find(l=>typeof l=="function"&&l.prototype&&typeof l.prototype.handle=="function");if(n){let l=new n;l.schedule(),s.push(l)}}catch(a){this.error(`Failed to load task ${r}: ${a.message??a}`)}}return s}};var Lt=class extends g{name="queue:work";description="Process queued jobs";flags=[{name:"queue",description:'Queue name to process (default: "default")',type:"string",default:"default"},{name:"max-jobs",description:"Stop after processing N jobs",type:"string"},{name:"max-time",description:"Stop after N seconds",type:"string"},{name:"sleep",description:"Sleep N milliseconds between polls (default: 1000)",type:"string",default:"1000"},{name:"once",description:"Process a single job and exit",type:"boolean"}];async handle(e,t){await this.bootstrap();let{Queue:s}=await Promise.resolve().then(()=>(ee(),Le)),r=t.queue??"default",i=t["max-jobs"]?parseInt(t["max-jobs"]):void 0,a=t["max-time"]?parseInt(t["max-time"]):void 0,n=t.sleep?parseInt(t.sleep):1e3;if(this.info(`Processing queue "${r}"...`),i&&this.info(`Will stop after ${i} jobs.`),a&&this.info(`Will stop after ${a} seconds.`),this.newLine(),t.once){let m=await s.work({queue:r,maxJobs:1,sleep:0});m===0?this.info("No jobs to process."):this.success(`Processed ${m} job(s).`);return}this.info(`Worker running on "${r}". Press Ctrl+C to stop.`),this.newLine();let l=Date.now(),c=0;for(;;){if(a&&(Date.now()-l)/1e3>=a){this.info(`Max time (${a}s) reached. Stopping.`);break}if(i&&c>=i){this.info(`Max jobs (${i}) reached. Stopping.`);break}let m=await s.work({queue:r,maxJobs:1,sleep:0});if(m>0){c+=m;let p=new Date().toISOString().replace("T"," ").slice(0,19);this.success(`[${p}] Processed ${m} job(s) (total: ${c})`)}else await new Promise(p=>setTimeout(p,n))}this.newLine(),this.info(`Worker stopped. Total jobs processed: ${c}`)}};var _t=class extends g{name="queue:failed";description="List all failed jobs";async handle(e,t){await this.bootstrap();let{Queue:s}=await Promise.resolve().then(()=>(ee(),Le)),r=await s.failed();if(r.length===0){this.info("No failed jobs.");return}this.info(`Found ${r.length} failed job(s):
1363
1406
  `);for(let i of r){let a=new Date(i.failedAt*1e3).toISOString().replace("T"," ").slice(0,19);this.log(` ID: ${i.id}`),this.log(` Job: ${i.jobClass}`),this.log(` Queue: ${i.queue}`),this.log(` Date: ${a}`),this.log(` Error: ${i.exception.split(`
1364
- `)[0]}`),this.log("")}}};var Lt=class extends g{name="queue:retry";description="Retry a failed job (or all failed jobs)";arguments=["id"];flags=[{name:"all",description:"Retry all failed jobs",type:"boolean",default:!1}];async handle(e,t){await this.bootstrap();let{Queue:s}=await Promise.resolve().then(()=>(ee(),Le));if(t.all){let a=await s.retryAll();a===0?this.info("No failed jobs to retry."):this.success(`Retried ${a} job(s).`);return}let r=e[0];r||(this.error("Please provide a failed job ID, or use --all to retry all."),process.exit(1)),await s.retry(r)?this.success(`Job ${r} has been pushed back onto the queue.`):this.error(`Failed job with ID "${r}" not found.`)}};var _t=class extends g{name="queue:flush";description="Delete all failed job records";async handle(e,t){await this.bootstrap();let{Queue:s}=await Promise.resolve().then(()=>(ee(),Le)),r=await s.flushFailed();r===0?this.info("No failed jobs to flush."):this.success(`Flushed ${r} failed job record(s).`)}};var os=class extends g{name="tinker";description="Start an interactive REPL with Svelar preloaded";flags=[];async handle(){await this.bootstrap(),this.info("Starting Svelar Tinker..."),this.log(`Type .exit to quit. All Svelar modules are available.
1365
- `);let t=(await import("repl")).start({prompt:"\x1B[36msvelar>\x1B[0m ",useGlobal:!0});try{let s=await Promise.resolve().then(()=>(ea(),Xi));for(let[r,i]of Object.entries(s))t.context[r]=i;t.context.DB=s.Connection,t.context.Schema=s.Schema,this.log("Available: Model, QueryBuilder, Connection, Schema, Hash, Cache, Event, Log, ..."),this.log("")}catch(s){this.warn(`Could not preload all modules: ${s.message}`)}try{let{readdirSync:s}=await import("fs"),{join:r}=await import("path"),{pathToFileURL:i}=await import("url"),{existsSync:a}=await import("fs"),n=r(process.cwd(),"src","lib","models"),l=r(process.cwd(),"src","lib","modules"),c=[],m=n;if(a(n))m=n,c=s(n).filter(p=>(p.endsWith(".ts")||p.endsWith(".js"))&&!p.startsWith("index"));else if(a(l)){m=l;for(let p of s(l,{withFileTypes:!0})){if(!p.isDirectory())continue;let h=r(l,p.name);for(let u of s(h))(u.endsWith(".ts")||u.endsWith(".js"))&&(u.startsWith("index")||u.includes("Controller")||u.includes("Service")||u.includes("Repository")||u.includes("Request")||u.includes("Resource")||u.includes("schema")||u.includes("gates")||c.push(r(p.name,u)))}}for(let p of c)try{let h=await import(i(r(m,p)).href);for(let[u,b]of Object.entries(h))typeof b=="function"&&(t.context[u]=b)}catch{}c.length>0&&this.log(`Loaded models: ${c.map(p=>p.replace(/\.(ts|js)$/,"")).join(", ")}`)}catch{}await new Promise(s=>{t.on("exit",s)})}};var d=class{static packageJson(e,t="0.4.0"){return JSON.stringify({name:e,version:"0.0.1",private:!0,type:"module",scripts:{dev:"vite dev",build:"vite build",preview:"vite preview",migrate:"npx svelar migrate","migrate:rollback":"npx svelar migrate --rollback","migrate:refresh":"npx svelar migrate --refresh",seed:"npx svelar seed:run"},devDependencies:{"@sveltejs/adapter-auto":"^3.0.0","@sveltejs/kit":"^2.55.0","@sveltejs/vite-plugin-svelte":"^5.0.0","@tailwindcss/vite":"^4.2.2","lucide-svelte":"^0.468.0",svelte:"^5.0.0","svelte-check":"^4.0.0",tailwindcss:"^4.2.2",typescript:"^5.7.0",vite:"^6.0.0"},dependencies:{"better-sqlite3":"^11.0.0","drizzle-orm":"^0.38.0","@beeblock/svelar":`^${t}`,exceljs:"^4.4.0",pdfkit:"^0.18.0","sveltekit-superforms":"^2.22.0",zod:"^3.23.0"}},null,2)+`
1407
+ `)[0]}`),this.log("")}}};var Mt=class extends g{name="queue:retry";description="Retry a failed job (or all failed jobs)";arguments=["id"];flags=[{name:"all",description:"Retry all failed jobs",type:"boolean",default:!1}];async handle(e,t){await this.bootstrap();let{Queue:s}=await Promise.resolve().then(()=>(ee(),Le));if(t.all){let a=await s.retryAll();a===0?this.info("No failed jobs to retry."):this.success(`Retried ${a} job(s).`);return}let r=e[0];r||(this.error("Please provide a failed job ID, or use --all to retry all."),process.exit(1)),await s.retry(r)?this.success(`Job ${r} has been pushed back onto the queue.`):this.error(`Failed job with ID "${r}" not found.`)}};var Nt=class extends g{name="queue:flush";description="Delete all failed job records";async handle(e,t){await this.bootstrap();let{Queue:s}=await Promise.resolve().then(()=>(ee(),Le)),r=await s.flushFailed();r===0?this.info("No failed jobs to flush."):this.success(`Flushed ${r} failed job record(s).`)}};var cs=class extends g{name="tinker";description="Start an interactive REPL with Svelar preloaded";flags=[];async handle(){await this.bootstrap(),this.info("Starting Svelar Tinker..."),this.log(`Type .exit to quit. All Svelar modules are available.
1408
+ `);let t=(await import("repl")).start({prompt:"\x1B[36msvelar>\x1B[0m ",useGlobal:!0});try{let s=await Promise.resolve().then(()=>(ia(),ra));for(let[r,i]of Object.entries(s))t.context[r]=i;t.context.DB=s.Connection,t.context.Schema=s.Schema,this.log("Available: Model, QueryBuilder, Connection, Schema, Hash, Cache, Event, Log, ..."),this.log("")}catch(s){this.warn(`Could not preload all modules: ${s.message}`)}try{let{readdirSync:s}=await import("fs"),{join:r}=await import("path"),{pathToFileURL:i}=await import("url"),{existsSync:a}=await import("fs"),n=r(process.cwd(),"src","lib","models"),l=r(process.cwd(),"src","lib","modules"),c=[],m=n;if(a(n))m=n,c=s(n).filter(p=>(p.endsWith(".ts")||p.endsWith(".js"))&&!p.startsWith("index"));else if(a(l)){m=l;for(let p of s(l,{withFileTypes:!0})){if(!p.isDirectory())continue;let h=r(l,p.name);for(let u of s(h))(u.endsWith(".ts")||u.endsWith(".js"))&&(u.startsWith("index")||u.includes("Controller")||u.includes("Service")||u.includes("Repository")||u.includes("Request")||u.includes("Resource")||u.includes("schema")||u.includes("gates")||c.push(r(p.name,u)))}}for(let p of c)try{let h=await import(i(r(m,p)).href);for(let[u,b]of Object.entries(h))typeof b=="function"&&(t.context[u]=b)}catch{}c.length>0&&this.log(`Loaded models: ${c.map(p=>p.replace(/\.(ts|js)$/,"")).join(", ")}`)}catch{}await new Promise(s=>{t.on("exit",s)})}};var d=class{static packageJson(e,t="0.4.0"){return JSON.stringify({name:e,version:"0.0.1",private:!0,type:"module",scripts:{dev:"vite dev",build:"vite build",preview:"vite preview",migrate:"npx svelar migrate","migrate:rollback":"npx svelar migrate --rollback","migrate:refresh":"npx svelar migrate --refresh",seed:"npx svelar seed:run",test:"vitest run","test:watch":"vitest","test:e2e":"playwright test","test:coverage":"vitest run --coverage"},devDependencies:{"@sveltejs/adapter-auto":"^3.0.0","@sveltejs/kit":"^2.55.0","@sveltejs/vite-plugin-svelte":"^5.0.0","@tailwindcss/vite":"^4.2.2","lucide-svelte":"^0.468.0",svelte:"^5.0.0","svelte-check":"^4.0.0",tailwindcss:"^4.2.2",typescript:"^5.7.0",vite:"^6.0.0",vitest:"^2.1.0","@playwright/test":"^1.48.0"},dependencies:{"better-sqlite3":"^11.0.0","drizzle-orm":"^0.38.0","@beeblock/svelar":`^${t}`,exceljs:"^4.4.0",pdfkit:"^0.18.0","sveltekit-superforms":"^2.22.0",zod:"^3.23.0"}},null,2)+`
1366
1409
  `}static svelteConfig(){return`import adapter from '@sveltejs/adapter-auto';
1367
1410
  import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
1368
1411
 
@@ -1447,6 +1490,7 @@ export default defineConfig({
1447
1490
  '@beeblock/svelar/ui': resolve(svelarRoot, 'src/ui/index.ts'),
1448
1491
  '@beeblock/svelar/i18n/LanguageSwitcher.svelte': resolve(svelarRoot, 'src/i18n/LanguageSwitcher.svelte'),
1449
1492
  '@beeblock/svelar/i18n': resolve(svelarRoot, 'dist/i18n/index.js'),
1493
+ '@beeblock/svelar/testing': resolve(svelarRoot, 'dist/testing/index.js'),
1450
1494
  '@beeblock/svelar': resolve(svelarRoot, 'dist/index.js'),
1451
1495
  },
1452
1496
  },
@@ -1806,6 +1850,11 @@ storage/cache/*
1806
1850
  storage/uploads/*
1807
1851
  storage/sessions/*
1808
1852
  !storage/**/.gitkeep
1853
+
1854
+ # Testing
1855
+ test-results/
1856
+ playwright-report/
1857
+ coverage/
1809
1858
  `}static svelarDatabaseJson(){return JSON.stringify({default:"sqlite",connections:{sqlite:{driver:"sqlite",filename:"database.db"}}},null,2)+`
1810
1859
  `}static userModel(){return`import { Model } from '@beeblock/svelar/orm';
1811
1860
  import { HasRoles } from '@beeblock/svelar/permissions';
@@ -3828,7 +3877,7 @@ export const actions: Actions = {
3828
3877
  let codeSent = $state(false);
3829
3878
  let email = $state('');
3830
3879
 
3831
- const requestSuperForm = superForm(data.requestForm, {
3880
+ const { form: requestForm, errors: requestErrors, enhance: requestEnhance, delayed: requestDelayed } = superForm(data.requestForm, {
3832
3881
  onResult: ({ result }) => {
3833
3882
  if (result.type === 'success' && result.data?.codeSent) {
3834
3883
  codeSent = true;
@@ -3837,7 +3886,7 @@ export const actions: Actions = {
3837
3886
  },
3838
3887
  });
3839
3888
 
3840
- const verifySuperForm = superForm(data.verifyForm);
3889
+ const { form: verifyForm, errors: verifyErrors, enhance: verifyEnhance, delayed: verifyDelayed, message: verifyMessage } = superForm(data.verifyForm);
3841
3890
  </script>
3842
3891
 
3843
3892
  <svelte:head>
@@ -3858,14 +3907,14 @@ export const actions: Actions = {
3858
3907
  </CardHeader>
3859
3908
 
3860
3909
  <CardContent class="space-y-4">
3861
- {#if verifySuperForm.message}
3910
+ {#if $verifyMessage}
3862
3911
  <Alert variant="destructive">
3863
- <span class="text-sm">{verifySuperForm.message}</span>
3912
+ <span class="text-sm">{$verifyMessage}</span>
3864
3913
  </Alert>
3865
3914
  {/if}
3866
3915
 
3867
3916
  {#if !codeSent}
3868
- <form method="POST" action="?/send" use:requestSuperForm.enhance class="space-y-4">
3917
+ <form method="POST" action="?/send" use:requestEnhance class="space-y-4">
3869
3918
  <div class="space-y-2">
3870
3919
  <Label for="email">Email</Label>
3871
3920
  <Input
@@ -3873,21 +3922,21 @@ export const actions: Actions = {
3873
3922
  name="email"
3874
3923
  type="email"
3875
3924
  placeholder="you@example.com"
3876
- bind:value={requestSuperForm.form.email}
3877
- aria-invalid={requestSuperForm.errors.email ? 'true' : undefined}
3878
- disabled={requestSuperForm.delayed}
3925
+ bind:value={$requestForm.email}
3926
+ aria-invalid={$requestErrors.email ? 'true' : undefined}
3927
+ disabled={$requestDelayed}
3879
3928
  />
3880
- {#if requestSuperForm.errors.email}
3881
- <p class="text-sm text-red-600">{requestSuperForm.errors.email[0]}</p>
3929
+ {#if $requestErrors.email}
3930
+ <p class="text-sm text-red-600">{$requestErrors.email[0]}</p>
3882
3931
  {/if}
3883
3932
  </div>
3884
3933
 
3885
- <Button type="submit" class="w-full" disabled={requestSuperForm.delayed}>
3886
- {requestSuperForm.delayed ? 'Sending...' : 'Send Code'}
3934
+ <Button type="submit" class="w-full" disabled={$requestDelayed}>
3935
+ {$requestDelayed ? 'Sending...' : 'Send Code'}
3887
3936
  </Button>
3888
3937
  </form>
3889
3938
  {:else}
3890
- <form method="POST" action="?/verify" use:verifySuperForm.enhance class="space-y-4">
3939
+ <form method="POST" action="?/verify" use:verifyEnhance class="space-y-4">
3891
3940
  <input type="hidden" name="email" value={email} />
3892
3941
 
3893
3942
  <div class="space-y-2">
@@ -3900,18 +3949,18 @@ export const actions: Actions = {
3900
3949
  pattern="[0-9]*"
3901
3950
  maxlength={6}
3902
3951
  placeholder="000000"
3903
- bind:value={verifySuperForm.form.code}
3904
- aria-invalid={verifySuperForm.errors.code ? 'true' : undefined}
3905
- disabled={verifySuperForm.delayed}
3952
+ bind:value={$verifyForm.code}
3953
+ aria-invalid={$verifyErrors.code ? 'true' : undefined}
3954
+ disabled={$verifyDelayed}
3906
3955
  class="text-center text-2xl tracking-[0.5em] font-mono"
3907
3956
  />
3908
- {#if verifySuperForm.errors.code}
3909
- <p class="text-sm text-red-600">{verifySuperForm.errors.code[0]}</p>
3957
+ {#if $verifyErrors.code}
3958
+ <p class="text-sm text-red-600">{$verifyErrors.code[0]}</p>
3910
3959
  {/if}
3911
3960
  </div>
3912
3961
 
3913
- <Button type="submit" class="w-full" disabled={verifySuperForm.delayed}>
3914
- {verifySuperForm.delayed ? 'Verifying...' : 'Verify & Sign In'}
3962
+ <Button type="submit" class="w-full" disabled={$verifyDelayed}>
3963
+ {$verifyDelayed ? 'Verifying...' : 'Verify & Sign In'}
3915
3964
  </Button>
3916
3965
 
3917
3966
  <button
@@ -7249,15 +7298,115 @@ export const POST: RequestHandler = async ({ request }) => {
7249
7298
  return new Response(JSON.stringify({ error: err.message }), { status: 500 });
7250
7299
  }
7251
7300
  };
7252
- `}};var ls=class extends g{name="new";description="Create a new SvelteKit project with Svelar pre-configured";arguments=["name"];flags=[{name:"no-install",alias:"n",description:"Skip npm install",type:"boolean",default:!1},{name:"flat",description:"Use flat folder structure instead of DDD modules",type:"boolean",default:!1}];async handle(e,t){let{join:s,resolve:r}=await import("path"),{existsSync:i,mkdirSync:a,writeFileSync:n}=await import("fs"),{execSync:l}=await import("child_process"),c=e[0];c||(this.error("Please provide a project name: npx svelar new my-app"),process.exit(1));let m=r(process.cwd(),c);i(m)&&(this.error(`Directory "${c}" already exists.`),process.exit(1));let p=t.flat||!1,h=p?"flat":"DDD modular";this.log(""),this.log(` \x1B[1m\x1B[38;5;208m</> Svelar\x1B[0m \u2014 Creating new project (${h})
7253
- `);let u=(_,We)=>{let bs=p?Po(_):_,Je=p?Ro(We,_):We,Ve=s(m,bs);a(s(Ve,".."),{recursive:!0}),n(Ve,Je)};this.info("Creating project structure...");let b=p?["","src","src/lib","src/lib/models","src/lib/services","src/lib/controllers","src/lib/repositories","src/lib/dtos","src/lib/actions","src/lib/resources","src/lib/events","src/lib/listeners","src/lib/notifications","src/lib/schemas","src/lib/jobs","src/lib/scheduler","src/lib/middleware","src/lib/components","src/lib/stores","src/lib/plugins","src/lib/channels","src/lib/commands","src/lib/providers","src/lib/database/migrations","src/lib/database/seeders","src/routes","src/routes/api","static","storage/logs","storage/cache","storage/uploads","storage/sessions"]:["","src","src/lib","src/lib/modules/auth","src/lib/modules/posts","src/lib/modules/admin","src/lib/shared/jobs","src/lib/shared/scheduler","src/lib/shared/middleware","src/lib/shared/components","src/lib/shared/stores","src/lib/shared/plugins","src/lib/shared/channels","src/lib/shared/commands","src/lib/shared/providers","src/lib/database/migrations","src/lib/database/seeders","src/routes","src/routes/api","static","storage/logs","storage/cache","storage/uploads","storage/sessions"];for(let _ of b)a(s(m,_),{recursive:!0});this.info("Writing config files...");let{dirname:y}=await import("path"),{fileURLToPath:v}=await import("url"),x=s(y(y(y(v(import.meta.url)))),"package.json"),A=JSON.parse((await import("fs")).readFileSync(x,"utf-8")).version??"0.4.0";u("package.json",d.packageJson(c,A)),u("svelte.config.js",d.svelteConfig()),u("vite.config.ts",d.viteConfig()),u("tsconfig.json",d.tsConfig()),u("src/app.html",d.appHtml()),u("static/favicon.svg",d.faviconSvg()),u("src/app.css",d.appCss()),u("src/app.ts",d.appTs()),u("src/hooks.server.ts",d.hooksServerTs()),u(".env.example",d.envExample());let{randomBytes:I}=await import("crypto"),xe=I(32).toString("hex"),Se=I(16).toString("hex"),qr=d.envExample().replace("APP_KEY=change-me-to-a-random-string",`APP_KEY=${xe}`).replace("INTERNAL_SECRET=change-me-to-a-random-string",`INTERNAL_SECRET=${Se}`);u(".env",qr),u(".gitignore",d.gitignore()),u("svelar.database.json",d.svelarDatabaseJson());for(let _ of["storage/logs","storage/cache","storage/uploads","storage/sessions"])u(`${_}/.gitkeep`,"");if(this.info("Scaffolding domain layer..."),u("src/lib/modules/auth/User.ts",d.userModel()),u("src/lib/modules/auth/UserRepository.ts",d.userRepository()),u("src/lib/modules/auth/AuthService.ts",d.authService()),u("src/lib/modules/auth/AuthController.ts",d.authController()),u("src/lib/modules/auth/RegisterUserAction.ts",d.registerUserAction()),u("src/lib/modules/auth/RegisterRequest.ts",d.registerRequest()),u("src/lib/modules/auth/LoginRequest.ts",d.loginRequest()),u("src/lib/modules/auth/ForgotPasswordRequest.ts",d.forgotPasswordRequest()),u("src/lib/modules/auth/ResetPasswordRequest.ts",d.resetPasswordRequest()),u("src/lib/modules/auth/OtpSendRequest.ts",d.otpSendRequest()),u("src/lib/modules/auth/OtpVerifyRequest.ts",d.otpVerifyRequest()),u("src/lib/modules/auth/UserResource.ts",d.userResource()),u("src/lib/modules/auth/gates.ts",d.gates()),u("src/lib/modules/auth/schemas.ts",d.authSchema()),u("src/lib/modules/auth/UserRegistered.ts",d.userRegisteredEvent()),u("src/lib/modules/auth/SendWelcomeEmailListener.ts",d.sendWelcomeEmailListener()),u("src/lib/modules/auth/WelcomeNotification.ts",d.welcomeNotification()),u("src/lib/modules/posts/Post.ts",d.postModel()),u("src/lib/modules/posts/PostRepository.ts",d.postRepository()),u("src/lib/modules/posts/PostService.ts",d.postService()),u("src/lib/modules/posts/PostController.ts",d.postController()),u("src/lib/modules/posts/CreatePostAction.ts",d.createPostAction()),u("src/lib/modules/posts/CreatePostRequest.ts",d.createPostRequest()),u("src/lib/modules/posts/UpdatePostRequest.ts",d.updatePostRequest()),u("src/lib/modules/posts/PostResource.ts",d.postResource()),u("src/lib/modules/posts/schemas.ts",d.postSchema()),u("src/lib/modules/admin/AdminService.ts",d.adminService()),u("src/lib/modules/admin/AdminController.ts",d.adminController()),u("src/lib/modules/admin/UpdateUserRoleRequest.ts",d.updateUserRoleRequest()),u("src/lib/modules/admin/DeleteUserRequest.ts",d.deleteUserRequest()),u("src/lib/modules/admin/CreateRoleRequest.ts",d.createRoleRequest()),u("src/lib/modules/admin/DeleteRoleRequest.ts",d.deleteRoleRequest()),u("src/lib/modules/admin/CreatePermissionRequest.ts",d.createPermissionRequest()),u("src/lib/modules/admin/DeletePermissionRequest.ts",d.deletePermissionRequest()),u("src/lib/modules/admin/RolePermissionRequest.ts",d.rolePermissionRequest()),u("src/lib/modules/admin/UserRoleRequest.ts",d.userRoleRequest()),u("src/lib/modules/admin/UserPermissionRequest.ts",d.userPermissionRequest()),u("src/lib/modules/admin/ExportDataRequest.ts",d.exportDataRequest()),u("src/lib/modules/admin/RoleResource.ts",d.roleResource()),u("src/lib/modules/admin/PermissionResource.ts",d.permissionResource()),u("src/lib/modules/admin/schemas.ts",d.adminSchema()),u("src/lib/shared/providers/EventServiceProvider.ts",d.eventServiceProvider()),this.info("Creating migrations..."),u("src/lib/database/migrations/00000001_create_users_table.ts",d.createUsersTable()),u("src/lib/database/migrations/00000002_create_posts_table.ts",d.createPostsTable()),u("src/lib/database/migrations/00000003_create_permissions_tables.ts",d.createPermissionsTables()),u("src/lib/database/migrations/00000004_add_role_to_users.ts",d.addRoleToUsers()),u("src/lib/database/migrations/00000005_create_sessions_table.ts",d.createSessionsTable()),u("src/lib/database/migrations/00000006_create_audit_logs_table.ts",d.createAuditLogsTable()),u("src/lib/database/migrations/00000007_create_notifications_table.ts",d.createNotificationsTable()),u("src/lib/database/migrations/00000008_create_failed_jobs_table.ts",d.createFailedJobsTable()),u("src/lib/database/migrations/00000009_add_stripe_to_users.ts",d.addStripeToUsers()),u("src/lib/database/migrations/00000010_create_subscription_plans.ts",d.createSubscriptionPlansTable()),u("src/lib/database/migrations/00000011_create_subscriptions.ts",d.createSubscriptionsTable()),u("src/lib/database/migrations/00000012_create_invoices.ts",d.createInvoicesTable()),u("src/lib/database/seeders/DatabaseSeeder.ts",d.databaseSeeder()),this.info("Creating auth pages..."),u("src/routes/login/+page.server.ts",d.loginPageServer()),u("src/routes/login/+page.svelte",d.loginPageSvelte()),u("src/routes/register/+page.server.ts",d.registerPageServer()),u("src/routes/register/+page.svelte",d.registerPageSvelte()),u("src/routes/logout/+page.server.ts",d.logoutPageServer()),u("src/routes/forgot-password/+page.server.ts",d.forgotPasswordPageServer()),u("src/routes/forgot-password/+page.svelte",d.forgotPasswordPageSvelte()),u("src/routes/reset-password/+page.server.ts",d.resetPasswordPageServer()),u("src/routes/reset-password/+page.svelte",d.resetPasswordPageSvelte()),u("src/routes/otp-login/+page.server.ts",d.otpLoginPageServer()),u("src/routes/otp-login/+page.svelte",d.otpLoginPageSvelte()),u("src/routes/verify-email/+page.server.ts",d.verifyEmailPageServer()),u("src/routes/verify-email/+page.svelte",d.verifyEmailPageSvelte()),this.info("Creating dashboard..."),u("src/routes/dashboard/+layout.server.ts",d.dashboardLayoutServer()),u("src/routes/dashboard/+layout.svelte",d.dashboardLayoutSvelte()),u("src/routes/dashboard/+page.server.ts",d.dashboardPageServer()),u("src/routes/dashboard/+page.svelte",d.dashboardPageSvelte()),u("src/routes/dashboard/api-keys/+page.server.ts",d.apiKeysPageServer()),u("src/routes/dashboard/api-keys/+page.svelte",d.apiKeysPageSvelte()),u("src/routes/dashboard/team/+page.server.ts",d.teamPageServer()),u("src/routes/dashboard/team/+page.svelte",d.teamPageSvelte()),u("src/routes/dashboard/billing/+page.server.ts",d.billingPageServer()),u("src/routes/dashboard/billing/+page.svelte",d.billingPageSvelte()),this.info("Creating admin panel..."),u("src/routes/admin/+layout.server.ts",d.adminLayoutServer()),u("src/routes/admin/+layout.svelte",d.adminLayoutSvelte()),u("src/routes/admin/+page.server.ts",d.adminPageServer()),u("src/routes/admin/+page.svelte",d.adminPageSvelte()),this.info("Creating API routes..."),u("src/routes/api/health/+server.ts",d.apiHealth()),u("src/routes/api/auth/register/+server.ts",d.apiAuthRegister()),u("src/routes/api/auth/login/+server.ts",d.apiAuthLogin()),u("src/routes/api/auth/logout/+server.ts",d.apiAuthLogout()),u("src/routes/api/auth/me/+server.ts",d.apiAuthMe()),u("src/routes/api/auth/forgot-password/+server.ts",d.apiAuthForgotPassword()),u("src/routes/api/auth/reset-password/+server.ts",d.apiAuthResetPassword()),u("src/routes/api/auth/otp/send/+server.ts",d.apiAuthOtpSend()),u("src/routes/api/auth/otp/verify/+server.ts",d.apiAuthOtpVerify()),u("src/routes/api/auth/verify-email/+server.ts",d.apiAuthVerifyEmail()),u("src/routes/api/posts/+server.ts",d.apiPosts()),u("src/routes/api/posts/[id]/+server.ts",d.apiPostsSingle()),u("src/routes/api/posts/mine/+server.ts",d.apiPostsMine()),u("src/routes/api/broadcasting/[channel]/+server.ts",d.apiBroadcasting()),u("src/routes/api/internal/broadcast/+server.ts",d.apiInternalBroadcast()),u("src/routes/api/admin/users/+server.ts",d.apiAdminUsers()),u("src/routes/api/admin/roles/+server.ts",d.apiAdminRoles()),u("src/routes/api/admin/permissions/+server.ts",d.apiAdminPermissions()),u("src/routes/api/admin/role-permissions/+server.ts",d.apiAdminRolePermissions()),u("src/routes/api/admin/user-roles/+server.ts",d.apiAdminUserRoles()),u("src/routes/api/admin/user-permissions/+server.ts",d.apiAdminUserPermissions()),u("src/routes/api/admin/export/+server.ts",d.apiAdminExport()),u("src/routes/api/admin/health/+server.ts",d.apiAdminHealth()),u("src/routes/api/admin/queue/+server.ts",d.apiAdminQueue()),u("src/routes/api/admin/queue/[id]/retry/+server.ts",d.apiAdminQueueRetry()),u("src/routes/api/admin/queue/[id]/+server.ts",d.apiAdminQueueDelete()),u("src/routes/api/admin/scheduler/+server.ts",d.apiAdminScheduler()),u("src/routes/api/admin/scheduler/[name]/run/+server.ts",d.apiAdminSchedulerRun()),u("src/routes/api/admin/scheduler/[name]/toggle/+server.ts",d.apiAdminSchedulerToggle()),u("src/routes/api/admin/logs/+server.ts",d.apiAdminLogs()),u("src/routes/api/admin/stats/+server.ts",d.apiAdminStats()),u("src/routes/api/admin/billing/subscriptions/+server.ts",d.apiAdminBillingSubscriptions()),u("src/routes/api/admin/billing/refund/+server.ts",d.apiAdminBillingRefund()),u("src/routes/api/admin/billing/cancel/+server.ts",d.apiAdminBillingCancel()),u("src/routes/api/webhooks/stripe/+server.ts",d.stripeWebhookRoute()),this.info("Creating background jobs..."),u("src/lib/shared/jobs/SendWelcomeEmail.ts",d.sendWelcomeEmail()),u("src/lib/shared/jobs/DailyDigestJob.ts",d.dailyDigestJob()),u("src/lib/shared/jobs/ExportDataJob.ts",d.exportDataJob()),this.info("Creating scheduled tasks..."),u("src/lib/shared/scheduler/CleanupExpiredTokens.ts",d.cleanupExpiredTokens()),u("src/lib/shared/scheduler/CleanExpiredSessions.ts",d.cleanExpiredSessions()),u("src/lib/shared/scheduler/DailyDigestEmail.ts",d.dailyDigestEmail()),u("src/lib/shared/scheduler/PruneAuditLogs.ts",d.pruneAuditLogs()),u("src/lib/shared/scheduler/QueueHealthCheck.ts",d.queueHealthCheck()),this.info("Creating layouts..."),u("src/routes/+layout.svelte",d.rootLayoutSvelte(c)),u("src/routes/+layout.server.ts",d.rootLayoutServer()),u("src/routes/+error.svelte",d.errorSvelte()),u("src/routes/+page.svelte",d.homePage(c)),this.success(`Project structure created (${h})`),!t["no-install"]){this.info("Installing dependencies...");try{l("npm install",{cwd:m,stdio:"inherit"}),this.success("Dependencies installed")}catch{this.warn("npm install failed \u2014 run it manually with: cd "+c+" && npm install")}this.info("Running migrations...");try{l("npx svelar migrate",{cwd:m,stdio:"inherit"}),this.success("Migrations complete")}catch{this.warn("Migrations failed \u2014 run manually: cd "+c+" && npx svelar migrate")}this.info("Seeding database...");try{l("npx svelar seed:run",{cwd:m,stdio:"inherit"}),this.success("Database seeded")}catch{this.warn("Seeding failed \u2014 run manually: cd "+c+" && npx svelar seed:run")}}this.log(""),this.log(` \x1B[32m+\x1B[0m Project \x1B[1m${c}\x1B[0m created successfully!
7301
+ `}static vitestConfig(){return`import { defineConfig } from 'vitest/config';
7302
+ import { createRequire } from 'module';
7303
+ import { dirname, resolve } from 'path';
7304
+
7305
+ const require_ = createRequire(import.meta.url);
7306
+ const svelarRoot = dirname(require_.resolve('@beeblock/svelar/package.json'));
7307
+
7308
+ export default defineConfig({
7309
+ test: {
7310
+ globals: true,
7311
+ include: ['tests/unit/**/*.test.ts', 'tests/feature/**/*.test.ts'],
7312
+ exclude: ['tests/e2e/**'],
7313
+ alias: {
7314
+ '$lib': resolve('./src/lib'),
7315
+ '$lib/*': resolve('./src/lib/*'),
7316
+ '@beeblock/svelar/testing': resolve(svelarRoot, 'dist/testing/index.js'),
7317
+ '@beeblock/svelar/orm': resolve(svelarRoot, 'dist/orm/index.js'),
7318
+ '@beeblock/svelar/database': resolve(svelarRoot, 'dist/database/index.js'),
7319
+ '@beeblock/svelar/auth': resolve(svelarRoot, 'dist/auth/index.js'),
7320
+ '@beeblock/svelar/validation': resolve(svelarRoot, 'dist/validation/index.js'),
7321
+ '@beeblock/svelar/hashing': resolve(svelarRoot, 'dist/hashing/index.js'),
7322
+ '@beeblock/svelar/session': resolve(svelarRoot, 'dist/session/index.js'),
7323
+ '@beeblock/svelar/events': resolve(svelarRoot, 'dist/events/index.js'),
7324
+ '@beeblock/svelar/queue': resolve(svelarRoot, 'dist/queue/index.js'),
7325
+ '@beeblock/svelar/cache': resolve(svelarRoot, 'dist/cache/index.js'),
7326
+ '@beeblock/svelar/mail': resolve(svelarRoot, 'dist/mail/index.js'),
7327
+ '@beeblock/svelar': resolve(svelarRoot, 'dist/index.js'),
7328
+ },
7329
+ },
7330
+ });
7331
+ `}static playwrightConfig(){return`import { defineConfig } from '@playwright/test';
7332
+
7333
+ export default defineConfig({
7334
+ testDir: 'tests/e2e',
7335
+ testMatch: '**/*.spec.ts',
7336
+ fullyParallel: true,
7337
+ forbidOnly: !!process.env.CI,
7338
+ retries: process.env.CI ? 2 : 0,
7339
+ workers: process.env.CI ? 1 : undefined,
7340
+ use: {
7341
+ baseURL: 'http://localhost:5173',
7342
+ trace: 'on-first-retry',
7343
+ },
7344
+ webServer: {
7345
+ command: 'npm run dev',
7346
+ url: 'http://localhost:5173',
7347
+ reuseExistingServer: !process.env.CI,
7348
+ },
7349
+ });
7350
+ `}static exampleUnitTest(){return`import { describe, it, expect } from 'vitest';
7351
+
7352
+ describe('Example Unit Test', () => {
7353
+ it('should pass a basic assertion', () => {
7354
+ expect(1 + 1).toBe(2);
7355
+ });
7356
+
7357
+ it('should handle string operations', () => {
7358
+ const greeting = 'Hello, Svelar!';
7359
+ expect(greeting).toContain('Svelar');
7360
+ });
7361
+ });
7362
+ `}static exampleFeatureTest(){return`import { describe, it, expect } from 'vitest';
7363
+ import { useSvelarTest, assertDatabaseHas } from '@beeblock/svelar/testing';
7364
+ // import UserFactory from '$lib/factories/UserFactory';
7365
+
7366
+ describe('Auth Feature Test', () => {
7367
+ useSvelarTest({ refreshDatabase: true });
7368
+
7369
+ it('should set up the test database', async () => {
7370
+ // The database is automatically refreshed before each test
7371
+ // when refreshDatabase: true is set in useSvelarTest().
7372
+ expect(true).toBe(true);
7373
+ });
7374
+
7375
+ // Uncomment once you have a UserFactory:
7376
+ // it('should create a user via factory', async () => {
7377
+ // const user = await UserFactory.create({ name: 'Alice' });
7378
+ // await assertDatabaseHas('users', { name: 'Alice' });
7379
+ // });
7380
+ });
7381
+ `}static scaffoldUserFactory(){return`import { Factory } from '@beeblock/svelar/testing';
7382
+ import { User } from '$lib/modules/auth/User';
7383
+
7384
+ export class UserFactory extends Factory<User> {
7385
+ model() {
7386
+ return User;
7387
+ }
7388
+
7389
+ definition() {
7390
+ return {
7391
+ name: \`User \${this.sequence}\`,
7392
+ email: \`user\${this.sequence}@test.com\`,
7393
+ password_hash: 'hashed',
7394
+ role: 'user',
7395
+ };
7396
+ }
7397
+ }
7398
+
7399
+ // Singleton instance for convenience
7400
+ export default new UserFactory();
7401
+ `}};var ds=class extends g{name="new";description="Create a new SvelteKit project with Svelar pre-configured";arguments=["name"];flags=[{name:"no-install",alias:"n",description:"Skip npm install",type:"boolean",default:!1},{name:"flat",description:"Use flat folder structure instead of DDD modules",type:"boolean",default:!1}];async handle(e,t){let{join:s,resolve:r}=await import("path"),{existsSync:i,mkdirSync:a,writeFileSync:n}=await import("fs"),{execSync:l}=await import("child_process"),c=e[0];c||(this.error("Please provide a project name: npx svelar new my-app"),process.exit(1));let m=r(process.cwd(),c);i(m)&&(this.error(`Directory "${c}" already exists.`),process.exit(1));let p=t.flat||!1,h=p?"flat":"DDD modular";this.log(""),this.log(` \x1B[1m\x1B[38;5;208m</> Svelar\x1B[0m \u2014 Creating new project (${h})
7402
+ `);let u=(_,We)=>{let vs=p?jo(_):_,Je=p?Oo(We,_):We,Ve=s(m,vs);a(s(Ve,".."),{recursive:!0}),n(Ve,Je)};this.info("Creating project structure...");let b=p?["","src","src/lib","src/lib/models","src/lib/services","src/lib/controllers","src/lib/repositories","src/lib/dtos","src/lib/actions","src/lib/resources","src/lib/events","src/lib/listeners","src/lib/notifications","src/lib/schemas","src/lib/jobs","src/lib/scheduler","src/lib/middleware","src/lib/components","src/lib/stores","src/lib/plugins","src/lib/channels","src/lib/commands","src/lib/providers","src/lib/database/migrations","src/lib/database/seeders","src/routes","src/routes/api","static","storage/logs","storage/cache","storage/uploads","storage/sessions","tests/unit","tests/feature","tests/e2e","src/lib/factories"]:["","src","src/lib","src/lib/modules/auth","src/lib/modules/posts","src/lib/modules/admin","src/lib/shared/jobs","src/lib/shared/scheduler","src/lib/shared/middleware","src/lib/shared/components","src/lib/shared/stores","src/lib/shared/plugins","src/lib/shared/channels","src/lib/shared/commands","src/lib/shared/providers","src/lib/database/migrations","src/lib/database/seeders","src/routes","src/routes/api","static","storage/logs","storage/cache","storage/uploads","storage/sessions","tests/unit","tests/feature","tests/e2e","src/lib/factories"];for(let _ of b)a(s(m,_),{recursive:!0});this.info("Writing config files...");let{dirname:y}=await import("path"),{fileURLToPath:v}=await import("url"),x=s(y(y(y(v(import.meta.url)))),"package.json"),A=JSON.parse((await import("fs")).readFileSync(x,"utf-8")).version??"0.4.0";u("package.json",d.packageJson(c,A)),u("svelte.config.js",d.svelteConfig()),u("vite.config.ts",d.viteConfig()),u("tsconfig.json",d.tsConfig()),u("src/app.html",d.appHtml()),u("static/favicon.svg",d.faviconSvg()),u("src/app.css",d.appCss()),u("src/app.ts",d.appTs()),u("src/hooks.server.ts",d.hooksServerTs()),u(".env.example",d.envExample());let{randomBytes:I}=await import("crypto"),xe=I(32).toString("hex"),Pe=I(16).toString("hex"),Fr=d.envExample().replace("APP_KEY=change-me-to-a-random-string",`APP_KEY=${xe}`).replace("INTERNAL_SECRET=change-me-to-a-random-string",`INTERNAL_SECRET=${Pe}`);u(".env",Fr),u(".gitignore",d.gitignore()),u("svelar.database.json",d.svelarDatabaseJson());for(let _ of["storage/logs","storage/cache","storage/uploads","storage/sessions"])u(`${_}/.gitkeep`,"");if(this.info("Scaffolding domain layer..."),u("src/lib/modules/auth/User.ts",d.userModel()),u("src/lib/modules/auth/UserRepository.ts",d.userRepository()),u("src/lib/modules/auth/AuthService.ts",d.authService()),u("src/lib/modules/auth/AuthController.ts",d.authController()),u("src/lib/modules/auth/RegisterUserAction.ts",d.registerUserAction()),u("src/lib/modules/auth/RegisterRequest.ts",d.registerRequest()),u("src/lib/modules/auth/LoginRequest.ts",d.loginRequest()),u("src/lib/modules/auth/ForgotPasswordRequest.ts",d.forgotPasswordRequest()),u("src/lib/modules/auth/ResetPasswordRequest.ts",d.resetPasswordRequest()),u("src/lib/modules/auth/OtpSendRequest.ts",d.otpSendRequest()),u("src/lib/modules/auth/OtpVerifyRequest.ts",d.otpVerifyRequest()),u("src/lib/modules/auth/UserResource.ts",d.userResource()),u("src/lib/modules/auth/gates.ts",d.gates()),u("src/lib/modules/auth/schemas.ts",d.authSchema()),u("src/lib/modules/auth/UserRegistered.ts",d.userRegisteredEvent()),u("src/lib/modules/auth/SendWelcomeEmailListener.ts",d.sendWelcomeEmailListener()),u("src/lib/modules/auth/WelcomeNotification.ts",d.welcomeNotification()),u("src/lib/modules/posts/Post.ts",d.postModel()),u("src/lib/modules/posts/PostRepository.ts",d.postRepository()),u("src/lib/modules/posts/PostService.ts",d.postService()),u("src/lib/modules/posts/PostController.ts",d.postController()),u("src/lib/modules/posts/CreatePostAction.ts",d.createPostAction()),u("src/lib/modules/posts/CreatePostRequest.ts",d.createPostRequest()),u("src/lib/modules/posts/UpdatePostRequest.ts",d.updatePostRequest()),u("src/lib/modules/posts/PostResource.ts",d.postResource()),u("src/lib/modules/posts/schemas.ts",d.postSchema()),u("src/lib/modules/admin/AdminService.ts",d.adminService()),u("src/lib/modules/admin/AdminController.ts",d.adminController()),u("src/lib/modules/admin/UpdateUserRoleRequest.ts",d.updateUserRoleRequest()),u("src/lib/modules/admin/DeleteUserRequest.ts",d.deleteUserRequest()),u("src/lib/modules/admin/CreateRoleRequest.ts",d.createRoleRequest()),u("src/lib/modules/admin/DeleteRoleRequest.ts",d.deleteRoleRequest()),u("src/lib/modules/admin/CreatePermissionRequest.ts",d.createPermissionRequest()),u("src/lib/modules/admin/DeletePermissionRequest.ts",d.deletePermissionRequest()),u("src/lib/modules/admin/RolePermissionRequest.ts",d.rolePermissionRequest()),u("src/lib/modules/admin/UserRoleRequest.ts",d.userRoleRequest()),u("src/lib/modules/admin/UserPermissionRequest.ts",d.userPermissionRequest()),u("src/lib/modules/admin/ExportDataRequest.ts",d.exportDataRequest()),u("src/lib/modules/admin/RoleResource.ts",d.roleResource()),u("src/lib/modules/admin/PermissionResource.ts",d.permissionResource()),u("src/lib/modules/admin/schemas.ts",d.adminSchema()),u("src/lib/shared/providers/EventServiceProvider.ts",d.eventServiceProvider()),this.info("Creating migrations..."),u("src/lib/database/migrations/00000001_create_users_table.ts",d.createUsersTable()),u("src/lib/database/migrations/00000002_create_posts_table.ts",d.createPostsTable()),u("src/lib/database/migrations/00000003_create_permissions_tables.ts",d.createPermissionsTables()),u("src/lib/database/migrations/00000004_add_role_to_users.ts",d.addRoleToUsers()),u("src/lib/database/migrations/00000005_create_sessions_table.ts",d.createSessionsTable()),u("src/lib/database/migrations/00000006_create_audit_logs_table.ts",d.createAuditLogsTable()),u("src/lib/database/migrations/00000007_create_notifications_table.ts",d.createNotificationsTable()),u("src/lib/database/migrations/00000008_create_failed_jobs_table.ts",d.createFailedJobsTable()),u("src/lib/database/migrations/00000009_add_stripe_to_users.ts",d.addStripeToUsers()),u("src/lib/database/migrations/00000010_create_subscription_plans.ts",d.createSubscriptionPlansTable()),u("src/lib/database/migrations/00000011_create_subscriptions.ts",d.createSubscriptionsTable()),u("src/lib/database/migrations/00000012_create_invoices.ts",d.createInvoicesTable()),u("src/lib/database/seeders/DatabaseSeeder.ts",d.databaseSeeder()),this.info("Creating auth pages..."),u("src/routes/login/+page.server.ts",d.loginPageServer()),u("src/routes/login/+page.svelte",d.loginPageSvelte()),u("src/routes/register/+page.server.ts",d.registerPageServer()),u("src/routes/register/+page.svelte",d.registerPageSvelte()),u("src/routes/logout/+page.server.ts",d.logoutPageServer()),u("src/routes/forgot-password/+page.server.ts",d.forgotPasswordPageServer()),u("src/routes/forgot-password/+page.svelte",d.forgotPasswordPageSvelte()),u("src/routes/reset-password/+page.server.ts",d.resetPasswordPageServer()),u("src/routes/reset-password/+page.svelte",d.resetPasswordPageSvelte()),u("src/routes/otp-login/+page.server.ts",d.otpLoginPageServer()),u("src/routes/otp-login/+page.svelte",d.otpLoginPageSvelte()),u("src/routes/verify-email/+page.server.ts",d.verifyEmailPageServer()),u("src/routes/verify-email/+page.svelte",d.verifyEmailPageSvelte()),this.info("Creating dashboard..."),u("src/routes/dashboard/+layout.server.ts",d.dashboardLayoutServer()),u("src/routes/dashboard/+layout.svelte",d.dashboardLayoutSvelte()),u("src/routes/dashboard/+page.server.ts",d.dashboardPageServer()),u("src/routes/dashboard/+page.svelte",d.dashboardPageSvelte()),u("src/routes/dashboard/api-keys/+page.server.ts",d.apiKeysPageServer()),u("src/routes/dashboard/api-keys/+page.svelte",d.apiKeysPageSvelte()),u("src/routes/dashboard/team/+page.server.ts",d.teamPageServer()),u("src/routes/dashboard/team/+page.svelte",d.teamPageSvelte()),u("src/routes/dashboard/billing/+page.server.ts",d.billingPageServer()),u("src/routes/dashboard/billing/+page.svelte",d.billingPageSvelte()),this.info("Creating admin panel..."),u("src/routes/admin/+layout.server.ts",d.adminLayoutServer()),u("src/routes/admin/+layout.svelte",d.adminLayoutSvelte()),u("src/routes/admin/+page.server.ts",d.adminPageServer()),u("src/routes/admin/+page.svelte",d.adminPageSvelte()),this.info("Creating API routes..."),u("src/routes/api/health/+server.ts",d.apiHealth()),u("src/routes/api/auth/register/+server.ts",d.apiAuthRegister()),u("src/routes/api/auth/login/+server.ts",d.apiAuthLogin()),u("src/routes/api/auth/logout/+server.ts",d.apiAuthLogout()),u("src/routes/api/auth/me/+server.ts",d.apiAuthMe()),u("src/routes/api/auth/forgot-password/+server.ts",d.apiAuthForgotPassword()),u("src/routes/api/auth/reset-password/+server.ts",d.apiAuthResetPassword()),u("src/routes/api/auth/otp/send/+server.ts",d.apiAuthOtpSend()),u("src/routes/api/auth/otp/verify/+server.ts",d.apiAuthOtpVerify()),u("src/routes/api/auth/verify-email/+server.ts",d.apiAuthVerifyEmail()),u("src/routes/api/posts/+server.ts",d.apiPosts()),u("src/routes/api/posts/[id]/+server.ts",d.apiPostsSingle()),u("src/routes/api/posts/mine/+server.ts",d.apiPostsMine()),u("src/routes/api/broadcasting/[channel]/+server.ts",d.apiBroadcasting()),u("src/routes/api/internal/broadcast/+server.ts",d.apiInternalBroadcast()),u("src/routes/api/admin/users/+server.ts",d.apiAdminUsers()),u("src/routes/api/admin/roles/+server.ts",d.apiAdminRoles()),u("src/routes/api/admin/permissions/+server.ts",d.apiAdminPermissions()),u("src/routes/api/admin/role-permissions/+server.ts",d.apiAdminRolePermissions()),u("src/routes/api/admin/user-roles/+server.ts",d.apiAdminUserRoles()),u("src/routes/api/admin/user-permissions/+server.ts",d.apiAdminUserPermissions()),u("src/routes/api/admin/export/+server.ts",d.apiAdminExport()),u("src/routes/api/admin/health/+server.ts",d.apiAdminHealth()),u("src/routes/api/admin/queue/+server.ts",d.apiAdminQueue()),u("src/routes/api/admin/queue/[id]/retry/+server.ts",d.apiAdminQueueRetry()),u("src/routes/api/admin/queue/[id]/+server.ts",d.apiAdminQueueDelete()),u("src/routes/api/admin/scheduler/+server.ts",d.apiAdminScheduler()),u("src/routes/api/admin/scheduler/[name]/run/+server.ts",d.apiAdminSchedulerRun()),u("src/routes/api/admin/scheduler/[name]/toggle/+server.ts",d.apiAdminSchedulerToggle()),u("src/routes/api/admin/logs/+server.ts",d.apiAdminLogs()),u("src/routes/api/admin/stats/+server.ts",d.apiAdminStats()),u("src/routes/api/admin/billing/subscriptions/+server.ts",d.apiAdminBillingSubscriptions()),u("src/routes/api/admin/billing/refund/+server.ts",d.apiAdminBillingRefund()),u("src/routes/api/admin/billing/cancel/+server.ts",d.apiAdminBillingCancel()),u("src/routes/api/webhooks/stripe/+server.ts",d.stripeWebhookRoute()),this.info("Creating background jobs..."),u("src/lib/shared/jobs/SendWelcomeEmail.ts",d.sendWelcomeEmail()),u("src/lib/shared/jobs/DailyDigestJob.ts",d.dailyDigestJob()),u("src/lib/shared/jobs/ExportDataJob.ts",d.exportDataJob()),this.info("Creating scheduled tasks..."),u("src/lib/shared/scheduler/CleanupExpiredTokens.ts",d.cleanupExpiredTokens()),u("src/lib/shared/scheduler/CleanExpiredSessions.ts",d.cleanExpiredSessions()),u("src/lib/shared/scheduler/DailyDigestEmail.ts",d.dailyDigestEmail()),u("src/lib/shared/scheduler/PruneAuditLogs.ts",d.pruneAuditLogs()),u("src/lib/shared/scheduler/QueueHealthCheck.ts",d.queueHealthCheck()),this.info("Creating layouts..."),u("src/routes/+layout.svelte",d.rootLayoutSvelte(c)),u("src/routes/+layout.server.ts",d.rootLayoutServer()),u("src/routes/+error.svelte",d.errorSvelte()),u("src/routes/+page.svelte",d.homePage(c)),this.info("Setting up testing..."),u("vitest.config.ts",d.vitestConfig()),u("playwright.config.ts",d.playwrightConfig()),u("tests/unit/example.test.ts",d.exampleUnitTest()),u("tests/feature/auth.test.ts",d.exampleFeatureTest()),u("src/lib/factories/UserFactory.ts",d.scaffoldUserFactory()),this.success(`Project structure created (${h})`),!t["no-install"]){this.info("Installing dependencies...");try{l("npm install",{cwd:m,stdio:"inherit"}),this.success("Dependencies installed")}catch{this.warn("npm install failed \u2014 run it manually with: cd "+c+" && npm install")}this.info("Running migrations...");try{l("npx svelar migrate",{cwd:m,stdio:"inherit"}),this.success("Migrations complete")}catch{this.warn("Migrations failed \u2014 run manually: cd "+c+" && npx svelar migrate")}this.info("Seeding database...");try{l("npx svelar seed:run",{cwd:m,stdio:"inherit"}),this.success("Database seeded")}catch{this.warn("Seeding failed \u2014 run manually: cd "+c+" && npx svelar seed:run")}}this.log(""),this.log(` \x1B[32m+\x1B[0m Project \x1B[1m${c}\x1B[0m created successfully!
7254
7403
  `),this.log(` Next steps:
7255
- `),this.log(` cd ${c}`),t["no-install"]&&(this.log(" npm install"),this.log(" npx svelar migrate"),this.log(" npx svelar seed:run")),this.log(" npm run dev"),this.log(""),this.log(" Default accounts:"),this.log(" Admin: admin@svelar.dev / admin123"),this.log(" Demo: demo@svelar.dev / password"),this.log("")}};function So(o){return/Service\./.test(o)?"services":/Controller\./.test(o)?"controllers":/Repository\./.test(o)?"repositories":/Request\./.test(o)?"dtos":/Resource\./.test(o)?"resources":/Action\./.test(o)?"actions":/Listener\./.test(o)?"listeners":/Notification\./.test(o)?"notifications":/Registered|Created|Updated|Deleted|Verified|Invited/.test(o)?"events":"models"}function Po(o){let e=o.match(/^src\/lib\/modules\/(\w+)\/(.+)$/);if(e){let[,s,r]=e;return r==="schemas.ts"?`src/lib/schemas/${s}.ts`:r==="gates.ts"?"src/lib/gates.ts":`src/lib/${So(r)}/${r}`}let t=o.match(/^src\/lib\/shared\/(.+)$/);return t?`src/lib/${t[1]}`:o}function Dr(o,e,t){return e==="schemas"?`$lib/schemas/${o}${t}`:e==="gates"?`$lib/gates${t}`:`$lib/${ta(e)}/${e}${t}`}function ta(o){return/Service$/.test(o)?"services":/Controller$/.test(o)?"controllers":/Repository$/.test(o)?"repositories":/Request$/.test(o)?"dtos":/Resource$/.test(o)?"resources":/Action$/.test(o)?"actions":/Listener$/.test(o)?"listeners":/Notification$/.test(o)?"notifications":/Registered|Created|Updated|Deleted|Verified|Invited/.test(o)?"events":"models"}function Ro(o,e){let s=e.match(/modules\/(\w+)\//)?.[1]||"";return o=o.replace(/\$lib\/modules\/(\w+)\/(\w+)(\.js)?/g,(r,i,a,n)=>Dr(i,a,n||"")),o=o.replace(/\.\/lib\/modules\/(\w+)\/(\w+)(\.js)?/g,(r,i,a,n)=>a==="schemas"?`./lib/schemas/${i}${n||""}`:a==="gates"?`./lib/gates${n||""}`:`./lib/${ta(a)}/${a}${n||""}`),o=o.replace(/\$lib\/shared\//g,"$lib/"),o=o.replace(/\.\/lib\/shared\//g,"./lib/"),e.includes("shared/")&&(o=o.replace(/'\.\.\/(\.\.\/\.\.\/)'/g,"'$1'"),o=o.replace(/'\.\.\/\.\.\/\.\.\//g,"'../../")),s&&(o=o.replace(/from '\.\/(\w+)(\.js)?'/g,(r,i,a)=>i.startsWith("$")||i==="app"?r:(a=a||"",`from '${Dr(s,i,a)}'`)),o=o.replace(/import '\.\/(\w+)(\.js)?'/g,(r,i,a)=>i.startsWith("$")||i==="app"?r:(a=a||"",`import '${Dr(s,i,a)}'`))),o}import{existsSync as sa,readFileSync as Ce,writeFileSync as cs,mkdirSync as To}from"fs";import{join as D,dirname as ko}from"path";import{createInterface as Eo}from"readline";function Ke(o){let e=Eo({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,s=>{e.close(),t(s.trim().toLowerCase())})})}var ds=class extends g{name="update";description="Update scaffold files from the latest svelar templates without overwriting customizations";flags=[{name:"force",alias:"f",description:"Overwrite all files without prompting",type:"boolean",default:!1},{name:"dry-run",alias:"d",description:"Show what would be updated without writing",type:"boolean",default:!1},{name:"category",alias:"c",description:"Only update a specific category (config, migration, route, page, domain, job, seeder)",type:"string",default:""},{name:"list",alias:"l",description:"List all updatable files and their status",type:"boolean",default:!1}];async handle(e,t){let s=process.cwd(),r=t.force??!1,i=t["dry-run"]??!1,a=t.category??"",n=t.list??!1,l=sa(D(s,"src","lib","modules")),c="app";try{c=JSON.parse(Ce(D(s,"package.json"),"utf-8")).name??"app"}catch{}this.log(""),this.info("Svelar Update \u2014 scanning project files..."),this.log("");let m=this.getFileManifest(l,c),p=a?m.filter(v=>v.category===a):m;if(p.length===0){this.warn(`No files found for category "${a}". Valid categories: config, migration, route, page, domain, job, seeder`);return}let h=[],u=[],b=[],y=[];for(let v of p){let x=D(s,v.path);if(!sa(x)){y.push(v);continue}let k=Ce(x,"utf-8"),A;try{A=v.content()}catch{continue}this.normalize(k)===this.normalize(A)?b.push(v):u.push(v)}if(n){this.printStatus(y,u,b);return}if(this.log(` Files scanned: ${p.length}`),this.log(` Up to date: \x1B[32m${b.length}\x1B[0m`),this.log(` Changed/outdated: \x1B[33m${u.length}\x1B[0m`),this.log(` Missing (new): \x1B[36m${y.length}\x1B[0m`),this.log(""),u.length===0&&y.length===0){this.success("All scaffold files are up to date!");return}if(y.length>0){this.info(`New files available (${y.length}):`);for(let v of y)this.log(` \x1B[36m+\x1B[0m ${v.path} \x1B[90m(${v.description})\x1B[0m`);if(this.log(""),!i){let v=r?"y":await Ke(" Create all new files? [Y/n/s(elect)] ");if(v==="y"||v==="yes"||v==="")for(let x of y)this.writeFile(D(s,x.path),x.content()),this.success(`Created ${x.path}`);else if(v==="s"||v==="select")for(let x of y){let k=await Ke(` Create ${x.path}? [y/N] `);k==="y"||k==="yes"?(this.writeFile(D(s,x.path),x.content()),this.success(`Created ${x.path}`)):this.log(` \x1B[90mSkipped ${x.path}\x1B[0m`)}else this.log(" Skipped new files.");this.log("")}}if(u.length>0){this.info(`Changed files (${u.length}):`);for(let v of u)this.log(` \x1B[33m~\x1B[0m ${v.path} \x1B[90m(${v.description})\x1B[0m`);if(this.log(""),i){this.info("Dry run \u2014 no files were modified.");return}if(r)for(let v of u)this.writeFile(D(s,v.path),v.content()),this.success(`Updated ${v.path}`);else{let v=await Ke(" Update changed files? [s(elect)/a(ll)/N] ");if(v==="a"||v==="all")for(let x of u){let k=D(s,x.path),A=k+".bak",I=Ce(k,"utf-8");cs(A,I),this.writeFile(k,x.content()),this.success(`Updated ${x.path} \x1B[90m(backup: ${x.path}.bak)\x1B[0m`)}else if(v==="s"||v==="select")for(let x of u){let k=await Ke(` Update ${x.path}? [y/N/d(iff)] `);if(k==="d"||k==="diff"){this.showDiff(D(s,x.path),x.content());let A=await Ke(" Apply this update? [y/N] ");if(A==="y"||A==="yes"){let I=Ce(D(s,x.path),"utf-8");cs(D(s,x.path)+".bak",I),this.writeFile(D(s,x.path),x.content()),this.success(`Updated ${x.path}`)}else this.log(` \x1B[90mSkipped ${x.path}\x1B[0m`)}else if(k==="y"||k==="yes"){let A=Ce(D(s,x.path),"utf-8");cs(D(s,x.path)+".bak",A),this.writeFile(D(s,x.path),x.content()),this.success(`Updated ${x.path} \x1B[90m(backup: ${x.path}.bak)\x1B[0m`)}else this.log(` \x1B[90mSkipped ${x.path}\x1B[0m`)}else this.log(" No files updated.")}}this.log(""),this.success("Update complete.")}normalize(e){return e.replace(/\r\n/g,`
7256
- `).trim()}writeFile(e,t){To(ko(e),{recursive:!0}),cs(e,t)}showDiff(e,t){let s=Ce(e,"utf-8").split(`
7404
+ `),this.log(` cd ${c}`),t["no-install"]&&(this.log(" npm install"),this.log(" npx svelar migrate"),this.log(" npx svelar seed:run")),this.log(" npm run dev"),this.log(""),this.log(" Default accounts:"),this.log(" Admin: admin@svelar.dev / admin123"),this.log(" Demo: demo@svelar.dev / password"),this.log("")}};function Io(o){return/Service\./.test(o)?"services":/Controller\./.test(o)?"controllers":/Repository\./.test(o)?"repositories":/Request\./.test(o)?"dtos":/Resource\./.test(o)?"resources":/Action\./.test(o)?"actions":/Listener\./.test(o)?"listeners":/Notification\./.test(o)?"notifications":/Registered|Created|Updated|Deleted|Verified|Invited/.test(o)?"events":"models"}function jo(o){let e=o.match(/^src\/lib\/modules\/(\w+)\/(.+)$/);if(e){let[,s,r]=e;return r==="schemas.ts"?`src/lib/schemas/${s}.ts`:r==="gates.ts"?"src/lib/gates.ts":`src/lib/${Io(r)}/${r}`}let t=o.match(/^src\/lib\/shared\/(.+)$/);return t?`src/lib/${t[1]}`:o}function _r(o,e,t){return e==="schemas"?`$lib/schemas/${o}${t}`:e==="gates"?`$lib/gates${t}`:`$lib/${aa(e)}/${e}${t}`}function aa(o){return/Service$/.test(o)?"services":/Controller$/.test(o)?"controllers":/Repository$/.test(o)?"repositories":/Request$/.test(o)?"dtos":/Resource$/.test(o)?"resources":/Action$/.test(o)?"actions":/Listener$/.test(o)?"listeners":/Notification$/.test(o)?"notifications":/Registered|Created|Updated|Deleted|Verified|Invited/.test(o)?"events":"models"}function Oo(o,e){let s=e.match(/modules\/(\w+)\//)?.[1]||"";return o=o.replace(/\$lib\/modules\/(\w+)\/(\w+)(\.js)?/g,(r,i,a,n)=>_r(i,a,n||"")),o=o.replace(/\.\/lib\/modules\/(\w+)\/(\w+)(\.js)?/g,(r,i,a,n)=>a==="schemas"?`./lib/schemas/${i}${n||""}`:a==="gates"?`./lib/gates${n||""}`:`./lib/${aa(a)}/${a}${n||""}`),o=o.replace(/\$lib\/shared\//g,"$lib/"),o=o.replace(/\.\/lib\/shared\//g,"./lib/"),e.includes("shared/")&&(o=o.replace(/'\.\.\/(\.\.\/\.\.\/)'/g,"'$1'"),o=o.replace(/'\.\.\/\.\.\/\.\.\//g,"'../../")),s&&(o=o.replace(/from '\.\/(\w+)(\.js)?'/g,(r,i,a)=>i.startsWith("$")||i==="app"?r:(a=a||"",`from '${_r(s,i,a)}'`)),o=o.replace(/import '\.\/(\w+)(\.js)?'/g,(r,i,a)=>i.startsWith("$")||i==="app"?r:(a=a||"",`import '${_r(s,i,a)}'`))),o}import{existsSync as na,readFileSync as Ce,writeFileSync as us,mkdirSync as qo}from"fs";import{join as D,dirname as Uo}from"path";import{createInterface as Fo}from"readline";function Ke(o){let e=Fo({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(o,s=>{e.close(),t(s.trim().toLowerCase())})})}var ms=class extends g{name="update";description="Update scaffold files from the latest svelar templates without overwriting customizations";flags=[{name:"force",alias:"f",description:"Overwrite all files without prompting",type:"boolean",default:!1},{name:"dry-run",alias:"d",description:"Show what would be updated without writing",type:"boolean",default:!1},{name:"category",alias:"c",description:"Only update a specific category (config, migration, route, page, domain, job, seeder)",type:"string",default:""},{name:"list",alias:"l",description:"List all updatable files and their status",type:"boolean",default:!1}];async handle(e,t){let s=process.cwd(),r=t.force??!1,i=t["dry-run"]??!1,a=t.category??"",n=t.list??!1,l=na(D(s,"src","lib","modules")),c="app";try{c=JSON.parse(Ce(D(s,"package.json"),"utf-8")).name??"app"}catch{}this.log(""),this.info("Svelar Update \u2014 scanning project files..."),this.log("");let m=this.getFileManifest(l,c),p=a?m.filter(v=>v.category===a):m;if(p.length===0){this.warn(`No files found for category "${a}". Valid categories: config, migration, route, page, domain, job, seeder`);return}let h=[],u=[],b=[],y=[];for(let v of p){let x=D(s,v.path);if(!na(x)){y.push(v);continue}let k=Ce(x,"utf-8"),A;try{A=v.content()}catch{continue}this.normalize(k)===this.normalize(A)?b.push(v):u.push(v)}if(n){this.printStatus(y,u,b);return}if(this.log(` Files scanned: ${p.length}`),this.log(` Up to date: \x1B[32m${b.length}\x1B[0m`),this.log(` Changed/outdated: \x1B[33m${u.length}\x1B[0m`),this.log(` Missing (new): \x1B[36m${y.length}\x1B[0m`),this.log(""),u.length===0&&y.length===0){this.success("All scaffold files are up to date!");return}if(y.length>0){this.info(`New files available (${y.length}):`);for(let v of y)this.log(` \x1B[36m+\x1B[0m ${v.path} \x1B[90m(${v.description})\x1B[0m`);if(this.log(""),!i){let v=r?"y":await Ke(" Create all new files? [Y/n/s(elect)] ");if(v==="y"||v==="yes"||v==="")for(let x of y)this.writeFile(D(s,x.path),x.content()),this.success(`Created ${x.path}`);else if(v==="s"||v==="select")for(let x of y){let k=await Ke(` Create ${x.path}? [y/N] `);k==="y"||k==="yes"?(this.writeFile(D(s,x.path),x.content()),this.success(`Created ${x.path}`)):this.log(` \x1B[90mSkipped ${x.path}\x1B[0m`)}else this.log(" Skipped new files.");this.log("")}}if(u.length>0){this.info(`Changed files (${u.length}):`);for(let v of u)this.log(` \x1B[33m~\x1B[0m ${v.path} \x1B[90m(${v.description})\x1B[0m`);if(this.log(""),i){this.info("Dry run \u2014 no files were modified.");return}if(r)for(let v of u)this.writeFile(D(s,v.path),v.content()),this.success(`Updated ${v.path}`);else{let v=await Ke(" Update changed files? [s(elect)/a(ll)/N] ");if(v==="a"||v==="all")for(let x of u){let k=D(s,x.path),A=k+".bak",I=Ce(k,"utf-8");us(A,I),this.writeFile(k,x.content()),this.success(`Updated ${x.path} \x1B[90m(backup: ${x.path}.bak)\x1B[0m`)}else if(v==="s"||v==="select")for(let x of u){let k=await Ke(` Update ${x.path}? [y/N/d(iff)] `);if(k==="d"||k==="diff"){this.showDiff(D(s,x.path),x.content());let A=await Ke(" Apply this update? [y/N] ");if(A==="y"||A==="yes"){let I=Ce(D(s,x.path),"utf-8");us(D(s,x.path)+".bak",I),this.writeFile(D(s,x.path),x.content()),this.success(`Updated ${x.path}`)}else this.log(` \x1B[90mSkipped ${x.path}\x1B[0m`)}else if(k==="y"||k==="yes"){let A=Ce(D(s,x.path),"utf-8");us(D(s,x.path)+".bak",A),this.writeFile(D(s,x.path),x.content()),this.success(`Updated ${x.path} \x1B[90m(backup: ${x.path}.bak)\x1B[0m`)}else this.log(` \x1B[90mSkipped ${x.path}\x1B[0m`)}else this.log(" No files updated.")}}this.log(""),this.success("Update complete.")}normalize(e){return e.replace(/\r\n/g,`
7405
+ `).trim()}writeFile(e,t){qo(Uo(e),{recursive:!0}),us(e,t)}showDiff(e,t){let s=Ce(e,"utf-8").split(`
7257
7406
  `),r=t.split(`
7258
- `);this.log(""),this.log(` \x1B[90m--- ${e} (current)\x1B[0m`),this.log(` \x1B[90m+++ ${e} (updated)\x1B[0m`);let i=Math.max(s.length,r.length),a=0,n=[];for(let c=0;c<i;c++){let m=s[c]??"",p=r[c]??"";m!==p?(s[c]!==void 0&&n.push(` \x1B[31m- ${m}\x1B[0m`),r[c]!==void 0&&n.push(` \x1B[32m+ ${p}\x1B[0m`),a=0):(a<2&&n.length>0&&n.push(` \x1B[90m ${m}\x1B[0m`),a++)}let l=n.slice(0,40);for(let c of l)this.log(c);n.length>40&&this.log(` \x1B[90m... and ${n.length-40} more lines\x1B[0m`),this.log("")}printStatus(e,t,s){let r=[];for(let i of e)r.push(["\x1B[36mNEW\x1B[0m",i.path,i.category,i.description]);for(let i of t)r.push(["\x1B[33mCHANGED\x1B[0m",i.path,i.category,i.description]);for(let i of s)r.push(["\x1B[32mOK\x1B[0m",i.path,i.category,i.description]);this.table(["Status","File","Category","Description"],r)}getFileManifest(e,t){let s=[],r=(y,v,x,k)=>{s.push({path:y,content:v,category:x,description:k})};r("src/app.ts",()=>d.appTs(),"config","Application bootstrap"),r("src/hooks.server.ts",()=>d.hooksServerTs(),"config","SvelteKit hooks"),r("vite.config.ts",()=>d.viteConfig(),"config","Vite configuration"),r(".env.example",()=>d.envExample(),"config","Environment template"),r("svelar.database.json",()=>d.svelarDatabaseJson(),"config","Database config"),r("src/app.css",()=>d.appCss(),"config","Global styles"),r("src/app.html",()=>d.appHtml(),"config","HTML shell"),r("src/lib/database/migrations/00000001_create_users_table.ts",()=>d.createUsersTable(),"migration","Users table"),r("src/lib/database/migrations/00000002_create_posts_table.ts",()=>d.createPostsTable(),"migration","Posts table"),r("src/lib/database/migrations/00000003_create_permissions_tables.ts",()=>d.createPermissionsTables(),"migration","Permissions tables"),r("src/lib/database/migrations/00000004_add_role_to_users.ts",()=>d.addRoleToUsers(),"migration","Role column on users"),r("src/lib/database/migrations/00000005_create_sessions_table.ts",()=>d.createSessionsTable(),"migration","Sessions table"),r("src/lib/database/migrations/00000006_create_audit_logs_table.ts",()=>d.createAuditLogsTable(),"migration","Audit logs table"),r("src/lib/database/migrations/00000007_create_notifications_table.ts",()=>d.createNotificationsTable(),"migration","Notifications table"),r("src/lib/database/migrations/00000008_create_failed_jobs_table.ts",()=>d.createFailedJobsTable(),"migration","Failed jobs table"),r("src/lib/database/migrations/00000009_add_stripe_to_users.ts",()=>d.addStripeToUsers(),"migration","Stripe customer ID on users"),r("src/lib/database/migrations/00000010_create_subscription_plans.ts",()=>d.createSubscriptionPlansTable(),"migration","Subscription plans table"),r("src/lib/database/migrations/00000011_create_subscriptions.ts",()=>d.createSubscriptionsTable(),"migration","Subscriptions table"),r("src/lib/database/migrations/00000012_create_invoices.ts",()=>d.createInvoicesTable(),"migration","Invoices table");let i=e?"src/lib/modules/auth":"src/lib",a=e?`${i}/User.ts`:`${i}/models/User.ts`,n=e?`${i}/UserRepository.ts`:`${i}/repositories/UserRepository.ts`,l=e?`${i}/AuthService.ts`:`${i}/services/AuthService.ts`,c=e?`${i}/AuthController.ts`:`${i}/controllers/AuthController.ts`,m=e?`${i}/RegisterUserAction.ts`:`${i}/actions/RegisterUserAction.ts`;r(a,()=>d.userModel(),"domain","User model"),r(n,()=>d.userRepository(),"domain","User repository"),r(l,()=>d.authService(),"domain","Auth service"),r(c,()=>d.authController(),"domain","Auth controller"),r(m,()=>d.registerUserAction(),"domain","Register user action");let p=e?i:`${i}/dtos`;r(`${e?i:p}/RegisterRequest.ts`,()=>d.registerRequest(),"domain","Register DTO"),r(`${e?i:p}/LoginRequest.ts`,()=>d.loginRequest(),"domain","Login DTO"),r(`${e?i:p}/ForgotPasswordRequest.ts`,()=>d.forgotPasswordRequest(),"domain","Forgot password DTO"),r(`${e?i:p}/ResetPasswordRequest.ts`,()=>d.resetPasswordRequest(),"domain","Reset password DTO"),r(`${e?i:p}/OtpSendRequest.ts`,()=>d.otpSendRequest(),"domain","OTP send DTO"),r(`${e?i:p}/OtpVerifyRequest.ts`,()=>d.otpVerifyRequest(),"domain","OTP verify DTO"),r(`${e?i:`${i}/resources`}/UserResource.ts`,()=>d.userResource(),"domain","User resource"),r(`${e?i:`${i}/schemas`}/gates.ts`,()=>d.gates(),"domain","Authorization gates"),r(`${e?i+"/schemas":`${i}/schemas`}.ts`,()=>d.authSchema(),"domain","Auth Zod schemas");let h=e?"src/lib/modules/posts":"src/lib";r(`${e?h:`${h}/models`}/Post.ts`,()=>d.postModel(),"domain","Post model"),r(`${e?h:`${h}/repositories`}/PostRepository.ts`,()=>d.postRepository(),"domain","Post repository"),r(`${e?h:`${h}/services`}/PostService.ts`,()=>d.postService(),"domain","Post service"),r(`${e?h:`${h}/controllers`}/PostController.ts`,()=>d.postController(),"domain","Post controller"),r(`${e?h:`${h}/actions`}/CreatePostAction.ts`,()=>d.createPostAction(),"domain","Create post action"),r("src/lib/database/seeders/DatabaseSeeder.ts",()=>d.databaseSeeder(),"seeder","Database seeder"),r("src/routes/login/+page.server.ts",()=>d.loginPageServer(),"page","Login server"),r("src/routes/login/+page.svelte",()=>d.loginPageSvelte(),"page","Login page"),r("src/routes/register/+page.server.ts",()=>d.registerPageServer(),"page","Register server"),r("src/routes/register/+page.svelte",()=>d.registerPageSvelte(),"page","Register page"),r("src/routes/logout/+page.server.ts",()=>d.logoutPageServer(),"page","Logout handler"),r("src/routes/forgot-password/+page.server.ts",()=>d.forgotPasswordPageServer(),"page","Forgot password server"),r("src/routes/forgot-password/+page.svelte",()=>d.forgotPasswordPageSvelte(),"page","Forgot password page"),r("src/routes/reset-password/+page.server.ts",()=>d.resetPasswordPageServer(),"page","Reset password server"),r("src/routes/reset-password/+page.svelte",()=>d.resetPasswordPageSvelte(),"page","Reset password page"),r("src/routes/otp-login/+page.server.ts",()=>d.otpLoginPageServer(),"page","OTP login server"),r("src/routes/otp-login/+page.svelte",()=>d.otpLoginPageSvelte(),"page","OTP login page"),r("src/routes/verify-email/+page.server.ts",()=>d.verifyEmailPageServer(),"page","Verify email server"),r("src/routes/verify-email/+page.svelte",()=>d.verifyEmailPageSvelte(),"page","Verify email page"),r("src/routes/dashboard/+layout.server.ts",()=>d.dashboardLayoutServer(),"page","Dashboard auth guard"),r("src/routes/dashboard/+layout.svelte",()=>d.dashboardLayoutSvelte(),"page","Dashboard layout"),r("src/routes/dashboard/+page.server.ts",()=>d.dashboardPageServer(),"page","Dashboard server"),r("src/routes/dashboard/+page.svelte",()=>d.dashboardPageSvelte(),"page","Dashboard overview"),r("src/routes/dashboard/api-keys/+page.server.ts",()=>d.apiKeysPageServer(),"page","API keys server"),r("src/routes/dashboard/api-keys/+page.svelte",()=>d.apiKeysPageSvelte(),"page","API keys page"),r("src/routes/dashboard/team/+page.server.ts",()=>d.teamPageServer(),"page","Team server"),r("src/routes/dashboard/team/+page.svelte",()=>d.teamPageSvelte(),"page","Team page"),r("src/routes/dashboard/billing/+page.server.ts",()=>d.billingPageServer(),"page","Billing server"),r("src/routes/dashboard/billing/+page.svelte",()=>d.billingPageSvelte(),"page","Billing page"),r("src/routes/admin/+layout.server.ts",()=>d.adminLayoutServer(),"page","Admin auth guard"),r("src/routes/admin/+layout.svelte",()=>d.adminLayoutSvelte(),"page","Admin layout"),r("src/routes/admin/+page.server.ts",()=>d.adminPageServer(),"page","Admin server"),r("src/routes/admin/+page.svelte",()=>d.adminPageSvelte(),"page","Admin dashboard"),r("src/routes/api/health/+server.ts",()=>d.apiHealth(),"route","Health check"),r("src/routes/api/auth/register/+server.ts",()=>d.apiAuthRegister(),"route","Auth register API"),r("src/routes/api/auth/login/+server.ts",()=>d.apiAuthLogin(),"route","Auth login API"),r("src/routes/api/auth/logout/+server.ts",()=>d.apiAuthLogout(),"route","Auth logout API"),r("src/routes/api/auth/me/+server.ts",()=>d.apiAuthMe(),"route","Auth me API"),r("src/routes/api/auth/forgot-password/+server.ts",()=>d.apiAuthForgotPassword(),"route","Forgot password API"),r("src/routes/api/auth/reset-password/+server.ts",()=>d.apiAuthResetPassword(),"route","Reset password API"),r("src/routes/api/auth/otp/send/+server.ts",()=>d.apiAuthOtpSend(),"route","OTP send API"),r("src/routes/api/auth/otp/verify/+server.ts",()=>d.apiAuthOtpVerify(),"route","OTP verify API"),r("src/routes/api/auth/verify-email/+server.ts",()=>d.apiAuthVerifyEmail(),"route","Verify email API"),r("src/routes/api/posts/+server.ts",()=>d.apiPosts(),"route","Posts list/create API"),r("src/routes/api/posts/[id]/+server.ts",()=>d.apiPostsSingle(),"route","Post CRUD API"),r("src/routes/api/posts/mine/+server.ts",()=>d.apiPostsMine(),"route","My posts API"),r("src/routes/api/broadcasting/[channel]/+server.ts",()=>d.apiBroadcasting(),"route","SSE broadcasting"),r("src/routes/api/internal/broadcast/+server.ts",()=>d.apiInternalBroadcast(),"route","Internal broadcast bridge"),r("src/routes/api/admin/users/+server.ts",()=>d.apiAdminUsers(),"route","Admin users API"),r("src/routes/api/admin/roles/+server.ts",()=>d.apiAdminRoles(),"route","Admin roles API"),r("src/routes/api/admin/permissions/+server.ts",()=>d.apiAdminPermissions(),"route","Admin permissions API"),r("src/routes/api/admin/role-permissions/+server.ts",()=>d.apiAdminRolePermissions(),"route","Role-permissions API"),r("src/routes/api/admin/user-roles/+server.ts",()=>d.apiAdminUserRoles(),"route","User-roles API"),r("src/routes/api/admin/user-permissions/+server.ts",()=>d.apiAdminUserPermissions(),"route","User-permissions API"),r("src/routes/api/admin/export/+server.ts",()=>d.apiAdminExport(),"route","Admin data export"),r("src/routes/api/admin/health/+server.ts",()=>d.apiAdminHealth(),"route","Admin health API"),r("src/routes/api/admin/queue/+server.ts",()=>d.apiAdminQueue(),"route","Admin queue API"),r("src/routes/api/admin/queue/[id]/retry/+server.ts",()=>d.apiAdminQueueRetry(),"route","Queue retry API"),r("src/routes/api/admin/queue/[id]/+server.ts",()=>d.apiAdminQueueDelete(),"route","Queue job API"),r("src/routes/api/admin/scheduler/+server.ts",()=>d.apiAdminScheduler(),"route","Admin scheduler API"),r("src/routes/api/admin/scheduler/[name]/run/+server.ts",()=>d.apiAdminSchedulerRun(),"route","Run task API"),r("src/routes/api/admin/scheduler/[name]/toggle/+server.ts",()=>d.apiAdminSchedulerToggle(),"route","Toggle task API"),r("src/routes/api/admin/logs/+server.ts",()=>d.apiAdminLogs(),"route","Admin logs API"),r("src/routes/api/admin/stats/+server.ts",()=>d.apiAdminStats(),"route","Admin stats API"),r("src/routes/api/admin/billing/subscriptions/+server.ts",()=>d.apiAdminBillingSubscriptions(),"route","Admin billing subscriptions"),r("src/routes/api/admin/billing/refund/+server.ts",()=>d.apiAdminBillingRefund(),"route","Admin billing refund"),r("src/routes/api/admin/billing/cancel/+server.ts",()=>d.apiAdminBillingCancel(),"route","Admin billing cancel"),r("src/routes/api/webhooks/stripe/+server.ts",()=>d.stripeWebhookRoute(),"route","Stripe webhook");let u=e?"src/lib/shared/jobs":"src/lib/jobs";r(`${u}/SendWelcomeEmail.ts`,()=>d.sendWelcomeEmail(),"job","Welcome email job"),r(`${u}/DailyDigestJob.ts`,()=>d.dailyDigestJob(),"job","Daily digest job"),r(`${u}/ExportDataJob.ts`,()=>d.exportDataJob(),"job","Export data job");let b=e?"src/lib/shared/scheduler":"src/lib/scheduler";return r(`${b}/CleanupExpiredTokens.ts`,()=>d.cleanupExpiredTokens(),"job","Cleanup tokens task"),r(`${b}/CleanExpiredSessions.ts`,()=>d.cleanExpiredSessions(),"job","Clean sessions task"),r(`${b}/DailyDigestEmail.ts`,()=>d.dailyDigestEmail(),"job","Daily digest task"),r(`${b}/PruneAuditLogs.ts`,()=>d.pruneAuditLogs(),"job","Prune audit logs task"),r(`${b}/QueueHealthCheck.ts`,()=>d.queueHealthCheck(),"job","Queue health check task"),r("src/routes/+layout.svelte",()=>d.rootLayoutSvelte(t),"page","Root layout"),r("src/routes/+layout.server.ts",()=>d.rootLayoutServer(),"page","Root layout server"),r("src/routes/+error.svelte",()=>d.errorSvelte(),"page","Error page"),r("src/routes/+page.svelte",()=>d.homePage(t),"page","Home page"),s}};var us=class extends g{name="key:generate";description="Generate a new APP_KEY and set it in .env";flags=[{name:"show",alias:"s",description:"Only display the key, do not write to .env",type:"boolean",default:!1},{name:"force",alias:"f",description:"Overwrite existing APP_KEY",type:"boolean",default:!1}];async handle(e,t){let{randomBytes:s}=await import("crypto"),{join:r}=await import("path"),{existsSync:i,readFileSync:a,writeFileSync:n}=await import("fs"),l=s(32).toString("hex");if(t.show){this.log(`
7407
+ `);this.log(""),this.log(` \x1B[90m--- ${e} (current)\x1B[0m`),this.log(` \x1B[90m+++ ${e} (updated)\x1B[0m`);let i=Math.max(s.length,r.length),a=0,n=[];for(let c=0;c<i;c++){let m=s[c]??"",p=r[c]??"";m!==p?(s[c]!==void 0&&n.push(` \x1B[31m- ${m}\x1B[0m`),r[c]!==void 0&&n.push(` \x1B[32m+ ${p}\x1B[0m`),a=0):(a<2&&n.length>0&&n.push(` \x1B[90m ${m}\x1B[0m`),a++)}let l=n.slice(0,40);for(let c of l)this.log(c);n.length>40&&this.log(` \x1B[90m... and ${n.length-40} more lines\x1B[0m`),this.log("")}printStatus(e,t,s){let r=[];for(let i of e)r.push(["\x1B[36mNEW\x1B[0m",i.path,i.category,i.description]);for(let i of t)r.push(["\x1B[33mCHANGED\x1B[0m",i.path,i.category,i.description]);for(let i of s)r.push(["\x1B[32mOK\x1B[0m",i.path,i.category,i.description]);this.table(["Status","File","Category","Description"],r)}getFileManifest(e,t){let s=[],r=(y,v,x,k)=>{s.push({path:y,content:v,category:x,description:k})};r("src/app.ts",()=>d.appTs(),"config","Application bootstrap"),r("src/hooks.server.ts",()=>d.hooksServerTs(),"config","SvelteKit hooks"),r("vite.config.ts",()=>d.viteConfig(),"config","Vite configuration"),r(".env.example",()=>d.envExample(),"config","Environment template"),r("svelar.database.json",()=>d.svelarDatabaseJson(),"config","Database config"),r("src/app.css",()=>d.appCss(),"config","Global styles"),r("src/app.html",()=>d.appHtml(),"config","HTML shell"),r("src/lib/database/migrations/00000001_create_users_table.ts",()=>d.createUsersTable(),"migration","Users table"),r("src/lib/database/migrations/00000002_create_posts_table.ts",()=>d.createPostsTable(),"migration","Posts table"),r("src/lib/database/migrations/00000003_create_permissions_tables.ts",()=>d.createPermissionsTables(),"migration","Permissions tables"),r("src/lib/database/migrations/00000004_add_role_to_users.ts",()=>d.addRoleToUsers(),"migration","Role column on users"),r("src/lib/database/migrations/00000005_create_sessions_table.ts",()=>d.createSessionsTable(),"migration","Sessions table"),r("src/lib/database/migrations/00000006_create_audit_logs_table.ts",()=>d.createAuditLogsTable(),"migration","Audit logs table"),r("src/lib/database/migrations/00000007_create_notifications_table.ts",()=>d.createNotificationsTable(),"migration","Notifications table"),r("src/lib/database/migrations/00000008_create_failed_jobs_table.ts",()=>d.createFailedJobsTable(),"migration","Failed jobs table"),r("src/lib/database/migrations/00000009_add_stripe_to_users.ts",()=>d.addStripeToUsers(),"migration","Stripe customer ID on users"),r("src/lib/database/migrations/00000010_create_subscription_plans.ts",()=>d.createSubscriptionPlansTable(),"migration","Subscription plans table"),r("src/lib/database/migrations/00000011_create_subscriptions.ts",()=>d.createSubscriptionsTable(),"migration","Subscriptions table"),r("src/lib/database/migrations/00000012_create_invoices.ts",()=>d.createInvoicesTable(),"migration","Invoices table");let i=e?"src/lib/modules/auth":"src/lib",a=e?`${i}/User.ts`:`${i}/models/User.ts`,n=e?`${i}/UserRepository.ts`:`${i}/repositories/UserRepository.ts`,l=e?`${i}/AuthService.ts`:`${i}/services/AuthService.ts`,c=e?`${i}/AuthController.ts`:`${i}/controllers/AuthController.ts`,m=e?`${i}/RegisterUserAction.ts`:`${i}/actions/RegisterUserAction.ts`;r(a,()=>d.userModel(),"domain","User model"),r(n,()=>d.userRepository(),"domain","User repository"),r(l,()=>d.authService(),"domain","Auth service"),r(c,()=>d.authController(),"domain","Auth controller"),r(m,()=>d.registerUserAction(),"domain","Register user action");let p=e?i:`${i}/dtos`;r(`${e?i:p}/RegisterRequest.ts`,()=>d.registerRequest(),"domain","Register DTO"),r(`${e?i:p}/LoginRequest.ts`,()=>d.loginRequest(),"domain","Login DTO"),r(`${e?i:p}/ForgotPasswordRequest.ts`,()=>d.forgotPasswordRequest(),"domain","Forgot password DTO"),r(`${e?i:p}/ResetPasswordRequest.ts`,()=>d.resetPasswordRequest(),"domain","Reset password DTO"),r(`${e?i:p}/OtpSendRequest.ts`,()=>d.otpSendRequest(),"domain","OTP send DTO"),r(`${e?i:p}/OtpVerifyRequest.ts`,()=>d.otpVerifyRequest(),"domain","OTP verify DTO"),r(`${e?i:`${i}/resources`}/UserResource.ts`,()=>d.userResource(),"domain","User resource"),r(`${e?i:`${i}/schemas`}/gates.ts`,()=>d.gates(),"domain","Authorization gates"),r(`${e?i+"/schemas":`${i}/schemas`}.ts`,()=>d.authSchema(),"domain","Auth Zod schemas");let h=e?"src/lib/modules/posts":"src/lib";r(`${e?h:`${h}/models`}/Post.ts`,()=>d.postModel(),"domain","Post model"),r(`${e?h:`${h}/repositories`}/PostRepository.ts`,()=>d.postRepository(),"domain","Post repository"),r(`${e?h:`${h}/services`}/PostService.ts`,()=>d.postService(),"domain","Post service"),r(`${e?h:`${h}/controllers`}/PostController.ts`,()=>d.postController(),"domain","Post controller"),r(`${e?h:`${h}/actions`}/CreatePostAction.ts`,()=>d.createPostAction(),"domain","Create post action"),r("src/lib/database/seeders/DatabaseSeeder.ts",()=>d.databaseSeeder(),"seeder","Database seeder"),r("src/routes/login/+page.server.ts",()=>d.loginPageServer(),"page","Login server"),r("src/routes/login/+page.svelte",()=>d.loginPageSvelte(),"page","Login page"),r("src/routes/register/+page.server.ts",()=>d.registerPageServer(),"page","Register server"),r("src/routes/register/+page.svelte",()=>d.registerPageSvelte(),"page","Register page"),r("src/routes/logout/+page.server.ts",()=>d.logoutPageServer(),"page","Logout handler"),r("src/routes/forgot-password/+page.server.ts",()=>d.forgotPasswordPageServer(),"page","Forgot password server"),r("src/routes/forgot-password/+page.svelte",()=>d.forgotPasswordPageSvelte(),"page","Forgot password page"),r("src/routes/reset-password/+page.server.ts",()=>d.resetPasswordPageServer(),"page","Reset password server"),r("src/routes/reset-password/+page.svelte",()=>d.resetPasswordPageSvelte(),"page","Reset password page"),r("src/routes/otp-login/+page.server.ts",()=>d.otpLoginPageServer(),"page","OTP login server"),r("src/routes/otp-login/+page.svelte",()=>d.otpLoginPageSvelte(),"page","OTP login page"),r("src/routes/verify-email/+page.server.ts",()=>d.verifyEmailPageServer(),"page","Verify email server"),r("src/routes/verify-email/+page.svelte",()=>d.verifyEmailPageSvelte(),"page","Verify email page"),r("src/routes/dashboard/+layout.server.ts",()=>d.dashboardLayoutServer(),"page","Dashboard auth guard"),r("src/routes/dashboard/+layout.svelte",()=>d.dashboardLayoutSvelte(),"page","Dashboard layout"),r("src/routes/dashboard/+page.server.ts",()=>d.dashboardPageServer(),"page","Dashboard server"),r("src/routes/dashboard/+page.svelte",()=>d.dashboardPageSvelte(),"page","Dashboard overview"),r("src/routes/dashboard/api-keys/+page.server.ts",()=>d.apiKeysPageServer(),"page","API keys server"),r("src/routes/dashboard/api-keys/+page.svelte",()=>d.apiKeysPageSvelte(),"page","API keys page"),r("src/routes/dashboard/team/+page.server.ts",()=>d.teamPageServer(),"page","Team server"),r("src/routes/dashboard/team/+page.svelte",()=>d.teamPageSvelte(),"page","Team page"),r("src/routes/dashboard/billing/+page.server.ts",()=>d.billingPageServer(),"page","Billing server"),r("src/routes/dashboard/billing/+page.svelte",()=>d.billingPageSvelte(),"page","Billing page"),r("src/routes/admin/+layout.server.ts",()=>d.adminLayoutServer(),"page","Admin auth guard"),r("src/routes/admin/+layout.svelte",()=>d.adminLayoutSvelte(),"page","Admin layout"),r("src/routes/admin/+page.server.ts",()=>d.adminPageServer(),"page","Admin server"),r("src/routes/admin/+page.svelte",()=>d.adminPageSvelte(),"page","Admin dashboard"),r("src/routes/api/health/+server.ts",()=>d.apiHealth(),"route","Health check"),r("src/routes/api/auth/register/+server.ts",()=>d.apiAuthRegister(),"route","Auth register API"),r("src/routes/api/auth/login/+server.ts",()=>d.apiAuthLogin(),"route","Auth login API"),r("src/routes/api/auth/logout/+server.ts",()=>d.apiAuthLogout(),"route","Auth logout API"),r("src/routes/api/auth/me/+server.ts",()=>d.apiAuthMe(),"route","Auth me API"),r("src/routes/api/auth/forgot-password/+server.ts",()=>d.apiAuthForgotPassword(),"route","Forgot password API"),r("src/routes/api/auth/reset-password/+server.ts",()=>d.apiAuthResetPassword(),"route","Reset password API"),r("src/routes/api/auth/otp/send/+server.ts",()=>d.apiAuthOtpSend(),"route","OTP send API"),r("src/routes/api/auth/otp/verify/+server.ts",()=>d.apiAuthOtpVerify(),"route","OTP verify API"),r("src/routes/api/auth/verify-email/+server.ts",()=>d.apiAuthVerifyEmail(),"route","Verify email API"),r("src/routes/api/posts/+server.ts",()=>d.apiPosts(),"route","Posts list/create API"),r("src/routes/api/posts/[id]/+server.ts",()=>d.apiPostsSingle(),"route","Post CRUD API"),r("src/routes/api/posts/mine/+server.ts",()=>d.apiPostsMine(),"route","My posts API"),r("src/routes/api/broadcasting/[channel]/+server.ts",()=>d.apiBroadcasting(),"route","SSE broadcasting"),r("src/routes/api/internal/broadcast/+server.ts",()=>d.apiInternalBroadcast(),"route","Internal broadcast bridge"),r("src/routes/api/admin/users/+server.ts",()=>d.apiAdminUsers(),"route","Admin users API"),r("src/routes/api/admin/roles/+server.ts",()=>d.apiAdminRoles(),"route","Admin roles API"),r("src/routes/api/admin/permissions/+server.ts",()=>d.apiAdminPermissions(),"route","Admin permissions API"),r("src/routes/api/admin/role-permissions/+server.ts",()=>d.apiAdminRolePermissions(),"route","Role-permissions API"),r("src/routes/api/admin/user-roles/+server.ts",()=>d.apiAdminUserRoles(),"route","User-roles API"),r("src/routes/api/admin/user-permissions/+server.ts",()=>d.apiAdminUserPermissions(),"route","User-permissions API"),r("src/routes/api/admin/export/+server.ts",()=>d.apiAdminExport(),"route","Admin data export"),r("src/routes/api/admin/health/+server.ts",()=>d.apiAdminHealth(),"route","Admin health API"),r("src/routes/api/admin/queue/+server.ts",()=>d.apiAdminQueue(),"route","Admin queue API"),r("src/routes/api/admin/queue/[id]/retry/+server.ts",()=>d.apiAdminQueueRetry(),"route","Queue retry API"),r("src/routes/api/admin/queue/[id]/+server.ts",()=>d.apiAdminQueueDelete(),"route","Queue job API"),r("src/routes/api/admin/scheduler/+server.ts",()=>d.apiAdminScheduler(),"route","Admin scheduler API"),r("src/routes/api/admin/scheduler/[name]/run/+server.ts",()=>d.apiAdminSchedulerRun(),"route","Run task API"),r("src/routes/api/admin/scheduler/[name]/toggle/+server.ts",()=>d.apiAdminSchedulerToggle(),"route","Toggle task API"),r("src/routes/api/admin/logs/+server.ts",()=>d.apiAdminLogs(),"route","Admin logs API"),r("src/routes/api/admin/stats/+server.ts",()=>d.apiAdminStats(),"route","Admin stats API"),r("src/routes/api/admin/billing/subscriptions/+server.ts",()=>d.apiAdminBillingSubscriptions(),"route","Admin billing subscriptions"),r("src/routes/api/admin/billing/refund/+server.ts",()=>d.apiAdminBillingRefund(),"route","Admin billing refund"),r("src/routes/api/admin/billing/cancel/+server.ts",()=>d.apiAdminBillingCancel(),"route","Admin billing cancel"),r("src/routes/api/webhooks/stripe/+server.ts",()=>d.stripeWebhookRoute(),"route","Stripe webhook");let u=e?"src/lib/shared/jobs":"src/lib/jobs";r(`${u}/SendWelcomeEmail.ts`,()=>d.sendWelcomeEmail(),"job","Welcome email job"),r(`${u}/DailyDigestJob.ts`,()=>d.dailyDigestJob(),"job","Daily digest job"),r(`${u}/ExportDataJob.ts`,()=>d.exportDataJob(),"job","Export data job");let b=e?"src/lib/shared/scheduler":"src/lib/scheduler";return r(`${b}/CleanupExpiredTokens.ts`,()=>d.cleanupExpiredTokens(),"job","Cleanup tokens task"),r(`${b}/CleanExpiredSessions.ts`,()=>d.cleanExpiredSessions(),"job","Clean sessions task"),r(`${b}/DailyDigestEmail.ts`,()=>d.dailyDigestEmail(),"job","Daily digest task"),r(`${b}/PruneAuditLogs.ts`,()=>d.pruneAuditLogs(),"job","Prune audit logs task"),r(`${b}/QueueHealthCheck.ts`,()=>d.queueHealthCheck(),"job","Queue health check task"),r("src/routes/+layout.svelte",()=>d.rootLayoutSvelte(t),"page","Root layout"),r("src/routes/+layout.server.ts",()=>d.rootLayoutServer(),"page","Root layout server"),r("src/routes/+error.svelte",()=>d.errorSvelte(),"page","Error page"),r("src/routes/+page.svelte",()=>d.homePage(t),"page","Home page"),s}};var ps=class extends g{name="key:generate";description="Generate a new APP_KEY and set it in .env";flags=[{name:"show",alias:"s",description:"Only display the key, do not write to .env",type:"boolean",default:!1},{name:"force",alias:"f",description:"Overwrite existing APP_KEY",type:"boolean",default:!1}];async handle(e,t){let{randomBytes:s}=await import("crypto"),{join:r}=await import("path"),{existsSync:i,readFileSync:a,writeFileSync:n}=await import("fs"),l=s(32).toString("hex");if(t.show){this.log(`
7259
7408
  APP_KEY=${l}
7260
7409
  `);return}let c=r(process.cwd(),".env");if(!i(c)){let h=r(process.cwd(),".env.example");if(i(h)){let u=a(h,"utf-8");u=u.replace(/^APP_KEY=.*$/m,`APP_KEY=${l}`),n(c,u),this.success("Application key set (created .env from .env.example).")}else n(c,`APP_KEY=${l}
7261
7410
  `),this.success("Application key set (created .env).");return}let m=a(c,"utf-8"),p=m.match(/^APP_KEY=(.*)$/m);if(p&&p[1]&&p[1]!=="change-me-to-a-random-string"&&!t.force){this.warn("APP_KEY already set. Use --force to overwrite.");return}if(p){let h=m.replace(/^APP_KEY=.*$/m,`APP_KEY=${l}`);n(c,h)}else n(c,`APP_KEY=${l}
7262
- ${m}`);this.success("Application key set.")}};var hs=class extends g{name="plugin:list";description="List all discovered and enabled plugins";arguments=[];flags=[];async handle(e,t){try{let{PluginRegistry:s}=await Promise.resolve().then(()=>(ps(),_r)),r=s;await r.discover();let i=r.list();if(i.length===0){this.info("No plugins discovered.");return}let a=["Name","Version","Description","Status","Config","Migrations"],n=i.map(l=>[l.name,l.version,l.description||"-",l.enabled?"\u2713 Enabled":" Disabled",l.hasConfig?"\u2713":"-",l.hasMigrations?"\u2713":"-"]);this.newLine(),this.table(a,n),this.newLine(),this.info(`Total: ${i.length} plugin(s)`)}catch(s){this.error(`Failed to list plugins: ${s?.message??String(s)}`)}}};var gs=class extends g{name="plugin:publish";description="Publish a plugin's config and migration files";arguments=["name"];flags=[{name:"force",alias:"f",description:"Overwrite existing files",type:"boolean"},{name:"only",alias:"o",description:"Publish only config|migrations|assets",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a plugin name.");return}try{let{PluginRegistry:r}=await Promise.resolve().then(()=>(ps(),_r)),{PluginPublisher:i}=await Promise.resolve().then(()=>(Ir(),ra)),a=r,n=i;await a.discover();let l=a.get(s);if(!l){this.error(`Plugin "${s}" not found.`);return}let c=await this.loadPluginClass(l.packageName);if(!c){this.error(`Failed to load plugin class for "${s}".`);return}let m=new c,p={force:t.force||!1,only:t.only};this.info(`Publishing plugin: ${s}`);let h=await n.publish(m,p);this.newLine(),h.configs.length>0&&(this.success(`${h.configs.length} config file(s) published:`),h.configs.forEach(u=>this.log(` - ${u}`))),h.migrations.length>0&&(this.success(`${h.migrations.length} migration file(s) published:`),h.migrations.forEach(u=>this.log(` - ${u}`))),h.assets.length>0&&(this.success(`${h.assets.length} asset file(s) published:`),h.assets.forEach(u=>this.log(` - ${u}`))),h.configs.length===0&&h.migrations.length===0&&h.assets.length===0&&this.warn("No publishable files found for this plugin."),this.newLine()}catch(r){this.error(`Failed to publish plugin: ${r?.message??String(r)}`)}}async loadPluginClass(e){try{let t=await import(e);return t.default||Object.values(t)[0]}catch{return null}}};var fs=class extends g{name="plugin:install";description="Install a plugin from npm";arguments=["package"];flags=[{name:"no-publish",alias:"n",description:"Skip auto-publishing plugin assets",type:"boolean"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a package name.");return}try{let{PluginInstaller:r}=await Promise.resolve().then(()=>(aa(),ia)),i=r;this.info(`Installing plugin package: ${s}`),this.newLine();let a=await i.install(s,{publish:!t["no-publish"]});this.newLine(),a.success?(this.success(`Plugin installed: ${a.pluginName} (v${a.version})`),a.published&&(a.published.configs.length>0&&this.info(`${a.published.configs.length} config file(s) published`),a.published.migrations.length>0&&this.info(`${a.published.migrations.length} migration file(s) published`),a.published.assets.length>0&&this.info(`${a.published.assets.length} asset file(s) published`)),this.newLine(),this.log("You can now use the plugin in your application by registering it in your app bootstrap code.")):this.error(`Failed to install plugin: ${a.error}`),this.newLine()}catch(r){this.error(`Installation error: ${r?.message??String(r)}`)}}};var na=Or(process.cwd(),".env");if(Lo(na))for(let o of ca(na,"utf-8").split(`
7263
- `)){let e=o.trim();if(!e||e.startsWith("#"))continue;let t=e.indexOf("=");if(t===-1)continue;let s=e.slice(0,t).trim(),r=e.slice(t+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),s in process.env||(process.env[s]=r)}var _o=oa(la(import.meta.url));Do(Ao(Or(_o,"ts-resolve-hook.mjs")).href,import.meta.url);var Mo=oa(la(import.meta.url)),No=Or(Mo,"..","..","package.json"),Io=JSON.parse(ca(No,"utf-8")),C=new Ge(Io.version);C.register(ls);C.register(ds);C.register(us);C.register(Ze);C.register(Xe);C.register(et);C.register(tt);C.register(st);C.register(rt);C.register(it);C.register(at);C.register(nt);C.register(ot);C.register(ft);C.register(bt);C.register(lt);C.register(ct);C.register(dt);C.register(ut);C.register(mt);C.register(pt);C.register(ht);C.register(gt);C.register(yt);C.register(vt);C.register(wt);C.register(Ct);C.register(xt);C.register(St);C.register(Pt);C.register(kt);C.register(At);C.register(Dt);C.register(Lt);C.register(_t);C.register(os);C.register(hs);C.register(gs);C.register(fs);async function jo(){let{join:o}=await import("path"),{existsSync:e,readdirSync:t}=await import("fs"),{pathToFileURL:s}=await import("url"),r=o(process.cwd(),"src","lib","shared","commands");if(!e(r))return;let i=t(r).filter(a=>(a.endsWith(".ts")||a.endsWith(".js"))&&!a.startsWith("."));for(let a of i)try{let n=o(r,a),c=await import(s(n).href),m=c.default??Object.values(c).find(p=>typeof p=="function"&&p.prototype&&"handle"in p.prototype);m&&typeof m=="function"&&C.add(new m)}catch{}}jo().then(()=>C.run());
7411
+ ${m}`);this.success("Application key set.")}};var fs=class extends g{name="plugin:list";description="List all discovered and enabled plugins";arguments=[];flags=[];async handle(e,t){try{let{PluginRegistry:s}=await Promise.resolve().then(()=>(gs(),Nr)),r=s;await r.discover();let i=r.list();if(i.length===0){this.info("No plugins discovered.");return}let a=["Name","Version","Description","Status","Config","Migrations"],n=i.map(l=>[l.name,l.version,l.description||"-",l.enabled?"\u2713 Enabled":" Disabled",l.hasConfig?"\u2713":"-",l.hasMigrations?"\u2713":"-"]);this.newLine(),this.table(a,n),this.newLine(),this.info(`Total: ${i.length} plugin(s)`)}catch(s){this.error(`Failed to list plugins: ${s?.message??String(s)}`)}}};var bs=class extends g{name="plugin:publish";description="Publish a plugin's config and migration files";arguments=["name"];flags=[{name:"force",alias:"f",description:"Overwrite existing files",type:"boolean"},{name:"only",alias:"o",description:"Publish only config|migrations|assets",type:"string"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a plugin name.");return}try{let{PluginRegistry:r}=await Promise.resolve().then(()=>(gs(),Nr)),{PluginPublisher:i}=await Promise.resolve().then(()=>(Or(),oa)),a=r,n=i;await a.discover();let l=a.get(s);if(!l){this.error(`Plugin "${s}" not found.`);return}let c=await this.loadPluginClass(l.packageName);if(!c){this.error(`Failed to load plugin class for "${s}".`);return}let m=new c,p={force:t.force||!1,only:t.only};this.info(`Publishing plugin: ${s}`);let h=await n.publish(m,p);this.newLine(),h.configs.length>0&&(this.success(`${h.configs.length} config file(s) published:`),h.configs.forEach(u=>this.log(` - ${u}`))),h.migrations.length>0&&(this.success(`${h.migrations.length} migration file(s) published:`),h.migrations.forEach(u=>this.log(` - ${u}`))),h.assets.length>0&&(this.success(`${h.assets.length} asset file(s) published:`),h.assets.forEach(u=>this.log(` - ${u}`))),h.configs.length===0&&h.migrations.length===0&&h.assets.length===0&&this.warn("No publishable files found for this plugin."),this.newLine()}catch(r){this.error(`Failed to publish plugin: ${r?.message??String(r)}`)}}async loadPluginClass(e){try{let t=await import(e);return t.default||Object.values(t)[0]}catch{return null}}};var ys=class extends g{name="plugin:install";description="Install a plugin from npm";arguments=["package"];flags=[{name:"no-publish",alias:"n",description:"Skip auto-publishing plugin assets",type:"boolean"}];async handle(e,t){let s=e[0];if(!s){this.error("Please provide a package name.");return}try{let{PluginInstaller:r}=await Promise.resolve().then(()=>(ca(),la)),i=r;this.info(`Installing plugin package: ${s}`),this.newLine();let a=await i.install(s,{publish:!t["no-publish"]});this.newLine(),a.success?(this.success(`Plugin installed: ${a.pluginName} (v${a.version})`),a.published&&(a.published.configs.length>0&&this.info(`${a.published.configs.length} config file(s) published`),a.published.migrations.length>0&&this.info(`${a.published.migrations.length} migration file(s) published`),a.published.assets.length>0&&this.info(`${a.published.assets.length} asset file(s) published`)),this.newLine(),this.log("You can now use the plugin in your application by registering it in your app bootstrap code.")):this.error(`Failed to install plugin: ${a.error}`),this.newLine()}catch(r){this.error(`Installation error: ${r?.message??String(r)}`)}}};var da=Ur(process.cwd(),".env");if(Ko(da))for(let o of pa(da,"utf-8").split(`
7412
+ `)){let e=o.trim();if(!e||e.startsWith("#"))continue;let t=e.indexOf("=");if(t===-1)continue;let s=e.slice(0,t).trim(),r=e.slice(t+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),s in process.env||(process.env[s]=r)}var Wo=ua(ma(import.meta.url));zo(Ho(Ur(Wo,"ts-resolve-hook.mjs")).href,import.meta.url);var Jo=ua(ma(import.meta.url)),Vo=Ur(Jo,"..","..","package.json"),Qo=JSON.parse(pa(Vo,"utf-8")),w=new Ge(Qo.version);w.register(ds);w.register(ms);w.register(ps);w.register(Ze);w.register(Xe);w.register(et);w.register(tt);w.register(st);w.register(rt);w.register(it);w.register(at);w.register(nt);w.register(ot);w.register(yt);w.register(vt);w.register(lt);w.register(ct);w.register(dt);w.register(ut);w.register(mt);w.register(pt);w.register(ht);w.register(gt);w.register(ft);w.register(bt);w.register(wt);w.register(Ct);w.register(xt);w.register(Pt);w.register(St);w.register(Rt);w.register(Tt);w.register($t);w.register(Lt);w.register(_t);w.register(Mt);w.register(Nt);w.register(cs);w.register(fs);w.register(bs);w.register(ys);async function Go(){let{join:o}=await import("path"),{existsSync:e,readdirSync:t}=await import("fs"),{pathToFileURL:s}=await import("url"),r=o(process.cwd(),"src","lib","shared","commands");if(!e(r))return;let i=t(r).filter(a=>(a.endsWith(".ts")||a.endsWith(".js"))&&!a.startsWith("."));for(let a of i)try{let n=o(r,a),c=await import(s(n).href),m=c.default??Object.values(c).find(p=>typeof p=="function"&&p.prototype&&"handle"in p.prototype);m&&typeof m=="function"&&w.add(new m)}catch{}}Go().then(()=>w.run());