@kyro-cms/core 0.12.41 → 0.12.42
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/api-handler-graphql.cjs +1 -1
- package/dist/api-handler-graphql.js +1 -1
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +1 -1
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.d.cts +1 -1
- package/dist/api-handler.d.ts +1 -1
- package/dist/api-handler.js +1 -1
- package/dist/bootstrap-ROSTPMVL.js +1 -0
- package/dist/bootstrap-WW5NJ6EB.cjs +1 -0
- package/dist/{chunk-RXZ3IUWM.cjs → chunk-3CVLI5C5.cjs} +2 -2
- package/dist/{chunk-65G73T7Z.cjs → chunk-4IGWJMBY.cjs} +2 -2
- package/dist/{chunk-NZ35PV5R.js → chunk-5B6X2GBJ.js} +2 -2
- package/dist/chunk-7IVN6TTY.js +133 -0
- package/dist/{chunk-7MBZYLME.js → chunk-B5XWYVWK.js} +1 -1
- package/dist/{chunk-5K4YG5DA.cjs → chunk-BGX27ZRG.cjs} +1 -1
- package/dist/{chunk-6J27P5D6.js → chunk-C2W5PSHC.js} +1 -1
- package/dist/chunk-CCUQZ66T.cjs +133 -0
- package/dist/chunk-EPMGPNBE.js +1 -0
- package/dist/chunk-FZ6Q2EBJ.cjs +20 -0
- package/dist/chunk-HQP2Y7QQ.js +251 -0
- package/dist/chunk-IFJ73O3A.cjs +1 -0
- package/dist/{chunk-HOP4D5XZ.cjs → chunk-J4252I5B.cjs} +5 -5
- package/dist/chunk-N5VNHUJS.cjs +4 -0
- package/dist/chunk-NZJAGASC.cjs +251 -0
- package/dist/{chunk-IKOXCJYO.js → chunk-Q2UYCYKV.js} +5 -5
- package/dist/{chunk-SZNM3F5V.js → chunk-QYFU5Y7S.js} +1 -1
- package/dist/{chunk-QBJT7XLN.cjs → chunk-TFBHE5FF.cjs} +1 -1
- package/dist/chunk-W7C6SJXZ.js +20 -0
- package/dist/chunk-ZIWJJRWQ.js +4 -0
- package/dist/cli/index.cjs +51 -90
- package/dist/cli/index.js +51 -90
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.d.cts +3 -1
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/graphql/index.d.cts +1 -1
- package/dist/graphql/index.d.ts +1 -1
- package/dist/{index-CqR97Q2L.d.ts → index-BeQtbl3z.d.ts} +2 -0
- package/dist/{index-DRNSjOte.d.cts → index-DTz6u7w9.d.cts} +2 -0
- package/dist/index.cjs +43 -25
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +43 -25
- package/dist/integration.cjs +1 -1
- package/dist/integration.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.d.cts +1 -1
- package/dist/rest/index.d.ts +1 -1
- package/dist/rest/index.js +1 -1
- package/dist/{sqlite-adapter-PLD57WOH.cjs → sqlite-adapter-GTTVSXRV.cjs} +1 -1
- package/dist/sqlite-adapter-UPANATIW.js +1 -0
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.js +1 -1
- package/package.json +2 -2
- package/dist/bootstrap-BGO2NFKB.cjs +0 -1
- package/dist/bootstrap-VVIT6YBP.js +0 -1
- package/dist/chunk-2YRM7CZZ.cjs +0 -251
- package/dist/chunk-4DJYAD4L.js +0 -251
- package/dist/chunk-4KFXG5ZB.cjs +0 -21
- package/dist/chunk-5KSRMBEO.js +0 -133
- package/dist/chunk-DZMIMB5W.js +0 -21
- package/dist/chunk-FUWPXR6W.cjs +0 -133
- package/dist/chunk-KKIBNWRL.cjs +0 -1
- package/dist/chunk-LCXPMPBU.js +0 -1
- package/dist/chunk-PTG24TQS.js +0 -20
- package/dist/chunk-YKIO34KG.cjs +0 -20
- package/dist/sqlite-adapter-EXYRYZEV.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkN5VNHUJS_cjs=require('./chunk-N5VNHUJS.cjs'),chunkTFBHE5FF_cjs=require('./chunk-TFBHE5FF.cjs'),chunkNZJAGASC_cjs=require('./chunk-NZJAGASC.cjs'),chunkJ4252I5B_cjs=require('./chunk-J4252I5B.cjs'),chunkCCUQZ66T_cjs=require('./chunk-CCUQZ66T.cjs'),chunkGYQMNXXW_cjs=require('./chunk-GYQMNXXW.cjs'),chunkQCA3AP3M_cjs=require('./chunk-QCA3AP3M.cjs'),g=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var g__default=/*#__PURE__*/_interopDefault(g);exports.a=null;var l=null;async function _(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let t=g__default.default.default||g__default.default,r=t.adapter,i=r&&!r.dialect&&typeof r.connect=="function";if(i&&globalThis.DB){let o=globalThis.DB;t.adapter=new chunkCCUQZ66T_cjs.c({type:"sqlite",client:o}),console.log("[Kyro API] Hot-swapped LocalAdapter for D1 DrizzleAdapter");}exports.a=chunkN5VNHUJS_cjs.z(t);let a=t.adapter,c=a&&a.dialect&&(a.dialect==="postgres"||a.dialect==="sqlite"),s=a&&a.dialect==="mongodb",e;if(c)a.dialect==="postgres"?e=new chunkGYQMNXXW_cjs.a({db:a.client}):a.dialect==="sqlite"&&(e=new chunkNZJAGASC_cjs.r({db:a.rawClient||a.client}));else if(i&&!globalThis.DB){let o=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";e=new chunkJ4252I5B_cjs.a({path:o});}else s&&(e=new chunkQCA3AP3M_cjs.a({db:a.client}));if(e?.connect)try{await e.connect();}catch(o){console.warn("[Kyro API] Auth connect warning:",o);}await exports.a.init();try{await exports.a.loadSettings();}catch(o){console.warn("[Kyro API] loadSettings warning:",o);}try{await chunkTFBHE5FF_cjs.d(e);}catch(o){console.warn("[Kyro API] autoBootstrap warning:",o);}globalThis.__KYRO_INSTANCE__=exports.a;}catch(t){throw exports.a=null,l=null,console.error("[Kyro API] Init failed, will retry:",t),t}}}async function b(t){let r=globalThis.DB?globalThis:null;if(t)try{r=t.locals?.runtime?.env||t.locals?.cfContext?.env||t?.env||r;}catch{}if(!r)try{r=process.env;}catch{}r?.DB&&(globalThis.DB=r.DB),r?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=r.STORAGE_BUCKET),l||(l=_()),await l;}var m={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function w(t){if(!exports.a)return m[t]??true;try{return (await exports.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.[t]??m[t]??!0}catch{return true}}var K=async t=>{if(!exports.a)try{await Promise.race([b(t),new Promise((s,e)=>setTimeout(()=>e(new Error("Initialization timeout")),3e4))]);}catch(s){return console.error("[Kyro API] Warm error:",s?.stack||s?.message||s),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}let i=new URL(t.request.url).pathname,a=__KYRO_API_PATH__;if(i===`${a}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!await w("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let e=await exports.a.getGraphQL().fetch(t.request,t.locals);return new Response(e.body,e)}if(i.startsWith(`${a}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!await w("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let e=await exports.a.getTRPC().fetch(t.request,t.locals);return new Response(e.body,e)}return exports.a.getREST().fetch(t.request,t.locals)};exports.b=b;exports.c=K;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var E=require('bcryptjs'),crypto=require('crypto'),fs=require('fs'),path=require('path'),module$1=require('module');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var E__default=/*#__PURE__*/_interopDefault(E);var c;function m(){return c||(c=module$1.createRequire("file:///")("node:sqlite").DatabaseSync,c)}var g=5e3,S=1e3,k=-64e3,A=268435456,l=class{db=null;path;saltRounds;externalDb;busyTimeout;walAutoCheckpoint;cacheSize;mmapSize;preparedStatements=new Map;constructor(e={}){this.path=e.path||"./data/auth.db",this.saltRounds=e.saltRounds||12,this.externalDb=!!e.db,this.busyTimeout=e.busyTimeout??g,this.walAutoCheckpoint=e.walAutoCheckpoint??S,this.cacheSize=e.cacheSize??k,this.mmapSize=e.mmapSize??A,e.db&&(this.db=e.db);}async connect(){if(this.db)return;let e=path.dirname(this.path);e&&e!=="."&&fs.mkdirSync(e,{recursive:true}),this.db=new(m())(this.path),this.db.exec(`PRAGMA busy_timeout = ${this.busyTimeout}`),this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA synchronous = NORMAL"),this.db.exec("PRAGMA cache_size = "+this.cacheSize),this.db.exec("PRAGMA mmap_size = "+this.mmapSize),this.db.exec("PRAGMA wal_autocheckpoint = "+this.walAutoCheckpoint),this.db.exec("PRAGMA foreign_keys = ON"),this.db.exec("PRAGMA temp_store = MEMORY"),this.ensureTables(),this.prepareStatements();}async disconnect(){this.db&&!this.externalDb&&(this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)"),this.db.close(),this.db=null,this.preparedStatements.clear());}async ensureConnected(){if(this.db||await this.connect(),!this.db)throw new Error("Failed to connect to SQLite database");return this.db}ensureTables(){if(this.db){this.db.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS kyro_users (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
name TEXT,
|
|
@@ -114,9 +114,9 @@
|
|
|
114
114
|
last_attempt = excluded.last_attempt,
|
|
115
115
|
locked_at = excluded.locked_at,
|
|
116
116
|
locked_until = excluded.locked_until
|
|
117
|
-
`)),this.preparedStatements.set("resetLockout",this.db.prepare("UPDATE kyro_lockouts SET attempts = 0, locked_at = NULL, locked_until = NULL WHERE user_id = ?")));}stmt(e){let s=this.preparedStatements.get(e);if(!s)throw new Error(`Prepared statement not found: ${e}`);return s}async cleanupExpiredSessions(){return await this.ensureConnected(),this.stmt("deleteExpiredSessions").run(new Date().toISOString()).changes}async cleanupOldAuditLogs(e=30){await this.ensureConnected();let s=new Date(Date.now()-e*24*60*60*1e3).toISOString();return this.stmt("cleanupOldAuditLogs").run(s).changes}async getStats(){await this.ensureConnected();let e=this.stmt("countUsers").get().count,s=this.db.prepare("SELECT COUNT(*) as count FROM kyro_sessions WHERE expires_at > ?").get(new Date().toISOString()).count,t=this.db.prepare("SELECT COUNT(*) as count FROM kyro_audit_logs").get().count;return {userCount:e,activeSessionCount:s,auditLogCount:t}}async createUser(e){await this.ensureConnected();let s=crypto.randomBytes(16).toString("hex"),t=new Date().toISOString(),r=await this.hashPassword(e.password),
|
|
118
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,
|
|
119
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(
|
|
117
|
+
`)),this.preparedStatements.set("resetLockout",this.db.prepare("UPDATE kyro_lockouts SET attempts = 0, locked_at = NULL, locked_until = NULL WHERE user_id = ?")));}stmt(e){let s=this.preparedStatements.get(e);if(!s)throw new Error(`Prepared statement not found: ${e}`);return s}async cleanupExpiredSessions(){return await this.ensureConnected(),this.stmt("deleteExpiredSessions").run(new Date().toISOString()).changes}async cleanupOldAuditLogs(e=30){await this.ensureConnected();let s=new Date(Date.now()-e*24*60*60*1e3).toISOString();return this.stmt("cleanupOldAuditLogs").run(s).changes}async getStats(){await this.ensureConnected();let e=this.stmt("countUsers").get().count,s=this.db.prepare("SELECT COUNT(*) as count FROM kyro_sessions WHERE expires_at > ?").get(new Date().toISOString()).count,t=this.db.prepare("SELECT COUNT(*) as count FROM kyro_audit_logs").get().count;return {userCount:e,activeSessionCount:s,auditLogCount:t}}async createUser(e){await this.ensureConnected();let s=crypto.randomBytes(16).toString("hex"),t=new Date().toISOString(),r=await this.hashPassword(e.password),n={id:s,name:e.name,email:e.email.toLowerCase(),passwordHash:r,role:e.role||"customer",avatar:e.avatar,tenantId:e.tenantId,createdAt:t,updatedAt:t};return this.db.prepare(`INSERT INTO kyro_users (id, name, email, password_hash, role, avatar, tenant_id, created_at, updated_at)
|
|
118
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,n.name||null,n.email,n.passwordHash,n.role,n.avatar||null,n.tenantId||null,t,t),n}async findUserByEmail(e){await this.ensureConnected();let s=this.stmt("findUserByEmail").get(e.toLowerCase());return s?this.rowToUser(s):null}async findUserById(e){await this.ensureConnected();let s=this.stmt("findUserById").get(e);return s?this.rowToUser(s):null}async updateUser(e,s){if(await this.ensureConnected(),!await this.findUserById(e))return null;let r=[],n=[];return s.email!==void 0&&(r.push("email = ?"),n.push(s.email.toLowerCase())),s.name!==void 0&&(r.push("name = ?"),n.push(s.name)),s.passwordHash!==void 0&&(r.push("password_hash = ?"),n.push(s.passwordHash)),s.role!==void 0&&(r.push("role = ?"),n.push(s.role)),s.avatar!==void 0&&(r.push("avatar = ?"),n.push(s.avatar)),s.tenantId!==void 0&&(r.push("tenant_id = ?"),n.push(s.tenantId)),s.emailVerified!==void 0&&(r.push("email_verified = ?"),n.push(s.emailVerified?1:0)),s.locked!==void 0&&(r.push("locked = ?"),n.push(s.locked?1:0)),s.lastLogin!==void 0&&(r.push("last_login = ?"),n.push(s.lastLogin)),s.failedLoginAttempts!==void 0&&(r.push("failed_login_attempts = ?"),n.push(s.failedLoginAttempts)),r.push("updated_at = ?"),n.push(new Date().toISOString()),n.push(e),this.db.prepare(`UPDATE kyro_users SET ${r.join(", ")} WHERE id = ?`).run(...n),this.findUserById(e)}async deleteUser(e){return await this.ensureConnected(),this.stmt("deleteUser").run(e).changes>0}async hashPassword(e){return E__default.default.hash(e,this.saltRounds)}async verifyPassword(e,s){await this.ensureConnected();let t=await this.findUserByEmail(e);if(!t)return null;let r=this.db.prepare("SELECT password_hash FROM kyro_users WHERE id = ?").get(t.id);return r?.password_hash&&await E__default.default.compare(s,r.password_hash)?t:null}async createSession(e,s={}){await this.ensureConnected();let t=crypto.randomBytes(32).toString("hex"),r=crypto.randomBytes(32).toString("base64url"),n=crypto.randomBytes(32).toString("base64url"),d=new Date,u=new Date(d.getTime()+864e5).toISOString(),i={id:t,userId:e,token:r,refreshToken:n,expiresAt:u,createdAt:d.toISOString(),ipAddress:s.ipAddress,userAgent:s.userAgent};return this.db.prepare(`INSERT INTO kyro_sessions (id, user_id, token, refresh_token, expires_at, created_at, ip_address, user_agent)
|
|
119
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(i.id,i.userId,i.token,i.refreshToken??null,i.expiresAt,i.createdAt,i.ipAddress??null,i.userAgent??null),i}async findSessionByToken(e){await this.ensureConnected();let s=this.stmt("findSessionByToken").get(e);return s?this.rowToSession(s):null}async findSessionByRefreshToken(e){await this.ensureConnected();let s=this.stmt("findSessionByRefreshToken").get(e);return s?this.rowToSession(s):null}async deleteSession(e){return await this.ensureConnected(),this.stmt("deleteSession").run(e,e).changes>0}async deleteUserSessions(e){return await this.ensureConnected(),this.stmt("deleteUserSessions").run(e).changes}async hasAnyUsers(){return await this.ensureConnected(),this.stmt("countUsers").get().count>0}async findUsers(e={}){await this.ensureConnected();let s=e.page??1,t=e.limit??10,r=(s-1)*t,n=e.search,d,u;if(n){let i=`%${n}%`;d=this.stmt("countUsersWithSearch").get(i).count,u=this.stmt("findUsersWithSearch").all(i,t,r);}else d=this.stmt("countUsers").get().count,u=this.stmt("findUsersPaginated").all(t,r);return {users:u.map(i=>this.rowToUser(i)),total:d}}async addPasswordToHistory(e,s){await this.ensureConnected(),this.stmt("addPasswordHistory").run(e,s,new Date().toISOString()),this.stmt("trimPasswordHistory").run(e);}async getPasswordHistory(e,s=5){return await this.ensureConnected(),this.stmt("getPasswordHistory").all(e,s).map(r=>r.password_hash)}async isPasswordInHistory(e,s,t=5){let r=await this.getPasswordHistory(s,t);for(let n of r)if(await E__default.default.compare(e,n))return true;return false}async recordFailedAttempt(e){await this.ensureConnected();let s=Date.now(),t=this.stmt("getLockout").get(e),r=(t?.attempts||0)+1,n=r>=5?s+900*1e3:t?.locked_until||null;this.stmt("upsertLockout").run(e,r,s,n!==null?s:null,n);}async resetAttempts(e){await this.ensureConnected(),this.stmt("resetLockout").run(e);}async checkLockout(e){await this.ensureConnected(),this.stmt("cleanupExpiredLockouts").run(Date.now());let s=this.stmt("getLockout").get(e);return s?s.locked_until!==null&&s.locked_until>Date.now()?{locked:true,attemptsRemaining:0,lockedUntil:new Date(s.locked_until),totalAttempts:s.attempts}:{locked:false,attemptsRemaining:Math.max(0,5-s.attempts),totalAttempts:s.attempts}:{locked:false,attemptsRemaining:5,totalAttempts:0}}async logAudit(e){await this.ensureConnected();let s=crypto.randomBytes(16).toString("hex"),t=new Date().toISOString();return this.db.prepare(`INSERT INTO kyro_audit_logs (
|
|
120
120
|
id, timestamp, action, user_id, user_email, role, resource, resource_id,
|
|
121
121
|
ip_address, user_agent, success, error, metadata, created_at
|
|
122
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,t,e.action,e.userId||null,e.userEmail||null,e.role||null,e.resource,e.resourceId||null,e.ipAddress||null,e.userAgent||null,e.success?1:0,e.error||null,e.metadata?JSON.stringify(e.metadata):null,new Date().toISOString()),s}async queryAuditLogs(e={}){await this.ensureConnected();let s=[],t=[];e.action&&(s.push("action = ?"),t.push(e.action)),e.userId&&(s.push("user_id = ?"),t.push(e.userId)),e.resource&&(s.push("resource = ?"),t.push(e.resource)),e.success!==void 0&&(s.push("success = ?"),t.push(e.success?1:0)),e.startDate&&(s.push("timestamp >= ?"),t.push(e.startDate.toISOString())),e.endDate&&(s.push("timestamp <= ?"),t.push(e.endDate.toISOString()));let r=s.length>0?"WHERE "+s.join(" AND "):"",
|
|
122
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,t,e.action,e.userId||null,e.userEmail||null,e.role||null,e.resource,e.resourceId||null,e.ipAddress||null,e.userAgent||null,e.success?1:0,e.error||null,e.metadata?JSON.stringify(e.metadata):null,new Date().toISOString()),s}async queryAuditLogs(e={}){await this.ensureConnected();let s=[],t=[];e.action&&(s.push("action = ?"),t.push(e.action)),e.userId&&(s.push("user_id = ?"),t.push(e.userId)),e.resource&&(s.push("resource = ?"),t.push(e.resource)),e.success!==void 0&&(s.push("success = ?"),t.push(e.success?1:0)),e.startDate&&(s.push("timestamp >= ?"),t.push(e.startDate.toISOString())),e.endDate&&(s.push("timestamp <= ?"),t.push(e.endDate.toISOString()));let r=s.length>0?"WHERE "+s.join(" AND "):"",n=e.limit||50,d=e.offset||0,u=this.db.prepare(`SELECT COUNT(*) as count FROM kyro_audit_logs ${r}`).get(...t),i=this.db.prepare(`SELECT * FROM kyro_audit_logs ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t,n,d);return {total:u.count,logs:i.map(a=>({id:a.id,timestamp:new Date(a.timestamp),action:a.action,userId:a.user_id||void 0,userEmail:a.user_email||void 0,resource:a.resource,resourceId:a.resource_id||void 0,ipAddress:a.ip_address||void 0,userAgent:a.user_agent||void 0,success:a.success===1,error:a.error||void 0,metadata:a.metadata?JSON.parse(a.metadata):void 0}))}}rowToUser(e){return {id:e.id,name:e.name||void 0,email:e.email,passwordHash:e.password_hash,role:e.role,tenantId:e.tenant_id,avatar:e.avatar,emailVerified:e.email_verified===1,locked:e.locked===1,lastLogin:e.last_login,failedLoginAttempts:e.failed_login_attempts||0,createdAt:e.created_at,updatedAt:e.updated_at}}rowToSession(e){return {id:e.id,userId:e.user_id,token:e.token,refreshToken:e.refresh_token,expiresAt:e.expires_at,createdAt:e.created_at,ipAddress:e.ip_address,userAgent:e.user_agent}}async findAuditLogs(e){let s=await this.queryAuditLogs({action:e.action,userId:e.userId,resource:e.resource,success:e.success,startDate:e.startDate,endDate:e.endDate,limit:e.limit,offset:e.offset});return {logs:s.logs.map(t=>({...t,action:t.action})),total:s.total}}async createAuditLog(e){let s=await this.logAudit({action:e.action,userId:e.userId,userEmail:e.userEmail,role:e.role,resource:e.resource,resourceId:e.resourceId,ipAddress:e.ipAddress,userAgent:e.userAgent,success:e.success,error:e.error,metadata:e.metadata}),t=this.db?.prepare("SELECT * FROM kyro_audit_logs WHERE id = ?").get(s);return {...e,id:s,timestamp:t?new Date(t.timestamp):new Date}}async createEmailVerificationToken(e){await this.ensureConnected();let s=crypto.randomBytes(16).toString("hex"),t=crypto.randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.db.prepare("INSERT INTO kyro_email_verifications (id, user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?, ?)").run(s,e,t,r.toISOString(),new Date().toISOString()),{token:t,expiresAt:r}}async verifyEmailToken(e){await this.ensureConnected();let s=this.db.prepare("SELECT * FROM kyro_email_verifications WHERE token = ?").get(e);return s?new Date(s.expires_at)<new Date?{success:false,error:"Verification token has expired"}:(this.db.prepare("UPDATE kyro_users SET email_verified = 1 WHERE id = ?").run(s.user_id),this.db.prepare("DELETE FROM kyro_email_verifications WHERE id = ?").run(s.id),{success:true,userId:s.user_id}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){await this.ensureConnected();let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let t=crypto.randomBytes(16).toString("hex"),r=crypto.randomBytes(32).toString("hex"),n=new Date(Date.now()+3600*1e3);return this.db.prepare("INSERT INTO kyro_password_resets (id, user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?, ?)").run(t,s.id,r,n.toISOString(),new Date().toISOString()),{token:r,expiresAt:n}}async resetPasswordWithToken(e,s){await this.ensureConnected();let t=this.db.prepare("SELECT * FROM kyro_password_resets WHERE token = ?").get(e);if(!t)return {success:false,error:"Invalid reset token"};if(new Date(t.expires_at)<new Date)return {success:false,error:"Reset token has expired"};if(t.used_at)return {success:false,error:"Reset token has already been used"};let r=await this.hashPassword(s);return this.db.prepare("UPDATE kyro_users SET password_hash = ?, updated_at = ? WHERE id = ?").run(r,new Date().toISOString(),t.user_id),this.db.prepare("UPDATE kyro_password_resets SET used_at = ? WHERE id = ?").run(new Date().toISOString(),t.id),this.db.prepare("DELETE FROM kyro_sessions WHERE user_id = ?").run(t.user_id),{success:true}}};exports.a=l;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var chunk4IGWJMBY_cjs=require('./chunk-4IGWJMBY.cjs'),chunkKD7LUCFY_cjs=require('./chunk-KD7LUCFY.cjs'),chunkZUVP4UK7_cjs=require('./chunk-ZUVP4UK7.cjs'),chunkHS2KNFAB_cjs=require('./chunk-HS2KNFAB.cjs'),chunkNZJAGASC_cjs=require('./chunk-NZJAGASC.cjs'),chunkILEZ3NYX_cjs=require('./chunk-ILEZ3NYX.cjs'),chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkG3J2EU5D_cjs=require('./chunk-G3J2EU5D.cjs'),chunkCCUQZ66T_cjs=require('./chunk-CCUQZ66T.cjs'),chunkMIOMMB23_cjs=require('./chunk-MIOMMB23.cjs'),zod=require('zod'),graphqlYoga=require('graphql-yoga');function T(s,e){for(let t of s){if(t.name===e)return true;if("tabs"in t&&t.tabs){for(let i of t.tabs)if(T(i.fields,e))return true}if("fields"in t&&t.fields&&T(t.fields,e))return true}return false}var K=class extends Error{errors;constructor(e){super(`Configuration validation failed:
|
|
2
|
+
${e.join(`
|
|
3
|
+
`)}`),this.name="ConfigValidationError",this.errors=e;}};function I(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Collection slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Collection "${s.slug}" has no fields defined`);else {let t=m(s.fields,s.slug);e.push(...t);}if(s.access)for(let[t,i]of Object.entries(s.access))typeof i!="boolean"&&typeof i!="function"&&e.push(`Collection "${s.slug}" has invalid access.${t} (must be boolean or function)`);if(s.admin?.useAsTitle&&(T(s.fields,s.admin.useAsTitle)||e.push(`Collection "${s.slug}" admin.useAsTitle references unknown field "${s.admin.useAsTitle}"`)),s.admin?.defaultColumns)for(let t of s.admin.defaultColumns)T(s.fields,t)||e.push(`Collection "${s.slug}" admin.defaultColumns references unknown field "${t}"`);if(s.upload&&s.upload.fileSize&&s.upload.fileSize<=0&&e.push(`Collection "${s.slug}" upload.fileSize must be positive`),s.versions&&s.versions.maxPerDoc&&s.versions.maxPerDoc<=0&&e.push(`Collection "${s.slug}" versions.maxPerDoc must be positive`),s.auth){let t=s.fields.some(o=>o.name==="email"),i=s.fields.some(o=>o.name==="password");t||e.push(`Collection "${s.slug}" with auth enabled requires an "email" field`),i||e.push(`Collection "${s.slug}" with auth enabled requires a "password" field`);}return e}function D(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Global slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Global "${s.slug}" has no fields defined`);else {let t=m(s.fields,`global:${s.slug}`);e.push(...t);}return e}function m(s,e){let t=[],i=new Set;for(let o=0;o<s.length;o++){let n=s[o];if(n.type==="row"||n.type==="collapsible"||n.type==="tabs"){if("fields"in n&&n.fields){let l=m(n.fields,e);t.push(...l);}else if("tabs"in n)for(let l of n.tabs){let c=m(l.fields,e);t.push(...c);}continue}let a=n.name;if(!a){t.push(`${e}: Field at index ${o} is missing a "name" property`);continue}if(i.has(a)&&t.push(`${e}: Duplicate field name "${a}"`),i.add(a),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(a)||t.push(`${e}: Field name "${a}" must be alphanumeric with underscores`),!n.type){t.push(`${e}: Field "${a}" is missing a "type" property`);continue}switch(n.type){case "relationship":n.relationTo||t.push(`${e}: Relationship field "${a}" is missing "relationTo"`);break;case "array":if(!n.fields||n.fields.length===0)t.push(`${e}: Array field "${a}" has no fields defined`);else {let l=m(n.fields,`${e}.${a}`);t.push(...l);}break;case "group":if(!n.fields||n.fields.length===0)t.push(`${e}: Group field "${a}" has no fields defined`);else {let l=m(n.fields,`${e}.${a}`);t.push(...l);}break;case "blocks":if(!n.blocks||n.blocks.length===0)t.push(`${e}: Blocks field "${a}" has no blocks defined`);else {let l=Ae(n.blocks,`${e}.${a}`);t.push(...l);}break;case "select":case "radio":if(typeof n.options=="function")break;if((!n.options||n.options.length===0)&&!n.dynamicOptions)t.push(`${e}: ${n.type} field "${a}" has no options defined`);else if(Array.isArray(n.options)){let l=n.options.map(f=>f.value),c=new Set(l);l.length!==c.size&&t.push(`${e}: ${n.type} field "${a}" has duplicate option values`);}break;case "upload":n.relationTo||t.push(`${e}: Upload field "${a}" is missing "relationTo"`);break}"min"in n&&"max"in n&&n.min>n.max&&t.push(`${e}: Field "${a}" has min greater than max`),"minLength"in n&&"maxLength"in n&&n.minLength>n.maxLength&&t.push(`${e}: Field "${a}" has minLength greater than maxLength`),"minRows"in n&&"maxRows"in n&&n.minRows>n.maxRows&&t.push(`${e}: Field "${a}" has minRows greater than maxRows`);}return t}function Ae(s,e){let t=[],i=new Set;for(let o of s){if(!o.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(i.has(o.slug)&&t.push(`${e}: Duplicate block slug "${o.slug}"`),i.add(o.slug),o.label||t.push(`${e}: Block "${o.slug}" is missing a "label" property`),!o.fields||o.fields.length===0)t.push(`${e}: Block "${o.slug}" has no fields defined`);else {let n=m(o.fields,`${e}.${o.slug}`);t.push(...n);}}return t}function de(s,e=[]){let t=[],i=new Set;for(let o of s)i.has(o.slug)&&t.push(`Duplicate collection slug "${o.slug}"`),i.add(o.slug);for(let o of e)i.has(o.slug)&&t.push(`Duplicate global slug "${o.slug}"`),i.add(o.slug);for(let o of s){let n=I(o);t.push(...n);}for(let o of e){let n=D(o);t.push(...n);}for(let o of s){let n=S(o.fields,s);t.push(...n);}if(t.length>0)throw new K(t)}function S(s,e){let t=[],i=new Set(e.map(o=>o.slug));for(let o of s){if(o.type==="relationship"){let n=Array.isArray(o.relationTo)?o.relationTo:[o.relationTo];for(let a of n)a!=="*"&&!i.has(a)&&console.warn(`[Kyro Config Warning]: Relationship field "${o.name}" references unknown collection "${a}". Select options will not be available until this collection is registered.`);}if(o.type==="upload"){let n=Array.isArray(o.relationTo)?o.relationTo:[o.relationTo];for(let a of n)i.has(a)||t.push(`Upload field "${o.name}" references unknown collection "${a}"`);}if("fields"in o&&o.fields){let n=S(o.fields,e);t.push(...n);}if("tabs"in o)for(let n of o.tabs){let a=S(n.fields,e);t.push(...a);}if("blocks"in o)for(let n of o.blocks){let a=S(n.fields,e);t.push(...a);}}return t}function u(s){switch(s.type){case "text":return Se(s);case "number":return Te(s);case "checkbox":return ke(s);case "date":return Re(s);case "email":return Pe(s);case "password":return Fe(s);case "textarea":return Ze(s);case "select":return je(s);case "radio":return $e(s);case "color":return qe(s);case "richtext":return Ee(s);case "json":return Ke(s);case "code":return Ie(s);case "upload":return ue(s);case "image":return ue(s);case "markdown":return De(s);case "relationship":return pe(s);case "relationship-block":return pe(s);case "array":return Oe(s);case "list":return Ge(s);case "group":return Ne(s);case "blocks":return Ue(s);case "row":return Le(s);case "collapsible":return ze(s);case "tabs":return _e(s);default:return zod.z.any()}}function Se(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.pattern&&(e=e.regex(new RegExp(s.pattern))),s.variant==="email"&&(e=e.email()),s.variant==="url"&&(e=e.url()),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function Te(s){let e=s.integer?zod.z.coerce.number().int():zod.z.coerce.number();return s.min!==void 0&&(e=e.min(s.min)),s.max!==void 0&&(e=e.max(s.max)),s.step&&(e=e.refine(t=>Number.isInteger(t/s.step),`Value must be divisible by ${s.step}`)),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function ke(s){let e=zod.z.boolean();return s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function Re(s){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return s.minDate&&(e=e.refine(t=>new Date(t)>=new Date(s.minDate),`Date must be after ${s.minDate}`)),s.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(s.maxDate),`Date must be before ${s.maxDate}`)),s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function Pe(s){let e=zod.z.string().email("Invalid email");return s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function Fe(s){let e=zod.z.string().min(6,"Password must be at least 6 characters");return s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function Ze(s){let e=zod.z.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function je(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(i=>i.value);s.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=s.hasMany?zod.z.array(zod.z.string()):zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function $e(s){let e;if(Array.isArray(s.options)&&s.options.length>0){let t=s.options.map(i=>i.value);e=zod.z.enum(t);}else e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function qe(s){let e=zod.z.string();return s.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),s.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),s.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function Ee(s){let e=zod.z.array(zod.z.record(zod.z.any()));return s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function Ke(s){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function Ie(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function ue(s){let e;if(s.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function De(s){let e=zod.z.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function pe(s){let e;return Array.isArray(s.relationTo)?e=zod.z.object({relationTo:zod.z.enum(s.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),s.hasMany&&(e=zod.z.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=d(e,s.validate)),e}function Oe(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(i=>i.name).map(i=>[i.name,u(i)]))).passthrough(),t=zod.z.array(e);return s.minRows&&(t=t.min(s.minRows)),s.maxRows&&(t=t.max(s.maxRows)),s.required||(t=t.optional().nullable()),s.validate&&(t=d(t,s.validate)),t}function Ge(s){let e=zod.z.array(zod.z.string());return s.required||(e=e.optional().nullable()),e}function Ne(s){let e=zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,u(t)])));return s.required?e:e.optional().nullable()}function Ue(s){let e=s.blocks||[];e.map(n=>zod.z.object({blockType:zod.z.literal(n.slug),...Object.fromEntries(n.fields.filter(a=>a.name).map(a=>[a.name,u(a)]))}));let i=e.map(n=>n.slug),o;if(i.length>0){let n=zod.z.object({blockType:zod.z.enum(i)}).catchall(zod.z.any()),a=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());o=zod.z.array(zod.z.union([n,a,zod.z.record(zod.z.any())]));}else o=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return s.minRows&&(o=o.min(s.minRows)),s.maxRows&&(o=o.max(s.maxRows)),s.required||(o=o.optional().nullable()),s.validate&&(o=d(o,s.validate)),o}function Le(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,u(t)])))}function ze(s){return zod.z.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,u(t)])))}function _e(s){let e={};for(let t of s.tabs)for(let i of t.fields)i.name&&(e[i.name]=u(i));return zod.z.object(e).passthrough().optional()}function d(s,e){return s.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function C(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let i={};for(let o of t.tabs){let n=C(o.fields);Object.assign(i,n);}t.name?e[t.name]=zod.z.object(i).passthrough().optional():Object.assign(e,i);}else if(t.type==="row"&&"fields"in t){let i=C(t.fields);t.name?e[t.name]=zod.z.object(i).passthrough().optional():Object.assign(e,i);}else if(t.type==="collapsible"&&"fields"in t){let i=C(t.fields);t.name?e[t.name]=zod.z.object(i).passthrough().optional():Object.assign(e,i);}else {if(!t.name)continue;e[t.name]=u(t);}return e}function y(s){let e={};for(let t of s)if(t.type==="tabs"&&"tabs"in t){let i={};for(let o of t.tabs){let n=y(o.fields);Object.assign(i,n);}t.name?e[t.name]=zod.z.object(i).passthrough().optional().nullable():Object.assign(e,i);}else if(t.type==="row"&&"fields"in t){let i=y(t.fields);t.name?e[t.name]=zod.z.object(i).passthrough().optional().nullable():Object.assign(e,i);}else if(t.type==="collapsible"&&"fields"in t){let i=y(t.fields);t.name?e[t.name]=zod.z.object(i).passthrough().optional().nullable():Object.assign(e,i);}else if(t.type==="group"&&"fields"in t)t.name?e[t.name]=zod.z.object(y(t.fields)).passthrough().optional().nullable():Object.assign(e,y(t.fields));else {if(!t.name)continue;e[t.name]=u(t).optional().nullable();}return e}function fe(s){let e=C(s.fields);return s.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),s.tenantScoped&&(e.tenantId=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function ye(s){let e=C(s.fields);return zod.z.object(e).passthrough()}function ge(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let i={};for(let o of t.tabs)for(let n of o.fields)n.name&&(i[n.name]=u(n).optional().nullable());e[t.name]=zod.z.object(i).optional().nullable();}else if(t.type==="row"&&"fields"in t){let i={};for(let o of t.fields)o.name&&(i[o.name]=u(o).optional().nullable());Object.assign(e,i);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(y(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(y(t.fields)).optional().nullable():e[t.name]=u(t).optional().nullable();return zod.z.object(e).passthrough()}function he(s){let e={};for(let t of s.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function me(s){let e=C(s.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function be(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let i={};for(let o of t.tabs)for(let n of o.fields)n.name&&(i[n.name]=u(n).optional().nullable());e[t.name]=zod.z.object(i).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(y(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(y(t.fields)).optional().nullable():e[t.name]=u(t).optional().nullable();return zod.z.object(e).passthrough()}var w=class{storageProviders=chunkNZJAGASC_cjs.f();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e,fields:[...e.fields]};for(let o of this.plugins){let n=o.extensions?.collections?.find(a=>a.slug===t.slug);n&&(t={...t,...n.config,fields:[...t.fields,...n.config.fields||[]]});}if(t.seo){let o=chunkKD7LUCFY_cjs.a(),n=t.fields.findIndex(a=>a.type==="tabs");if(n!==-1){let a=t.fields[n];t.fields[n]={...a,tabs:[...a.tabs,{label:"SEO Settings",fields:o.fields}]};}else t.fields.push(o);}t.fields=this.applyFieldDefaults(t);let i=I(t);if(i.length>0)throw new Error(`Invalid collection config: ${i.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=D(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let i={...e};for(let o of this.plugins){let n=o.extensions?.globals?.find(a=>a.slug===i.slug);n&&(i={...i,...n.config,fields:[...i.fields||[],...n.config.fields||[]]});}this.globals.set(i.slug,i),this.clearSchemaCache(`global:${i.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let i=this.collections.get(e);if(i){let n=fe(i);return this.schemaCache.set(e,n),n}let o=this.globals.get(e);if(o){let n=me(o);return this.schemaCache.set(`global:${e}`,n),n}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,i=this.schemaCache.get(t);if(i)return i;let o=this.collections.get(e);if(o){let n=ye(o);return this.schemaCache.set(t,n),n}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,i=this.schemaCache.get(t);if(i)return i;let o=this.collections.get(e);if(o){let a=ge(o);return this.schemaCache.set(t,a),a}let n=this.globals.get(e);if(n){let a=be(n);return this.schemaCache.set(`global:${e}:update`,a),a}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,i=this.schemaCache.get(t);if(i)return i;let o=this.collections.get(e);if(o){let n=he(o);return this.schemaCache.set(t,n),n}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return u(e)}clearSchemaCache(e){this.schemaCache.delete(e),this.schemaCache.delete(`${e}:create`),this.schemaCache.delete(`${e}:update`),this.schemaCache.delete(`${e}:where`);}applyFieldDefaults(e){let t=[...e.fields];return t.some(i=>i.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(i=>i.name==="tenantId")&&t.push({name:"tenantId",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(i=>i.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(i=>i.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(i=>i.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let i=this.globals.get(e);if(i)return i.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),i=new Map,o=n=>{for(let a of n){if(a.name&&i.set(a.name,a),"fields"in a&&a.fields&&o(a.fields),"tabs"in a)for(let l of a.tabs)o(l.fields);if("blocks"in a)for(let l of a.blocks)o(l.fields);}};return o(t),i}getVisibleFields(e){return this.getFields(e).filter(i=>!i.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();de(e,t);}async init(e){this.validate();for(let t of this.plugins){t.init&&await t.init(e||this);let i=t.collections||[];for(let n of i)n.slug&&!this.hasCollection(n.slug)&&this.addCollection(n);let o=t.globals||[];for(let n of o)n.slug&&!this.hasGlobal(n.slug)&&this.addGlobal(n);}this.initialized=true;}isInitialized(){return this.initialized}getPaginationDefaults(e){let t=this.collections.get(e);return {defaultLimit:t?.admin?.pagination?.defaultLimit||10,limits:t?.admin?.pagination?.limits||[10,25,50,100]}}getDefaultSort(e){let i=this.collections.get(e)?.admin?.useAsTitle;return i||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(o=>o.name)}getAdminTitle(e){let t=this.collections.get(e);return t?.label||t?.admin?.description||e}getAdminLabel(e){let t=this.collections.get(e);return t?.singularLabel||t?.label||e}getAdminGroup(e){return this.collections.get(e)?.admin?.group}getStats(){let e=0;for(let t of this.collections.values())e+=t.fields.length;for(let t of this.globals.values())e+=t.fields.length;return {collections:this.collections.size,globals:this.globals.size,plugins:this.plugins.length,fields:e}}toJSON(){return {collections:this.getCollections(),globals:this.getGlobals()}}},v=null;function He(){return v||(v=new w),v}function Me(){v=null;}function O(){return v=new w,v}var p=class{name;displayName;adminEntry;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},k=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[i,o]of Object.entries(t))if(Array.isArray(o))for(let n of o)this.registerHook(i,n);}unregister(e){let t=this.plugins.get(e);if(!t)return;let i=t.getHooks?.()||{};for(let[o,n]of Object.entries(i))if(Array.isArray(n))for(let a of n)this.unregisterHook(o,a);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let i=this.hooks.get(e);if(i){let o=i.indexOf(t);o>-1&&i.splice(o,1);}}async executeHook(e,t){let i=this.hooks.get(e)||[],o=t;for(let n of i)try{let a=await n({...t,data:o});a!==void 0&&(o=a);}catch(a){console.error(`[PluginManager] Error in hook "${e}":`,a);}return o}getAllCollections(){let e=[];for(let t of this.plugins.values()){let i=t.getCollections?.()||[];e.push(...i);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let i=t.getGlobals?.()||[];e.push(...i);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},G=class extends p{constructor(){super("seo"),this.displayName="Core SEO",this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.adminEntry="@kyro-cms/admin/plugins/seo-admin",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},N=class extends p{constructor(){super("analytics"),this.displayName="Core Analytics",this.description="Built-in privacy-friendly analytics and dashboards",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},U=class extends p{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},L=class extends p{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},z=class extends p{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},ct={SEO:G,Analytics:N,Comments:U,Reviews:L,Wishlist:z};var Ve={aws:{type:"aws",configKey:"s3",displayName:"S3 Compatible (AWS, Backblaze, Wasabi, etc.)",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1",admin:{placeholder:"us-east-1"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"endpoint",type:"text",label:"Endpoint URL",admin:{placeholder:"https://s3.custom.com"}},{name:"cdnUrl",type:"text",label:"CDN URL",admin:{placeholder:"https://cdn.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}]},r2:{type:"r2",configKey:"r2",displayName:"Cloudflare R2",configFields:[{name:"accountId",type:"text",label:"Account ID",required:true,admin:{placeholder:"Your Cloudflare Account ID"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"publicDevUrl",type:"text",label:"Public Dev URL ID",admin:{placeholder:"pub-xxxxxxxxxxxxxxxx",description:"Enter ONLY the ID (e.g., pub-b8d8c4cc8bcf4d868ddd95efc1b305aa). Do NOT include https:// or the full URL. Found in R2 Dashboard \u2192 Public Dev URL."}},{name:"cdnUrl",type:"text",label:"Custom CDN URL",admin:{placeholder:"https://assets.example.com (optional)"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads (optional)",description:"Optional prefix for all object keys. Do not use '/' as prefix."}}]},gcs:{type:"gcs",configKey:"gcs",displayName:"Google Cloud Storage",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"projectId",type:"text",label:"Project ID"},{name:"clientEmail",type:"text",label:"Client Email"},{name:"privateKey",type:"password",label:"Private Key"},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},digitalocean:{type:"digitalocean",configKey:"digitalocean",displayName:"DigitalOcean Spaces",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"nyc3"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},backblaze:{type:"backblaze",configKey:"backblaze",displayName:"Backblaze B2",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"accountId",type:"text",label:"Account ID"},{name:"applicationKeyId",type:"text",label:"Application Key ID",required:true},{name:"applicationKey",type:"password",label:"Application Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},wasabi:{type:"wasabi",configKey:"wasabi",displayName:"Wasabi",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]}};function Be(s,e){switch(s){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function xe(s,e){return {provider:s,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:Be(s,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function We(s,e,t){let i=t[e.configKey]||{};return xe(s,i)}function Je(s,e,t){let i=t?.[e.configKey]||t;return xe(s,i)}var _=class extends p{constructor(){super("@kyro-cms/storage-s3"),this.version="1.0.0",this.description="S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)";}async init(e){let t=e.registry?.storageProviders;if(!t)return;let i=this.name;for(let o of Object.values(Ve))t.register({type:o.type,displayName:o.displayName,pluginName:i,configKey:o.configKey,configFields:o.configFields,extractConfig:n=>We(o.type,o,n),extractRawConfig:n=>Je(o.type,o,n),factory:n=>chunkNZJAGASC_cjs.a(n)});}},Ce=new _;var H=class extends p{constructor(){super("@kyro-cms/storage-cloudinary"),this.version="1.0.0",this.description="Cloudinary image and video storage";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"cloudinary",displayName:"Cloudinary",pluginName:this.name,configKey:"cloudinary",configFields:[{name:"cloudName",type:"text",label:"Cloud Name",required:true},{name:"apiKey",type:"text",label:"API Key",required:true},{name:"apiSecret",type:"password",label:"API Secret",required:true},{name:"folder",type:"text",label:"Folder",admin:{placeholder:"Optional folder path"}},{name:"uploadPreset",type:"text",label:"Upload Preset (optional)",admin:{placeholder:"Leave empty for signed uploads",description:"If not set, uploads will be signed with API Secret"}}],extractConfig:i=>({cloudName:i.cloudinary?.cloudName||"",apiKey:i.cloudinary?.apiKey||"",apiSecret:i.cloudinary?.apiSecret||"",folder:i.cloudinary?.folder,uploadPreset:i.cloudinary?.uploadPreset}),extractRawConfig:i=>{let o=i?.cloudinary||i;return {cloudName:o?.cloudName||"",apiKey:o?.apiKey||"",apiSecret:o?.apiSecret||"",folder:o?.folder,uploadPreset:o?.uploadPreset}},factory:i=>chunkNZJAGASC_cjs.b(i)});}},ve=new H;var M=class extends p{constructor(){super("@kyro-cms/storage-ftp"),this.version="1.0.0",this.description="FTP/SFTP storage provider";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"ftp",displayName:"FTP",pluginName:this.name,configKey:"ftp",configFields:[{name:"host",type:"text",label:"Host",required:true,admin:{placeholder:"ftp.example.com"}},{name:"port",type:"number",label:"Port",defaultValue:21,admin:{placeholder:"21 for FTP"}},{name:"user",type:"text",label:"Username",required:true},{name:"password",type:"password",label:"Password",required:true},{name:"secure",type:"checkbox",label:"Use TLS/SSL",defaultValue:false,admin:{description:"Enable TLS/SSL for secure connections (FTP only)"}},{name:"baseUrl",type:"text",label:"Base URL",required:true,admin:{placeholder:"https://files.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}],extractConfig:i=>({host:i.ftp?.host||"",port:i.ftp?.port||21,user:i.ftp?.user||"",password:i.ftp?.password||"",secure:i.ftp?.secure||false,baseUrl:i.ftp?.baseUrl||"",prefix:i.ftp?.prefix,type:"ftp"}),extractRawConfig:i=>{let o=i?.ftp||i;return {host:o?.host||"",port:o?.port||21,user:o?.user||"",password:o?.password||"",secure:o?.secure||false,baseUrl:o?.baseUrl||"",prefix:o?.prefix,type:"ftp"}},factory:i=>chunkNZJAGASC_cjs.c(i)});}},we=new M;var Qe=[Ce,ve,we];function b(s,e,t){let i=e.split(".");if(i.length===0)return false;let o=i[0],n=i.slice(1).join(".");for(let a of s)if(a.name===o)if(n){if(a.fields&&Array.isArray(a.fields))return b(a.fields,n,t);if(a.type==="tabs"&&a.tabs&&Array.isArray(a.tabs)){for(let l of a.tabs)if(l.fields&&Array.isArray(l.fields)&&b(l.fields,n,t))return true;return false}if(a.type==="blocks"&&a.blocks&&Array.isArray(a.blocks)){let l=n.split(".")[0],c=n.split(".").slice(1).join(".");if(!c)return false;for(let f of a.blocks)if(f.slug===l&&f.fields&&Array.isArray(f.fields))return b(f.fields,c,t);return false}return a.type==="array"&&a.fields&&Array.isArray(a.fields)?b(a.fields,n,t):false}else return Object.assign(a,t),true;for(let a of s)if(!a.name||a.type==="tabs"||a.type==="row"||a.type==="collapsible"){if(a.fields&&Array.isArray(a.fields)&&b(a.fields,e,t))return true;if(a.type==="tabs"&&a.tabs&&Array.isArray(a.tabs)){for(let c of a.tabs)if(c.fields&&Array.isArray(c.fields)&&b(c.fields,e,t))return true}}return n?false:(s.push({name:o,...t}),true)}function Xe(s,e){if(e)for(let t of s){let i=e[t.slug];if(i){let{fields:o,...n}=i;if(t.admin={...t.admin,...n},o&&t.fields&&Array.isArray(t.fields))for(let[a,l]of Object.entries(o))b(t.fields,a,l);}}}var V=class{registry;db;pubsub;webhookService;settings;pluginManager;wsServer;config;constructor(e){this.config=e,this.registry=O(),this.db=e.adapter||e.db,this.pubsub=new chunkG3J2EU5D_cjs.b(this.registry),this.webhookService=chunkILEZ3NYX_cjs.o(this.db),this.pluginManager=new k;for(let t of Qe)this.pluginManager.register(t),this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.pluginManager.register(t),this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&Xe(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.pluginManager.executeHook("beforeInit",{kyro:this}),await this.registry.init(this),await this.pluginManager.executeHook("afterInit",{kyro:this}),this.registry.addGlobalPostInit(chunk4IGWJMBY_cjs.a);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:chunkNY47CFVP_cjs.d,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},i={slug:chunkILEZ3NYX_cjs.f,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},o={slug:chunkILEZ3NYX_cjs.g,fields:[{name:"webhookId",type:"text",required:true},{name:"event",type:"text",required:true},{name:"payload",type:"json",required:true},{name:"attempt",type:"number",required:true},{name:"status",type:"text",required:true},{name:"responseStatus",type:"number"},{name:"responseBody",type:"text"},{name:"error",type:"text"},{name:"duration",type:"number"},{name:"deliveredAt",type:"date"},{name:"nextRetryAt",type:"date"}]},n=this.registry.getGlobals();if(this.db instanceof chunkCCUQZ66T_cjs.c&&this.db.dialect==="postgres"){let a=this.db,l=chunkNY47CFVP_cjs.d.replace(/-/g,"_");a.schema[l]||(a.schema[l]=chunkMIOMMB23_cjs.g);}await this.db.init([...this.registry.getCollections(),t,i,o],n),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),i={};try{let o=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});o&&o.states&&(i=o.states);}catch{}for(let o of t)i[o]!==void 0&&e.setPluginEnabled(o,i[o]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,i=t?.secret,o=t?.checkSession!==false;return chunkNZJAGASC_cjs.u({registry:this.registry,db:this.db,authSecret:i,authAdapter:this.config.authAdapter,checkSession:o,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunkHS2KNFAB_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:o})=>{let n=chunkNY47CFVP_cjs.f(o),a,l;if(n&&this.db){let f=await chunkNY47CFVP_cjs.e(n,this.db);f.user&&(a=f.user,l=chunkNY47CFVP_cjs.g(f));}let c=e?.tenantId;return {db:this.db,registry:this.registry,user:a,req:o,tenantId:c,apiKey:l,relationLoader:new chunkHS2KNFAB_cjs.a({db:this.db,tenantId:c,user:a})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,i)=>{let n=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[a,...l]=n.split("."),c=l.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!a||!c)return new Response(JSON.stringify({error:{message:"Invalid tRPC path",code:-32600,data:{code:"BAD_REQUEST",httpStatus:400}}}),{status:400,headers:{"Content-Type":"application/json"}});let f=await chunkZUVP4UK7_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),B=chunkZUVP4UK7_cjs.i(f)[a];if(!B)return new Response(JSON.stringify({error:{message:`Collection '${a}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let W=B[c];if(typeof W!="function")return new Response(JSON.stringify({error:{message:`Procedure '${c}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let x={};if(t.method==="POST"||t.method==="PATCH")x=await t.json().catch(()=>({}));else {let A=new URL(t.url).searchParams.get("input");if(A)try{x=JSON.parse(decodeURIComponent(A));}catch{}}let g=x?.["0"]??x,h=await W({...g,collection:a});return new Response(JSON.stringify({result:{data:h}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(x){let g=x.message||"Internal error",h=g.includes("not found")?404:g.includes("denied")||g.includes("authentication required")?403:g.includes("conflict")?409:500,A=h===404?-32601:h===403?-32001:h===409?-32002:-32603;return new Response(JSON.stringify({error:{message:g,code:A,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:h}}}),{status:h,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let i=async n=>{let a=await chunkNY47CFVP_cjs.e(n,this.db);if(!a.valid)throw new Error(a.error||"Invalid API key");if(!a.user)throw new Error("API key has no associated user");return a.user},o=e?.port||8080;if(globalThis.__KYRO_WS_SERVER__)try{await globalThis.__KYRO_WS_SERVER__.close();}catch{}return this.wsServer=chunkG3J2EU5D_cjs.d({pubsub:this.pubsub,port:o,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||i}),globalThis.__KYRO_WS_SERVER__=this.wsServer,this.wsServer}async shutdown(){await this.pluginManager.executeHook("beforeServerStop",{kyro:this}),this.wsServer&&await this.wsServer.close(),await this.db.disconnect(),await this.pluginManager.executeHook("afterServerStop",{kyro:this});}};function Lt(s){return new V(s)}
|
|
4
|
+
exports.a=K;exports.b=I;exports.c=D;exports.d=m;exports.e=de;exports.f=u;exports.g=fe;exports.h=ye;exports.i=ge;exports.j=he;exports.k=me;exports.l=w;exports.m=He;exports.n=Me;exports.o=O;exports.p=p;exports.q=k;exports.r=G;exports.s=N;exports.t=U;exports.u=L;exports.v=z;exports.w=ct;exports.x=Xe;exports.y=V;exports.z=Lt;
|