@kyro-cms/core 0.11.2 → 0.11.4
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/{WebhookService-neHWRdFM.d.ts → WebhookService-BU7tpsju.d.ts} +1 -1
- package/dist/{WebhookService-DvP8e4Gb.d.cts → WebhookService-C-AiI-mY.d.cts} +1 -1
- 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.js +1 -1
- package/dist/{base-CH7d01Yw.d.cts → base-Belr0_tE.d.cts} +2 -2
- package/dist/{base-DRK_7V46.d.ts → base-D5VkUbPm.d.ts} +2 -2
- package/dist/{chunk-Q4CSLXCO.cjs → chunk-5BOHALPJ.cjs} +2 -2
- package/dist/chunk-5KHTAW4H.cjs +86 -0
- package/dist/chunk-7ORSLR3S.js +2 -0
- package/dist/chunk-AYCQ3E7K.js +21 -0
- package/dist/chunk-CC7UIA4Y.cjs +21 -0
- package/dist/chunk-DNLO7PK6.cjs +2 -0
- package/dist/{chunk-62Y4NYMH.cjs → chunk-H6K44OUB.cjs} +1 -1
- package/dist/{chunk-GDMLWVJO.js → chunk-MTFJDAPX.js} +6 -6
- package/dist/{chunk-NGBJKZMT.js → chunk-NJS6FLXT.js} +2 -2
- package/dist/chunk-O6WZLSKJ.js +86 -0
- package/dist/chunk-O7FYIPJW.cjs +2 -0
- package/dist/{chunk-RLDAQ7IH.cjs → chunk-QAJS4EXW.cjs} +7 -7
- package/dist/chunk-XQPYBNIT.js +2 -0
- package/dist/{chunk-E33PFGHA.js → chunk-ZIFNNRVH.js} +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.d.cts +2 -2
- package/dist/client.d.ts +2 -2
- package/dist/client.js +1 -1
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.d.cts +3 -3
- package/dist/drizzle/index.d.ts +3 -3
- package/dist/drizzle/index.js +1 -1
- package/dist/fields/index.cjs +1 -1
- package/dist/fields/index.d.cts +1 -1
- package/dist/fields/index.d.ts +1 -1
- package/dist/fields/index.js +1 -1
- package/dist/graphql/index.cjs +1 -1
- package/dist/graphql/index.d.cts +3 -3
- package/dist/graphql/index.d.ts +3 -3
- package/dist/graphql/index.js +1 -1
- package/dist/{index-BTFBhepB.d.ts → index-BitS8SsT.d.ts} +2 -2
- package/dist/{index-B52AAXcJ.d.cts → index-ChfSBo05.d.cts} +2 -2
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +9 -9
- package/dist/index.d.ts +9 -9
- package/dist/index.js +1 -1
- package/dist/mongodb/index.cjs +1 -1
- package/dist/mongodb/index.d.cts +3 -3
- package/dist/mongodb/index.d.ts +3 -3
- package/dist/mongodb/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.d.cts +4 -4
- package/dist/rest/index.d.ts +4 -4
- package/dist/rest/index.js +1 -1
- package/dist/templates/index.d.cts +2 -2
- package/dist/templates/index.d.ts +2 -2
- package/dist/trpc/index.d.cts +3 -3
- package/dist/trpc/index.d.ts +3 -3
- package/dist/{types-BH7tjlpR.d.ts → types-B7Zn7cy6.d.ts} +1 -1
- package/dist/{types-BMu-234T.d.cts → types-CM9P5IfD.d.cts} +1 -1
- package/dist/{types-C9izrwhZ.d.cts → types-d0sRWA-r.d.cts} +14 -2
- package/dist/{types-C9izrwhZ.d.ts → types-d0sRWA-r.d.ts} +14 -2
- package/package.json +1 -1
- package/dist/chunk-6JHNHMGB.cjs +0 -2
- package/dist/chunk-GT5P64DV.js +0 -21
- package/dist/chunk-PY45XUEJ.cjs +0 -21
- package/dist/chunk-RNY7W36D.cjs +0 -86
- package/dist/chunk-TYOVXKQP.js +0 -2
- package/dist/chunk-WMY7BDPK.cjs +0 -2
- package/dist/chunk-WQKF57FY.js +0 -86
- package/dist/chunk-YLEVWUTV.js +0 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export{a as RedisAuthAdapter}from'./chunk-AU6IWTBO.js';export{P as allSettingsGlobals,c as blogCollections,d as blogGlobals,Q as coreSettingsGlobals,U as createTemplateConfig,e as ecommerceCollections,f as ecommerceGlobals,g as kitchenSinkCollections,i as mediaCollections,a as minimalCollections,T as templateCollections}from'./chunk-ODCLVIIT.js';export{a as kyro}from'./chunk-PTS33SK5.js';export{a as ConfigValidationError,p as Kyro,r as LocalAdapter,l as Registry,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,q as createKyro,s as createLocalAdapter,o as createRegistry,f as fieldToZod,m as getRegistry,k as globalToZod,n as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-GT5P64DV.js';export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,c as getBootstrapFromEnv}from'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';export{a as CSSGenerator,g as createAdminStyling,d as defaultDarkTheme,h as defaultFieldStyling,c as defaultLightTheme,e as ecommerce2026Theme,f as generateCSSVariables,b as generateTailwindConfig}from'./chunk-UHFDH3PG.js';export{p as ALL_FIELD_TYPES,m as COMPLEX_FIELD_TYPES,o as LAYOUT_FIELD_TYPES,l as PRIMITIVE_FIELD_TYPES,n as RELATIONAL_FIELD_TYPES,d as isArrayField,f as isBlocksField,e as isGroupField,h as isImageField,k as isLayoutField,b as isNumberField,c as isRelationshipField,i as isRichTextField,j as isSelectField,a as isTextField,g as isUploadField,s as normalizeRichTextValue,t as renderRichText,r as richTextStyles}from'./chunk-NGBJKZMT.js';export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'./chunk-GJQH6NV7.js';export{c as buildGraphQLSchema,d as createGraphQLSchema}from'./chunk-YLEVWUTV.js';import {l,n,m,p as p$1,q}from'./chunk-WQKF57FY.js';export{n as AuditLogger,p as InMemoryAuditLogger,m as InMemoryRateLimiter,r as MediaService,o as createAuditContext,s as createHonoApp,e as createLocalStorage,t as createRESTAPI,i as getAppSecret,j as getEncryptionKey,k as getSessionConfig,h as loadSecrets,d as resolveProvider,g as setDbAdapter}from'./chunk-WQKF57FY.js';import {b as b$1,c}from'./chunk-7WOX27LK.js';export{a as ConfigService,b as EmailTransport,c as PasswordPolicy}from'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import {a as a$1}from'./chunk-2W4FK6CJ.js';export{a as SQLiteAuthAdapter}from'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';export{e as ALL_WEBHOOK_EVENTS,f as WEBHOOK_COLLECTION,g as WEBHOOK_DELIVERY_COLLECTION,d as WEBHOOK_EVENTS,n as WebhookService,l as buildDeliveryRecord,m as createTestPayload,o as createWebhookService,j as deliverWebhook,k as deliverWithRetry,i as generateWebhookSecret,h as signPayload}from'./chunk-QIP7PY2U.js';export{a as evaluateAccess,c as getWhereClause,b as mergeWhereClauses}from'./chunk-HLSB2MCK.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-SL3LZQCF.js';import'./chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'./chunk-GDMLWVJO.js';import {a as a$2}from'./chunk-RHCWCG3O.js';export{a as PostgresAuthAdapter}from'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-TYOVXKQP.js';import {a}from'./chunk-P7CESLDJ.js';export{a as MongoDBAuthAdapter}from'./chunk-P7CESLDJ.js';export{a as AbstractBaseAdapter}from'./chunk-4YYBWCDJ.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';import q$1,{randomBytes}from'crypto';import {readFileSync}from'fs';import Me,{join,resolve}from'path';export{z}from'zod';import {createStorage}from'unstorage';import $r from'unstorage/drivers/indexedb';import zr from'unstorage/drivers/fs';async function Ie(s,e){let t=e.data;for(let r of s){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function br(s,e){return Ie(s,e)}var b=class{name;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}},$=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[r,o]of Object.entries(t))if(Array.isArray(o))for(let i of o)this.registerHook(r,i);}unregister(e){let t=this.plugins.get(e);if(!t)return;let r=t.getHooks?.()||{};for(let[o,i]of Object.entries(r))if(Array.isArray(i))for(let n of i)this.unregisterHook(o,n);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 r=this.hooks.get(e);if(r){let o=r.indexOf(t);o>-1&&r.splice(o,1);}}async executeHook(e,t){let r=this.hooks.get(e)||[],o=t;for(let i of r)try{let n=await i({...t,data:o});n!==void 0&&(o=n);}catch(n){console.error(`[PluginManager] Error in hook "${e}":`,n);}return o}getAllCollections(){let e=[];for(let t of this.plugins.values()){let r=t.getCollections?.()||[];e.push(...r);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let r=t.getGlobals?.()||[];e.push(...r);}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}},L=class extends b{constructor(){super("seo"),this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",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"}]});}},E=class extends b{constructor(){super("analytics"),this.description="Analytics integration for tracking page views and events",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 b{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={};}},V=class extends b{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={};}},O=class extends b{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"}]}]}]}]});}},Ar={SEO:L,Analytics:E,Comments:U,Reviews:V,Wishlist:O};var wr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},x=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...wr,...t};}lockKey(e){return `${this.prefix}${e}`}historyKey(e){return `${this.prefix}${e}:history`}async checkLockout(e){let t=this.lockKey(e),r=await this.redis.hgetall(t);if(!r||Object.keys(r).length===0)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let o=parseInt(r.attempts,10),i=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return i&&i>new Date?{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:o}:i&&i<=new Date?(await this.unlockAccount(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0}):{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=this.lockKey(e),r=this.historyKey(e),o=Date.now(),i=await this.redis.hincrby(t,"attempts",1);if(await this.redis.hset(t,"lastAttempt",o.toString()),await this.redis.lpush(r,o.toString()),await this.redis.ltrim(r,0,99),i>=this.config.maxAttempts){let n=new Date(o+this.config.lockDuration);return await this.redis.hset(t,{lockedAt:o.toString(),lockedUntil:n.getTime().toString()}),await this.redis.expire(t,Math.ceil(this.config.lockDuration/1e3)+3600),{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:i}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-i),totalAttempts:i}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),i=t||this.config.lockDuration,n=new Date(o+i),a=this.redis.pipeline();a.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:n.getTime().toString()}),a.expire(r,Math.ceil(i/1e3)+3600),await a.exec();}async unlockAccount(e){let t=this.lockKey(e);await this.redis.del(t);}async resetAttempts(e){let t=this.lockKey(e);(await this.redis.hgetall(t)).lockedAt?await this.redis.hset(t,{attempts:"0",lockedAt:"",lockedUntil:""}):await this.redis.del(t);}async getLockoutHistory(e,t=10){let r=this.historyKey(e);return (await this.redis.lrange(r,0,t-1)).map(i=>new Date(parseInt(i,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((n,a)=>(a+1)%this.config.maxAttempts===0).length,i=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:i?new Date(parseInt(i,10)):null,averageAttemptsBeforeLockout:o>0?this.config.maxAttempts:0}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};var kr={"auth:login":{window:9e5,max:5},"auth:register":{window:36e5,max:3},"auth:forgot":{window:36e5,max:3},"auth:reset":{window:36e5,max:5},"auth:verify":{window:36e5,max:5},"api:general":{window:6e4,max:100},"api:authenticated":{window:6e4,max:200}},S=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...kr,...t},this.userLimits=r||{"user:api":{window:6e4,max:500},"user:write":{window:36e5,max:100}};}getKey(e,t){return `${this.prefix}${e}:${t}`}async check(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),i=Date.now(),n=i-r.window,a=this.redis.pipeline();a.zremrangebyscore(o,0,n),a.zcard(o),a.zadd(o,i,`${i}:${Math.random()}`),a.expire(o,Math.ceil(r.window/1e3)+1);let c=(await a.exec())?.[1]?.[1]||0;if(c>=r.max){let g=await this.redis.zrange(o,0,0,"WITHSCORES"),d=g.length>1?parseInt(g[1],10)+r.window:i+r.window;return {allowed:false,remaining:0,resetAt:d,retryAfter:Math.ceil((d-i)/1e3)}}return {allowed:true,remaining:r.max-c-1,resetAt:i+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],i=this.getKey(`user:${e}:${t}`,r),n=Date.now(),a=n-o.window,l=this.redis.pipeline();l.zremrangebyscore(i,0,a),l.zcard(i),l.zadd(i,n,`${n}:${Math.random()}`),l.expire(i,Math.ceil(o.window/1e3)+1);let g=(await l.exec())?.[1]?.[1]||0;if(g>=o.max){let d=await this.redis.zrange(i,0,0,"WITHSCORES"),u=d.length>1?parseInt(d[1],10)+o.window:n+o.window;return {allowed:false,remaining:0,resetAt:u,retryAfter:Math.ceil((u-n)/1e3)}}return {allowed:true,remaining:o.max-g-1,resetAt:n+o.window}}async reset(e,t){let r=this.getKey(e,t);await this.redis.del(r);}async resetUser(e,t,r){let o=this.getKey(`user:${e}:${t}`,r);await this.redis.del(o);}async getStatus(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),i=Date.now(),n=i-r.window;await this.redis.zremrangebyscore(o,0,n);let a=await this.redis.zcard(o);return {count:a,limit:r.max,remaining:Math.max(0,r.max-a),resetAt:i+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};var P=class{users=new Map;sessions=new Map;refreshTokens=new Map;emailToUserId=new Map;passwordHistory=new Map;emailVerificationTokens=new Map;passwordResetTokens=new Map;auditLogs=[];externalDb=false;constructor(){}async connect(){}async disconnect(){this.users.clear(),this.sessions.clear(),this.refreshTokens.clear(),this.emailToUserId.clear(),this.passwordHistory.clear();}async createUser(e){let t=randomBytes(16).toString("hex"),r=new Date().toISOString(),o=await this.hashPassword(e.password),i={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,i),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),i}async findUserByEmail(e){let t=this.emailToUserId.get(e.toLowerCase());return t?this.findUserById(t):null}async findUserById(e){return this.users.get(e)||null}async updateUser(e,t){let r=await this.findUserById(e);if(!r)return null;let o={...r,...t,id:e,updatedAt:new Date().toISOString()};return t.email&&t.email!==r.email&&(this.emailToUserId.delete(r.email.toLowerCase()),this.emailToUserId.set(t.email.toLowerCase(),e)),this.users.set(e,o),o}async deleteUser(e){let t=await this.findUserById(e);return t?(this.users.delete(e),this.emailToUserId.delete(t.email.toLowerCase()),this.refreshTokens.forEach((r,o)=>{this.sessions.get(r)?.userId===e&&(this.refreshTokens.delete(o),this.sessions.delete(r));}),this.passwordHistory.delete(e),this.sessions.forEach((r,o)=>{r.userId===e&&this.sessions.delete(o);}),true):false}async hashPassword(e){return (await import('bcryptjs')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('bcryptjs')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),i=randomBytes(32).toString("base64url"),n=new Date,a={id:r,userId:e,token:o,refreshToken:i,expiresAt:new Date(n.getTime()+86400*1e3).toISOString(),createdAt:n.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,a),this.refreshTokens.set(i,r),a}async findSessionByToken(e){return this.sessions.get(e)||null}async findSessionByRefreshToken(e){let t=this.refreshTokens.get(e);return t&&this.sessions.get(t)||null}async deleteSession(e){let t=this.sessions.get(e);return t?(t.refreshToken&&this.refreshTokens.delete(t.refreshToken),this.sessions.delete(e),true):false}async deleteUserSessions(e){let t=0;return this.sessions.forEach((r,o)=>{r.userId===e&&(r.refreshToken&&this.refreshTokens.delete(r.refreshToken),this.sessions.delete(o),t++);}),t}async addPasswordToHistory(e,t){let r=this.passwordHistory.get(e)||[];r.push(t),r.length>5&&r.splice(0,r.length-5),this.passwordHistory.set(e,r);}async getPasswordHistory(e,t=5){return this.passwordHistory.get(e)||[]}async isPasswordInHistory(e,t,r=5){let o=await this.getPasswordHistory(t,r),i=(await import('bcryptjs')).default;for(let n of o)if(await i.compare(e,n))return true;return false}async createEmailVerificationToken(e){let t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.emailVerificationTokens.set(t,{userId:e,expiresAt:r}),{token:t,expiresAt:r}}async verifyEmailToken(e){let t=this.emailVerificationTokens.get(e);return !t||t.expiresAt<new Date?(this.emailVerificationTokens.delete(e),{success:false,error:"Invalid or expired token"}):(this.emailVerificationTokens.delete(e),{success:true,userId:t.userId})}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let r=randomBytes(32).toString("hex"),o=new Date(Date.now()+3600*1e3);return this.passwordResetTokens.set(r,{userId:t.id,expiresAt:o}),{token:r,expiresAt:o}}async resetPasswordWithToken(e,t){let r=this.passwordResetTokens.get(e);if(!r||r.expiresAt<new Date)return this.passwordResetTokens.delete(e),{success:false,error:"Invalid or expired token"};let o=await this.hashPassword(t);return await this.updateUser(r.userId,{passwordHash:o}),this.passwordResetTokens.delete(e),{success:true}}async hasAnyUsers(){return this.users.size>0}async findAuditLogs(e){let{limit:t=50,offset:r=0}=e,o=this.auditLogs.slice().reverse();return e.userId&&(o=o.filter(i=>i.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(i=>e.action.includes(String(i.action))):o=o.filter(i=>i.action===e.action)),e.resource&&(o=o.filter(i=>i.resource===e.resource)),e.success!==void 0&&(o=o.filter(i=>i.success===e.success)),{logs:o.slice(r,r+t),total:o.length}}async createAuditLog(e){let t=randomBytes(16).toString("hex"),o={...e,id:t,timestamp:new Date};return this.auditLogs.push(o),o}};var C=class{storage=new Map;history=new Map;config;constructor(e={}){this.config={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3,...e};}async checkLockout(e){let t=Date.now(),r=this.storage.get(e);if(r&&r.lockedUntil!==null&&r.lockedUntil<=t)return await this.resetAttempts(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};if(!r)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let{attempts:o,lockedUntil:i}=r;return i!==null&&i>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(i),totalAttempts:o}:{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=Date.now(),r=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};r.attempts+=1,r.lastAttempt=t;let o=this.history.get(e)||[];if(o.push(t),o.length>100&&o.splice(0,o.length-100),this.history.set(e,o),this.storage.set(e,r),r.attempts>=this.config.maxAttempts){let i=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=i.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:r.attempts}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-r.attempts),totalAttempts:r.attempts}}async lockAccount(e,t){let r=Date.now(),o=t||this.config.lockDuration,i=new Date(r+o),n=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};n.attempts=this.config.maxAttempts,n.lockedAt=r,n.lockedUntil=i.getTime(),this.storage.set(e,n);}async unlockAccount(e){await this.resetAttempts(e);}async resetAttempts(e){let t=this.storage.get(e);t&&(t.attempts=0,t.lockedAt=null,t.lockedUntil=null,this.storage.set(e,t)),this.history.delete(e);}async getLockoutHistory(e,t=10){return (this.history.get(e)||[]).slice(-t).reverse().map(o=>new Date(o))}async getLockoutStats(e){let r=(this.history.get(e)||[]).length,o=Math.floor(r/this.config.maxAttempts),i=null,n=this.storage.get(e);n&&n.lockedAt!==null&&(i=new Date(n.lockedAt));let a=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:i,averageAttemptsBeforeLockout:a}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function h(s,e=""){return process.env[s]||e}function A(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function p(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Le(){let s=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(s&&["sqlite","postgres","mongodb","memory"].includes(s))return s;try{let e=join(process.cwd(),"kyro.config.ts"),t=readFileSync(e,"utf8");if(t.includes("createLocalAdapter"))return "sqlite";if(t.includes("createDrizzleAdapter"))return t.includes("postgres")||t.includes("postgresql"),"postgres";if(t.includes("createMongoDBAdapter"))return "mongodb"}catch{}return "memory"}async function Pr(s){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(s){case "sqlite":return new a$1({path:h("KYRO_AUTH_DB_PATH",r)});case "postgres":{try{let o=h("DATABASE_URL","");if(o){let{drizzle:i}=await import('drizzle-orm/postgres-js'),a=(await import('postgres')).default(o,{onnotice:()=>{}}),l=i(a);return new a$2({db:l})}}catch{console.warn("[Auth] Could not create PostgresAuthAdapter, falling back to SQLite auth adapter.");}return new a$1({path:h("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{try{let o=h("MONGODB_URI","");if(o){let{MongoClient:i}=await import('mongodb'),n=new i(o);await n.connect();let l=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",c=n.db(l);return new a({db:c})}}catch{console.warn("[Auth] Could not create MongoDBAuthAdapter, falling back to SQLite auth adapter.");}return new a$1({path:h("KYRO_AUTH_DB_PATH",r)})}default:return new P}}async function W(s,e){let t=A("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:d}=await import('./redis-adapter-VAXP43GR.js'),u=h("REDIS_URL","redis://localhost:6379"),y=A("REDIS_TLS",false),f=new d({url:u,tls:y});await f.connect?.(),r=f;}else {let d=s||Le();r=await Pr(d),r.connect&&await r.connect();}let o=e?await b$1.fromConfig(e).catch(()=>null)||b$1.fromEnv()||void 0:b$1.fromEnv()||void 0,i=new c({minLength:p("PASSWORD_MIN_LENGTH",12),requireUppercase:A("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:A("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:A("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:A("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:p("PASSWORD_PREVENT_REUSE",5),maxLength:p("PASSWORD_MAX_LENGTH",128)}),n$1,a,l;if(t){let u=r.redis;n$1=new x(u,{maxAttempts:p("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:p("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new S(u,{"auth:login":{window:p("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:p("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:p("RATE_LIMIT_WINDOW_MS",6e4),max:p("RATE_LIMIT_MAX_REQUESTS",100)}}),l=new n(u,p("AUDIT_LOG_RETENTION_DAYS",30));}else n$1=new C({maxAttempts:p("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:p("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new m({"auth:login":{window:p("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:p("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:p("RATE_LIMIT_WINDOW_MS",6e4),max:p("RATE_LIMIT_MAX_REQUESTS",100)}}),l=A("AUDIT_LOG_ENABLED",true)?new p$1(p("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let c$1=new q({redis:r,email:o,jwtSecret:h("APP_SECRET","change-me"),jwtExpiresIn:h("JWT_EXPIRES_IN","24h"),jwtIssuer:h("JWT_ISSUER","kyro-cms"),jwtAudience:h("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:i,lockout:n$1,rateLimiter:a,auditLogger:l,baseUrl:h("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:A("EMAIL_VERIFICATION_REQUIRED",true)}),g=t?"distributed":s||Le();return {authAdapter:r,databaseType:g,email:o,passwordPolicy:i,lockout:n$1,rateLimiter:a,auditLogger:l,routes:c$1}}var Ue=W().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Cr=12,Tr="24h",vr="7d",H=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Tr,refreshExpiresIn:t.refreshExpiresIn??vr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Cr};}async register(e){try{if(await this.adapter.findUserByEmail(e.email))return {success:!1,error:"Email already registered"};let r=await this.adapter.createUser({email:e.email,password:e.password,role:e.role??"customer",tenantId:e.tenantId});return this.createSessionForUser(r)}catch(t){return {success:false,error:String(t)}}}async login(e){try{let t=await this.adapter.verifyPassword(e.email,e.password);return t?this.createSessionForUser(t):{success:!1,error:"Invalid credentials"}}catch(t){return {success:false,error:String(t)}}}async logout(e){await this.adapter.deleteSession(e);}async refreshToken(e){try{let t=await this.adapter.findSessionByToken(e);if(!t||new Date(t.expiresAt)<new Date)return {success:!1,error:"Invalid or expired refresh token"};let r=await this.adapter.findUserById(t.userId);return r?(await this.adapter.deleteSession(e),this.createSessionForUser(r)):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async verifyToken(e){try{let{default:t}=await import('jsonwebtoken');return t.verify(e,this.config.secret,{issuer:this.config.issuer,audience:this.config.audience.length>0?this.config.audience[0]:void 0})}catch{return null}}async getUserFromToken(e){let t=await this.verifyToken(e);return t?this.adapter.findUserById(t.sub):null}async changePassword(e,t,r){try{let o=await this.adapter.findUserById(e);return o?await this.adapter.verifyPassword(o.email,t)?(await this.adapter.updateUser(e,{password:r}),await this.adapter.deleteUserSessions(e),{success:!0,user:o}):{success:!1,error:"Current password is incorrect"}:{success:!1,error:"User not found"}}catch(o){return {success:false,error:String(o)}}}async resetPassword(e,t){try{let r=await this.adapter.findUserByEmail(e);return r?(await this.adapter.updateUser(r.id,{password:t}),await this.adapter.deleteUserSessions(r.id),{success:!0,user:r}):{success:!1,error:"User not found"}}catch(r){return {success:false,error:String(r)}}}async sendEmailVerification(e){try{let{token:t,expiresAt:r}=await this.adapter.createEmailVerificationToken(e);return {success:!0}}catch(t){return {success:false,error:String(t)}}}async verifyEmail(e){try{return await this.adapter.verifyEmailToken(e)}catch(t){return {success:false,error:String(t)}}}async requestPasswordReset(e){try{let t=await this.adapter.createPasswordResetToken(e);return t.error?{success:!1,error:t.error}:{success:!0}}catch(t){return {success:false,error:String(t)}}}async resetPasswordWithToken(e,t){try{return await this.adapter.resetPasswordWithToken(e,t)}catch(r){return {success:false,error:String(r)}}}async deleteAccount(e){try{return await this.adapter.findUserById(e)?(await this.adapter.deleteUserSessions(e),await this.adapter.deleteUser(e),{success:!0}):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async createSessionForUser(e){let t=await this.generateToken(e),r=await this.adapter.createSession(e.id);return {success:true,user:e,session:r,token:t}}async generateToken(e){let{default:t}=await import('jsonwebtoken'),r={sub:e.id,email:e.email,role:e.role,tenantId:e.tenantId},o={expiresIn:this.parseExpiresIn(this.config.expiresIn)/1e3,issuer:this.config.issuer};return this.config.audience.length>0&&(o.audience=this.config.audience[0]),t.sign(r,this.config.secret,o)}async hashPassword(e){let{default:t}=await import('bcryptjs');return t.hash(e,this.config.saltRounds)}parseExpiresIn(e){if(typeof e=="number")return e;let t=e.match(/^(\d+)([smhd])$/);if(!t)return 864e5;let r=parseInt(t[1],10);switch(t[2]){case "s":return r*1e3;case "m":return r*6e4;case "h":return r*36e5;case "d":return r*864e5;default:return 864e5}}};function Rr(s,e){return new H(s,e)}function _(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var M=class{adapter;config;constructor(e,t){this.adapter=e,this.config={..._(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},i=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),i}async publishVersion(e){let t=await this.adapter.getVersion(e.collection,e.versionId);if(!t)throw new Error("Version not found");if(t.status==="published")throw new Error("Version is already published");await this.adapter.publishVersion(e);}async unpublishDocument(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:1e3});for(let o of r)if(o.status==="published"){await this.createVersion({collection:e,documentId:t,data:o.data,status:"draft",createdBy:"system",changeDescription:"Unpublished document"});break}}async revertToVersion(e,t,r,o){if(!await this.adapter.getVersion(e,r))throw new Error("Version not found");return await this.adapter.revertToVersion({collection:e,documentId:t,versionId:r,userId:o})}async getVersionHistory(e,t,r=20,o=0){return this.adapter.getVersions({collection:e,documentId:t,limit:r,offset:o})}async compareTwoVersions(e,t,r,o){return this.adapter.compareVersions({collection:e,documentId:t,versionA:r,versionB:o})}async getLatestDraft(e,t){return this.adapter.getLatestVersion(e,t)}async getPublishedVersion(e,t){return this.adapter.getPublishedVersion(e,t)}async getVersion(e,t){return this.adapter.getVersion(e,t)}async schedulePublish(e,t,r,o){if(!this.config.scheduleEnabled)throw new Error("Scheduled publishing is not enabled");if(!await this.adapter.getVersion(e,r))throw new Error("Version not found")}async deleteVersionHistory(e,t){await this.adapter.deleteVersions(e,t);}async pruneOldVersions(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:this.config.maxVersionsPerDocument+100});if(r.length<=this.config.maxVersionsPerDocument)return;r.slice(0,this.config.maxVersionsPerDocument);let i=r.slice(this.config.maxVersionsPerDocument);for(let n of i)if(n.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Dr(s,e){return new M(s,e)}function Ir(s){return s==="published"}function Lr(s){return s==="draft"}function Er(s){return s==="archived"}function Ur(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Vr(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Ve(s){return {collections:Ur(s.collections),globals:Vr(s.globals),adapter:s.adapter,plugins:s.plugins,auth:s.auth,cors:s.cors,admin:s.admin,upload:s.upload,graphQL:s.graphQL,typescript:s.typescript,localization:s.localization,rateLimit:s.rateLimit,debug:s.debug}}var Or=Ve;function Hr(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:i,url:n}=s;if(!e)return "";let a=e.siteName||"",l=r||t?.defaultTitle||a,c=t?.titleTemplate,g=t?.separator||" | ",d=t?.siteNameInTitle!==false,u=c?c.replace(/\{\{title\}\}/g,l).replace(/\{\{siteName\}\}/g,d?a:"").replace(/\{\{separator\}\}/g,g).replace(/\s+/g," ").trim():l,y=o||t?.defaultDescription||e.siteDescription||"",f=i||e.siteOgImage?.url||"",F=n||e.siteUrl||"",m=`
|
|
1
|
+
export{a as RedisAuthAdapter}from'./chunk-AU6IWTBO.js';export{P as allSettingsGlobals,c as blogCollections,d as blogGlobals,Q as coreSettingsGlobals,U as createTemplateConfig,e as ecommerceCollections,f as ecommerceGlobals,g as kitchenSinkCollections,i as mediaCollections,a as minimalCollections,T as templateCollections}from'./chunk-ODCLVIIT.js';export{a as kyro}from'./chunk-PTS33SK5.js';export{a as ConfigValidationError,p as Kyro,r as LocalAdapter,l as Registry,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,q as createKyro,s as createLocalAdapter,o as createRegistry,f as fieldToZod,m as getRegistry,k as globalToZod,n as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-AYCQ3E7K.js';export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,c as getBootstrapFromEnv}from'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';export{a as CSSGenerator,g as createAdminStyling,d as defaultDarkTheme,h as defaultFieldStyling,c as defaultLightTheme,e as ecommerce2026Theme,f as generateCSSVariables,b as generateTailwindConfig}from'./chunk-UHFDH3PG.js';export{p as ALL_FIELD_TYPES,m as COMPLEX_FIELD_TYPES,o as LAYOUT_FIELD_TYPES,l as PRIMITIVE_FIELD_TYPES,n as RELATIONAL_FIELD_TYPES,d as isArrayField,f as isBlocksField,e as isGroupField,h as isImageField,k as isLayoutField,b as isNumberField,c as isRelationshipField,i as isRichTextField,j as isSelectField,a as isTextField,g as isUploadField,s as normalizeRichTextValue,t as renderRichText,r as richTextStyles}from'./chunk-NJS6FLXT.js';export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'./chunk-GJQH6NV7.js';export{c as buildGraphQLSchema,d as createGraphQLSchema}from'./chunk-XQPYBNIT.js';import {l,n,m,p as p$1,q}from'./chunk-O6WZLSKJ.js';export{n as AuditLogger,p as InMemoryAuditLogger,m as InMemoryRateLimiter,r as MediaService,o as createAuditContext,s as createHonoApp,e as createLocalStorage,t as createRESTAPI,i as getAppSecret,j as getEncryptionKey,k as getSessionConfig,h as loadSecrets,d as resolveProvider,g as setDbAdapter}from'./chunk-O6WZLSKJ.js';import {b as b$1,c}from'./chunk-7WOX27LK.js';export{a as ConfigService,b as EmailTransport,c as PasswordPolicy}from'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import {a as a$1}from'./chunk-2W4FK6CJ.js';export{a as SQLiteAuthAdapter}from'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';export{e as ALL_WEBHOOK_EVENTS,f as WEBHOOK_COLLECTION,g as WEBHOOK_DELIVERY_COLLECTION,d as WEBHOOK_EVENTS,n as WebhookService,l as buildDeliveryRecord,m as createTestPayload,o as createWebhookService,j as deliverWebhook,k as deliverWithRetry,i as generateWebhookSecret,h as signPayload}from'./chunk-QIP7PY2U.js';export{a as evaluateAccess,c as getWhereClause,b as mergeWhereClauses}from'./chunk-HLSB2MCK.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-SL3LZQCF.js';import'./chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'./chunk-MTFJDAPX.js';import {a as a$2}from'./chunk-RHCWCG3O.js';export{a as PostgresAuthAdapter}from'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-7ORSLR3S.js';import {a}from'./chunk-P7CESLDJ.js';export{a as MongoDBAuthAdapter}from'./chunk-P7CESLDJ.js';export{a as AbstractBaseAdapter}from'./chunk-4YYBWCDJ.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';import q$1,{randomBytes}from'crypto';import {readFileSync}from'fs';import Me,{join,resolve}from'path';export{z}from'zod';import {createStorage}from'unstorage';import $r from'unstorage/drivers/indexedb';import zr from'unstorage/drivers/fs';async function Ie(s,e){let t=e.data;for(let r of s){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function br(s,e){return Ie(s,e)}var b=class{name;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}},$=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[r,o]of Object.entries(t))if(Array.isArray(o))for(let i of o)this.registerHook(r,i);}unregister(e){let t=this.plugins.get(e);if(!t)return;let r=t.getHooks?.()||{};for(let[o,i]of Object.entries(r))if(Array.isArray(i))for(let n of i)this.unregisterHook(o,n);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 r=this.hooks.get(e);if(r){let o=r.indexOf(t);o>-1&&r.splice(o,1);}}async executeHook(e,t){let r=this.hooks.get(e)||[],o=t;for(let i of r)try{let n=await i({...t,data:o});n!==void 0&&(o=n);}catch(n){console.error(`[PluginManager] Error in hook "${e}":`,n);}return o}getAllCollections(){let e=[];for(let t of this.plugins.values()){let r=t.getCollections?.()||[];e.push(...r);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let r=t.getGlobals?.()||[];e.push(...r);}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}},L=class extends b{constructor(){super("seo"),this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",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"}]});}},E=class extends b{constructor(){super("analytics"),this.description="Analytics integration for tracking page views and events",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 b{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={};}},V=class extends b{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={};}},O=class extends b{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"}]}]}]}]});}},Ar={SEO:L,Analytics:E,Comments:U,Reviews:V,Wishlist:O};var wr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},x=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...wr,...t};}lockKey(e){return `${this.prefix}${e}`}historyKey(e){return `${this.prefix}${e}:history`}async checkLockout(e){let t=this.lockKey(e),r=await this.redis.hgetall(t);if(!r||Object.keys(r).length===0)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let o=parseInt(r.attempts,10),i=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return i&&i>new Date?{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:o}:i&&i<=new Date?(await this.unlockAccount(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0}):{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=this.lockKey(e),r=this.historyKey(e),o=Date.now(),i=await this.redis.hincrby(t,"attempts",1);if(await this.redis.hset(t,"lastAttempt",o.toString()),await this.redis.lpush(r,o.toString()),await this.redis.ltrim(r,0,99),i>=this.config.maxAttempts){let n=new Date(o+this.config.lockDuration);return await this.redis.hset(t,{lockedAt:o.toString(),lockedUntil:n.getTime().toString()}),await this.redis.expire(t,Math.ceil(this.config.lockDuration/1e3)+3600),{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:i}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-i),totalAttempts:i}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),i=t||this.config.lockDuration,n=new Date(o+i),a=this.redis.pipeline();a.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:n.getTime().toString()}),a.expire(r,Math.ceil(i/1e3)+3600),await a.exec();}async unlockAccount(e){let t=this.lockKey(e);await this.redis.del(t);}async resetAttempts(e){let t=this.lockKey(e);(await this.redis.hgetall(t)).lockedAt?await this.redis.hset(t,{attempts:"0",lockedAt:"",lockedUntil:""}):await this.redis.del(t);}async getLockoutHistory(e,t=10){let r=this.historyKey(e);return (await this.redis.lrange(r,0,t-1)).map(i=>new Date(parseInt(i,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((n,a)=>(a+1)%this.config.maxAttempts===0).length,i=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:i?new Date(parseInt(i,10)):null,averageAttemptsBeforeLockout:o>0?this.config.maxAttempts:0}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};var kr={"auth:login":{window:9e5,max:5},"auth:register":{window:36e5,max:3},"auth:forgot":{window:36e5,max:3},"auth:reset":{window:36e5,max:5},"auth:verify":{window:36e5,max:5},"api:general":{window:6e4,max:100},"api:authenticated":{window:6e4,max:200}},S=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...kr,...t},this.userLimits=r||{"user:api":{window:6e4,max:500},"user:write":{window:36e5,max:100}};}getKey(e,t){return `${this.prefix}${e}:${t}`}async check(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),i=Date.now(),n=i-r.window,a=this.redis.pipeline();a.zremrangebyscore(o,0,n),a.zcard(o),a.zadd(o,i,`${i}:${Math.random()}`),a.expire(o,Math.ceil(r.window/1e3)+1);let c=(await a.exec())?.[1]?.[1]||0;if(c>=r.max){let g=await this.redis.zrange(o,0,0,"WITHSCORES"),d=g.length>1?parseInt(g[1],10)+r.window:i+r.window;return {allowed:false,remaining:0,resetAt:d,retryAfter:Math.ceil((d-i)/1e3)}}return {allowed:true,remaining:r.max-c-1,resetAt:i+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],i=this.getKey(`user:${e}:${t}`,r),n=Date.now(),a=n-o.window,l=this.redis.pipeline();l.zremrangebyscore(i,0,a),l.zcard(i),l.zadd(i,n,`${n}:${Math.random()}`),l.expire(i,Math.ceil(o.window/1e3)+1);let g=(await l.exec())?.[1]?.[1]||0;if(g>=o.max){let d=await this.redis.zrange(i,0,0,"WITHSCORES"),u=d.length>1?parseInt(d[1],10)+o.window:n+o.window;return {allowed:false,remaining:0,resetAt:u,retryAfter:Math.ceil((u-n)/1e3)}}return {allowed:true,remaining:o.max-g-1,resetAt:n+o.window}}async reset(e,t){let r=this.getKey(e,t);await this.redis.del(r);}async resetUser(e,t,r){let o=this.getKey(`user:${e}:${t}`,r);await this.redis.del(o);}async getStatus(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),i=Date.now(),n=i-r.window;await this.redis.zremrangebyscore(o,0,n);let a=await this.redis.zcard(o);return {count:a,limit:r.max,remaining:Math.max(0,r.max-a),resetAt:i+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};var P=class{users=new Map;sessions=new Map;refreshTokens=new Map;emailToUserId=new Map;passwordHistory=new Map;emailVerificationTokens=new Map;passwordResetTokens=new Map;auditLogs=[];externalDb=false;constructor(){}async connect(){}async disconnect(){this.users.clear(),this.sessions.clear(),this.refreshTokens.clear(),this.emailToUserId.clear(),this.passwordHistory.clear();}async createUser(e){let t=randomBytes(16).toString("hex"),r=new Date().toISOString(),o=await this.hashPassword(e.password),i={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,i),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),i}async findUserByEmail(e){let t=this.emailToUserId.get(e.toLowerCase());return t?this.findUserById(t):null}async findUserById(e){return this.users.get(e)||null}async updateUser(e,t){let r=await this.findUserById(e);if(!r)return null;let o={...r,...t,id:e,updatedAt:new Date().toISOString()};return t.email&&t.email!==r.email&&(this.emailToUserId.delete(r.email.toLowerCase()),this.emailToUserId.set(t.email.toLowerCase(),e)),this.users.set(e,o),o}async deleteUser(e){let t=await this.findUserById(e);return t?(this.users.delete(e),this.emailToUserId.delete(t.email.toLowerCase()),this.refreshTokens.forEach((r,o)=>{this.sessions.get(r)?.userId===e&&(this.refreshTokens.delete(o),this.sessions.delete(r));}),this.passwordHistory.delete(e),this.sessions.forEach((r,o)=>{r.userId===e&&this.sessions.delete(o);}),true):false}async hashPassword(e){return (await import('bcryptjs')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('bcryptjs')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),i=randomBytes(32).toString("base64url"),n=new Date,a={id:r,userId:e,token:o,refreshToken:i,expiresAt:new Date(n.getTime()+86400*1e3).toISOString(),createdAt:n.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,a),this.refreshTokens.set(i,r),a}async findSessionByToken(e){return this.sessions.get(e)||null}async findSessionByRefreshToken(e){let t=this.refreshTokens.get(e);return t&&this.sessions.get(t)||null}async deleteSession(e){let t=this.sessions.get(e);return t?(t.refreshToken&&this.refreshTokens.delete(t.refreshToken),this.sessions.delete(e),true):false}async deleteUserSessions(e){let t=0;return this.sessions.forEach((r,o)=>{r.userId===e&&(r.refreshToken&&this.refreshTokens.delete(r.refreshToken),this.sessions.delete(o),t++);}),t}async addPasswordToHistory(e,t){let r=this.passwordHistory.get(e)||[];r.push(t),r.length>5&&r.splice(0,r.length-5),this.passwordHistory.set(e,r);}async getPasswordHistory(e,t=5){return this.passwordHistory.get(e)||[]}async isPasswordInHistory(e,t,r=5){let o=await this.getPasswordHistory(t,r),i=(await import('bcryptjs')).default;for(let n of o)if(await i.compare(e,n))return true;return false}async createEmailVerificationToken(e){let t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.emailVerificationTokens.set(t,{userId:e,expiresAt:r}),{token:t,expiresAt:r}}async verifyEmailToken(e){let t=this.emailVerificationTokens.get(e);return !t||t.expiresAt<new Date?(this.emailVerificationTokens.delete(e),{success:false,error:"Invalid or expired token"}):(this.emailVerificationTokens.delete(e),{success:true,userId:t.userId})}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let r=randomBytes(32).toString("hex"),o=new Date(Date.now()+3600*1e3);return this.passwordResetTokens.set(r,{userId:t.id,expiresAt:o}),{token:r,expiresAt:o}}async resetPasswordWithToken(e,t){let r=this.passwordResetTokens.get(e);if(!r||r.expiresAt<new Date)return this.passwordResetTokens.delete(e),{success:false,error:"Invalid or expired token"};let o=await this.hashPassword(t);return await this.updateUser(r.userId,{passwordHash:o}),this.passwordResetTokens.delete(e),{success:true}}async hasAnyUsers(){return this.users.size>0}async findAuditLogs(e){let{limit:t=50,offset:r=0}=e,o=this.auditLogs.slice().reverse();return e.userId&&(o=o.filter(i=>i.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(i=>e.action.includes(String(i.action))):o=o.filter(i=>i.action===e.action)),e.resource&&(o=o.filter(i=>i.resource===e.resource)),e.success!==void 0&&(o=o.filter(i=>i.success===e.success)),{logs:o.slice(r,r+t),total:o.length}}async createAuditLog(e){let t=randomBytes(16).toString("hex"),o={...e,id:t,timestamp:new Date};return this.auditLogs.push(o),o}};var C=class{storage=new Map;history=new Map;config;constructor(e={}){this.config={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3,...e};}async checkLockout(e){let t=Date.now(),r=this.storage.get(e);if(r&&r.lockedUntil!==null&&r.lockedUntil<=t)return await this.resetAttempts(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};if(!r)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let{attempts:o,lockedUntil:i}=r;return i!==null&&i>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(i),totalAttempts:o}:{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=Date.now(),r=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};r.attempts+=1,r.lastAttempt=t;let o=this.history.get(e)||[];if(o.push(t),o.length>100&&o.splice(0,o.length-100),this.history.set(e,o),this.storage.set(e,r),r.attempts>=this.config.maxAttempts){let i=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=i.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:r.attempts}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-r.attempts),totalAttempts:r.attempts}}async lockAccount(e,t){let r=Date.now(),o=t||this.config.lockDuration,i=new Date(r+o),n=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};n.attempts=this.config.maxAttempts,n.lockedAt=r,n.lockedUntil=i.getTime(),this.storage.set(e,n);}async unlockAccount(e){await this.resetAttempts(e);}async resetAttempts(e){let t=this.storage.get(e);t&&(t.attempts=0,t.lockedAt=null,t.lockedUntil=null,this.storage.set(e,t)),this.history.delete(e);}async getLockoutHistory(e,t=10){return (this.history.get(e)||[]).slice(-t).reverse().map(o=>new Date(o))}async getLockoutStats(e){let r=(this.history.get(e)||[]).length,o=Math.floor(r/this.config.maxAttempts),i=null,n=this.storage.get(e);n&&n.lockedAt!==null&&(i=new Date(n.lockedAt));let a=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:i,averageAttemptsBeforeLockout:a}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function h(s,e=""){return process.env[s]||e}function A(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function p(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Le(){let s=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(s&&["sqlite","postgres","mongodb","memory"].includes(s))return s;try{let e=join(process.cwd(),"kyro.config.ts"),t=readFileSync(e,"utf8");if(t.includes("createLocalAdapter"))return "sqlite";if(t.includes("createDrizzleAdapter"))return t.includes("postgres")||t.includes("postgresql"),"postgres";if(t.includes("createMongoDBAdapter"))return "mongodb"}catch{}return "memory"}async function Pr(s){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(s){case "sqlite":return new a$1({path:h("KYRO_AUTH_DB_PATH",r)});case "postgres":{try{let o=h("DATABASE_URL","");if(o){let{drizzle:i}=await import('drizzle-orm/postgres-js'),a=(await import('postgres')).default(o,{onnotice:()=>{}}),l=i(a);return new a$2({db:l})}}catch{console.warn("[Auth] Could not create PostgresAuthAdapter, falling back to SQLite auth adapter.");}return new a$1({path:h("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{try{let o=h("MONGODB_URI","");if(o){let{MongoClient:i}=await import('mongodb'),n=new i(o);await n.connect();let l=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",c=n.db(l);return new a({db:c})}}catch{console.warn("[Auth] Could not create MongoDBAuthAdapter, falling back to SQLite auth adapter.");}return new a$1({path:h("KYRO_AUTH_DB_PATH",r)})}default:return new P}}async function W(s,e){let t=A("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:d}=await import('./redis-adapter-VAXP43GR.js'),u=h("REDIS_URL","redis://localhost:6379"),y=A("REDIS_TLS",false),f=new d({url:u,tls:y});await f.connect?.(),r=f;}else {let d=s||Le();r=await Pr(d),r.connect&&await r.connect();}let o=e?await b$1.fromConfig(e).catch(()=>null)||b$1.fromEnv()||void 0:b$1.fromEnv()||void 0,i=new c({minLength:p("PASSWORD_MIN_LENGTH",12),requireUppercase:A("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:A("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:A("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:A("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:p("PASSWORD_PREVENT_REUSE",5),maxLength:p("PASSWORD_MAX_LENGTH",128)}),n$1,a,l;if(t){let u=r.redis;n$1=new x(u,{maxAttempts:p("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:p("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new S(u,{"auth:login":{window:p("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:p("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:p("RATE_LIMIT_WINDOW_MS",6e4),max:p("RATE_LIMIT_MAX_REQUESTS",100)}}),l=new n(u,p("AUDIT_LOG_RETENTION_DAYS",30));}else n$1=new C({maxAttempts:p("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:p("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new m({"auth:login":{window:p("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:p("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:p("RATE_LIMIT_WINDOW_MS",6e4),max:p("RATE_LIMIT_MAX_REQUESTS",100)}}),l=A("AUDIT_LOG_ENABLED",true)?new p$1(p("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let c$1=new q({redis:r,email:o,jwtSecret:h("APP_SECRET","change-me"),jwtExpiresIn:h("JWT_EXPIRES_IN","24h"),jwtIssuer:h("JWT_ISSUER","kyro-cms"),jwtAudience:h("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:i,lockout:n$1,rateLimiter:a,auditLogger:l,baseUrl:h("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:A("EMAIL_VERIFICATION_REQUIRED",true)}),g=t?"distributed":s||Le();return {authAdapter:r,databaseType:g,email:o,passwordPolicy:i,lockout:n$1,rateLimiter:a,auditLogger:l,routes:c$1}}var Ue=W().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Cr=12,Tr="24h",vr="7d",H=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Tr,refreshExpiresIn:t.refreshExpiresIn??vr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Cr};}async register(e){try{if(await this.adapter.findUserByEmail(e.email))return {success:!1,error:"Email already registered"};let r=await this.adapter.createUser({email:e.email,password:e.password,role:e.role??"customer",tenantId:e.tenantId});return this.createSessionForUser(r)}catch(t){return {success:false,error:String(t)}}}async login(e){try{let t=await this.adapter.verifyPassword(e.email,e.password);return t?this.createSessionForUser(t):{success:!1,error:"Invalid credentials"}}catch(t){return {success:false,error:String(t)}}}async logout(e){await this.adapter.deleteSession(e);}async refreshToken(e){try{let t=await this.adapter.findSessionByToken(e);if(!t||new Date(t.expiresAt)<new Date)return {success:!1,error:"Invalid or expired refresh token"};let r=await this.adapter.findUserById(t.userId);return r?(await this.adapter.deleteSession(e),this.createSessionForUser(r)):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async verifyToken(e){try{let{default:t}=await import('jsonwebtoken');return t.verify(e,this.config.secret,{issuer:this.config.issuer,audience:this.config.audience.length>0?this.config.audience[0]:void 0})}catch{return null}}async getUserFromToken(e){let t=await this.verifyToken(e);return t?this.adapter.findUserById(t.sub):null}async changePassword(e,t,r){try{let o=await this.adapter.findUserById(e);return o?await this.adapter.verifyPassword(o.email,t)?(await this.adapter.updateUser(e,{password:r}),await this.adapter.deleteUserSessions(e),{success:!0,user:o}):{success:!1,error:"Current password is incorrect"}:{success:!1,error:"User not found"}}catch(o){return {success:false,error:String(o)}}}async resetPassword(e,t){try{let r=await this.adapter.findUserByEmail(e);return r?(await this.adapter.updateUser(r.id,{password:t}),await this.adapter.deleteUserSessions(r.id),{success:!0,user:r}):{success:!1,error:"User not found"}}catch(r){return {success:false,error:String(r)}}}async sendEmailVerification(e){try{let{token:t,expiresAt:r}=await this.adapter.createEmailVerificationToken(e);return {success:!0}}catch(t){return {success:false,error:String(t)}}}async verifyEmail(e){try{return await this.adapter.verifyEmailToken(e)}catch(t){return {success:false,error:String(t)}}}async requestPasswordReset(e){try{let t=await this.adapter.createPasswordResetToken(e);return t.error?{success:!1,error:t.error}:{success:!0}}catch(t){return {success:false,error:String(t)}}}async resetPasswordWithToken(e,t){try{return await this.adapter.resetPasswordWithToken(e,t)}catch(r){return {success:false,error:String(r)}}}async deleteAccount(e){try{return await this.adapter.findUserById(e)?(await this.adapter.deleteUserSessions(e),await this.adapter.deleteUser(e),{success:!0}):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async createSessionForUser(e){let t=await this.generateToken(e),r=await this.adapter.createSession(e.id);return {success:true,user:e,session:r,token:t}}async generateToken(e){let{default:t}=await import('jsonwebtoken'),r={sub:e.id,email:e.email,role:e.role,tenantId:e.tenantId},o={expiresIn:this.parseExpiresIn(this.config.expiresIn)/1e3,issuer:this.config.issuer};return this.config.audience.length>0&&(o.audience=this.config.audience[0]),t.sign(r,this.config.secret,o)}async hashPassword(e){let{default:t}=await import('bcryptjs');return t.hash(e,this.config.saltRounds)}parseExpiresIn(e){if(typeof e=="number")return e;let t=e.match(/^(\d+)([smhd])$/);if(!t)return 864e5;let r=parseInt(t[1],10);switch(t[2]){case "s":return r*1e3;case "m":return r*6e4;case "h":return r*36e5;case "d":return r*864e5;default:return 864e5}}};function Rr(s,e){return new H(s,e)}function _(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var M=class{adapter;config;constructor(e,t){this.adapter=e,this.config={..._(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},i=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),i}async publishVersion(e){let t=await this.adapter.getVersion(e.collection,e.versionId);if(!t)throw new Error("Version not found");if(t.status==="published")throw new Error("Version is already published");await this.adapter.publishVersion(e);}async unpublishDocument(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:1e3});for(let o of r)if(o.status==="published"){await this.createVersion({collection:e,documentId:t,data:o.data,status:"draft",createdBy:"system",changeDescription:"Unpublished document"});break}}async revertToVersion(e,t,r,o){if(!await this.adapter.getVersion(e,r))throw new Error("Version not found");return await this.adapter.revertToVersion({collection:e,documentId:t,versionId:r,userId:o})}async getVersionHistory(e,t,r=20,o=0){return this.adapter.getVersions({collection:e,documentId:t,limit:r,offset:o})}async compareTwoVersions(e,t,r,o){return this.adapter.compareVersions({collection:e,documentId:t,versionA:r,versionB:o})}async getLatestDraft(e,t){return this.adapter.getLatestVersion(e,t)}async getPublishedVersion(e,t){return this.adapter.getPublishedVersion(e,t)}async getVersion(e,t){return this.adapter.getVersion(e,t)}async schedulePublish(e,t,r,o){if(!this.config.scheduleEnabled)throw new Error("Scheduled publishing is not enabled");if(!await this.adapter.getVersion(e,r))throw new Error("Version not found")}async deleteVersionHistory(e,t){await this.adapter.deleteVersions(e,t);}async pruneOldVersions(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:this.config.maxVersionsPerDocument+100});if(r.length<=this.config.maxVersionsPerDocument)return;r.slice(0,this.config.maxVersionsPerDocument);let i=r.slice(this.config.maxVersionsPerDocument);for(let n of i)if(n.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Dr(s,e){return new M(s,e)}function Ir(s){return s==="published"}function Lr(s){return s==="draft"}function Er(s){return s==="archived"}function Ur(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Vr(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Ve(s){return {collections:Ur(s.collections),globals:Vr(s.globals),adapter:s.adapter,plugins:s.plugins,auth:s.auth,cors:s.cors,admin:s.admin,upload:s.upload,graphQL:s.graphQL,typescript:s.typescript,localization:s.localization,rateLimit:s.rateLimit,debug:s.debug}}var Or=Ve;function Hr(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:i,url:n}=s;if(!e)return "";let a=e.siteName||"",l=r||t?.defaultTitle||a,c=t?.titleTemplate,g=t?.separator||" | ",d=t?.siteNameInTitle!==false,u=c?c.replace(/\{\{title\}\}/g,l).replace(/\{\{siteName\}\}/g,d?a:"").replace(/\{\{separator\}\}/g,g).replace(/\s+/g," ").trim():l,y=o||t?.defaultDescription||e.siteDescription||"",f=i||e.siteOgImage?.url||"",F=n||e.siteUrl||"",m=`
|
|
2
2
|
<title>${u}</title>
|
|
3
3
|
<meta name="description" content="${y}">
|
|
4
4
|
`;e.siteFavicon?.url&&(m+=`
|
package/dist/mongodb/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';require('../chunk-UBHFUFD4.cjs');var
|
|
1
|
+
'use strict';require('../chunk-UBHFUFD4.cjs');var chunkDNLO7PK6_cjs=require('../chunk-DNLO7PK6.cjs'),chunkATLSIYRH_cjs=require('../chunk-ATLSIYRH.cjs');require('../chunk-W4ZDETHA.cjs'),require('../chunk-Q3Q7BJVQ.cjs'),require('../chunk-AHSFSERC.cjs');Object.defineProperty(exports,"MongoDBAdapter",{enumerable:true,get:function(){return chunkDNLO7PK6_cjs.a}});Object.defineProperty(exports,"createMongoDBAdapter",{enumerable:true,get:function(){return chunkDNLO7PK6_cjs.b}});Object.defineProperty(exports,"MongoDBAuthAdapter",{enumerable:true,get:function(){return chunkATLSIYRH_cjs.a}});
|
package/dist/mongodb/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as AbstractBaseAdapter } from '../base-
|
|
2
|
-
import { F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindVersionsArgs, g as VersionRecord, h as CreateVersionArgs } from '../types-
|
|
1
|
+
import { A as AbstractBaseAdapter } from '../base-Belr0_tE.cjs';
|
|
2
|
+
import { F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindVersionsArgs, g as VersionRecord, h as CreateVersionArgs } from '../types-CM9P5IfD.cjs';
|
|
3
3
|
import { A as AuthAdapter, U as UserRole, c as AuthUser, S as Session, e as AuditLogFilter, d as AuditLog } from '../types-CpjuXbe7.cjs';
|
|
4
|
-
import '../types-
|
|
4
|
+
import '../types-d0sRWA-r.cjs';
|
|
5
5
|
|
|
6
6
|
declare class MongoDBAdapter extends AbstractBaseAdapter {
|
|
7
7
|
client: any;
|
package/dist/mongodb/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as AbstractBaseAdapter } from '../base-
|
|
2
|
-
import { F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindVersionsArgs, g as VersionRecord, h as CreateVersionArgs } from '../types-
|
|
1
|
+
import { A as AbstractBaseAdapter } from '../base-D5VkUbPm.js';
|
|
2
|
+
import { F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindVersionsArgs, g as VersionRecord, h as CreateVersionArgs } from '../types-B7Zn7cy6.js';
|
|
3
3
|
import { A as AuthAdapter, U as UserRole, c as AuthUser, S as Session, e as AuditLogFilter, d as AuditLog } from '../types-CpjuXbe7.js';
|
|
4
|
-
import '../types-
|
|
4
|
+
import '../types-d0sRWA-r.js';
|
|
5
5
|
|
|
6
6
|
declare class MongoDBAdapter extends AbstractBaseAdapter {
|
|
7
7
|
client: any;
|
package/dist/mongodb/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import'../chunk-QRXDCV6K.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'../chunk-
|
|
1
|
+
import'../chunk-QRXDCV6K.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'../chunk-7ORSLR3S.js';export{a as MongoDBAuthAdapter}from'../chunk-P7CESLDJ.js';import'../chunk-4YYBWCDJ.js';import'../chunk-KDNYHLD2.js';import'../chunk-5J6HXUF6.js';
|
package/dist/rest/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk5KHTAW4H_cjs=require('../chunk-5KHTAW4H.cjs');require('../chunk-AJAZ7D3W.cjs'),require('../chunk-WIZ6C5QZ.cjs'),require('../chunk-GFU7AOI3.cjs'),require('../chunk-ET6NN2V2.cjs'),require('../chunk-HVXO3OFB.cjs'),require('../chunk-4FV3HQBI.cjs'),require('../chunk-NY47CFVP.cjs'),require('../chunk-QAJS4EXW.cjs'),require('../chunk-GYQMNXXW.cjs'),require('../chunk-MIOMMB23.cjs'),require('../chunk-DNLO7PK6.cjs'),require('../chunk-ATLSIYRH.cjs'),require('../chunk-W4ZDETHA.cjs'),require('../chunk-Q3Q7BJVQ.cjs'),require('../chunk-AHSFSERC.cjs');Object.defineProperty(exports,"createHonoApp",{enumerable:true,get:function(){return chunk5KHTAW4H_cjs.s}});Object.defineProperty(exports,"createRESTAPI",{enumerable:true,get:function(){return chunk5KHTAW4H_cjs.t}});
|
package/dist/rest/index.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
-
import { B as BaseAdapter, i as User } from '../types-
|
|
3
|
-
import { R as Registry } from '../index-
|
|
4
|
-
import { i as createWebhookService } from '../WebhookService-
|
|
5
|
-
import '../types-
|
|
2
|
+
import { B as BaseAdapter, i as User } from '../types-CM9P5IfD.cjs';
|
|
3
|
+
import { R as Registry } from '../index-ChfSBo05.cjs';
|
|
4
|
+
import { i as createWebhookService } from '../WebhookService-C-AiI-mY.cjs';
|
|
5
|
+
import '../types-d0sRWA-r.cjs';
|
|
6
6
|
import 'zod';
|
|
7
7
|
|
|
8
8
|
interface HonoAppOptions {
|
package/dist/rest/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
-
import { B as BaseAdapter, i as User } from '../types-
|
|
3
|
-
import { R as Registry } from '../index-
|
|
4
|
-
import { i as createWebhookService } from '../WebhookService-
|
|
5
|
-
import '../types-
|
|
2
|
+
import { B as BaseAdapter, i as User } from '../types-B7Zn7cy6.js';
|
|
3
|
+
import { R as Registry } from '../index-BitS8SsT.js';
|
|
4
|
+
import { i as createWebhookService } from '../WebhookService-BU7tpsju.js';
|
|
5
|
+
import '../types-d0sRWA-r.js';
|
|
6
6
|
import 'zod';
|
|
7
7
|
|
|
8
8
|
interface HonoAppOptions {
|
package/dist/rest/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{s as createHonoApp,t as createRESTAPI}from'../chunk-
|
|
1
|
+
export{s as createHonoApp,t as createRESTAPI}from'../chunk-O6WZLSKJ.js';import'../chunk-7WOX27LK.js';import'../chunk-K6WUOU6P.js';import'../chunk-AE6GXUT7.js';import'../chunk-2W4FK6CJ.js';import'../chunk-NRLIGDYF.js';import'../chunk-QIP7PY2U.js';import'../chunk-HLSB2MCK.js';import'../chunk-MTFJDAPX.js';import'../chunk-RHCWCG3O.js';import'../chunk-OG7CNQGU.js';import'../chunk-7ORSLR3S.js';import'../chunk-P7CESLDJ.js';import'../chunk-4YYBWCDJ.js';import'../chunk-KDNYHLD2.js';import'../chunk-5J6HXUF6.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as GlobalConfig, C as CollectionConfig } from '../types-
|
|
2
|
-
import '../types-
|
|
1
|
+
import { G as GlobalConfig, C as CollectionConfig } from '../types-CM9P5IfD.cjs';
|
|
2
|
+
import '../types-d0sRWA-r.cjs';
|
|
3
3
|
|
|
4
4
|
declare const minimalCollections: Record<string, any>;
|
|
5
5
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as GlobalConfig, C as CollectionConfig } from '../types-
|
|
2
|
-
import '../types-
|
|
1
|
+
import { G as GlobalConfig, C as CollectionConfig } from '../types-B7Zn7cy6.js';
|
|
2
|
+
import '../types-d0sRWA-r.js';
|
|
3
3
|
|
|
4
4
|
declare const minimalCollections: Record<string, any>;
|
|
5
5
|
|
package/dist/trpc/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { B as BaseAdapter, R as Request, i as User, b as FindResult } from '../types-
|
|
2
|
-
import { i as createWebhookService } from '../WebhookService-
|
|
3
|
-
import '../types-
|
|
1
|
+
import { B as BaseAdapter, R as Request, i as User, b as FindResult } from '../types-CM9P5IfD.cjs';
|
|
2
|
+
import { i as createWebhookService } from '../WebhookService-C-AiI-mY.cjs';
|
|
3
|
+
import '../types-d0sRWA-r.cjs';
|
|
4
4
|
|
|
5
5
|
interface ApiKeyContext {
|
|
6
6
|
userId: string;
|
package/dist/trpc/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { B as BaseAdapter, R as Request, i as User, b as FindResult } from '../types-
|
|
2
|
-
import { i as createWebhookService } from '../WebhookService-
|
|
3
|
-
import '../types-
|
|
1
|
+
import { B as BaseAdapter, R as Request, i as User, b as FindResult } from '../types-B7Zn7cy6.js';
|
|
2
|
+
import { i as createWebhookService } from '../WebhookService-BU7tpsju.js';
|
|
3
|
+
import '../types-d0sRWA-r.js';
|
|
4
4
|
|
|
5
5
|
interface ApiKeyContext {
|
|
6
6
|
userId: string;
|
|
@@ -96,7 +96,13 @@ interface SelectField extends BaseField {
|
|
|
96
96
|
options?: Array<{
|
|
97
97
|
label: string;
|
|
98
98
|
value: string;
|
|
99
|
-
}
|
|
99
|
+
}> | ((args: {
|
|
100
|
+
data: any;
|
|
101
|
+
siblingData: any;
|
|
102
|
+
}) => Array<{
|
|
103
|
+
label: string;
|
|
104
|
+
value: string;
|
|
105
|
+
}>);
|
|
100
106
|
dynamicOptions?: string;
|
|
101
107
|
hasMany?: boolean;
|
|
102
108
|
defaultValue?: string | string[];
|
|
@@ -106,7 +112,13 @@ interface RadioField extends BaseField {
|
|
|
106
112
|
options: Array<{
|
|
107
113
|
label: string;
|
|
108
114
|
value: string;
|
|
109
|
-
}
|
|
115
|
+
}> | ((args: {
|
|
116
|
+
data: any;
|
|
117
|
+
siblingData: any;
|
|
118
|
+
}) => Array<{
|
|
119
|
+
label: string;
|
|
120
|
+
value: string;
|
|
121
|
+
}>);
|
|
110
122
|
defaultValue?: string;
|
|
111
123
|
}
|
|
112
124
|
interface ColorField extends BaseField {
|
|
@@ -96,7 +96,13 @@ interface SelectField extends BaseField {
|
|
|
96
96
|
options?: Array<{
|
|
97
97
|
label: string;
|
|
98
98
|
value: string;
|
|
99
|
-
}
|
|
99
|
+
}> | ((args: {
|
|
100
|
+
data: any;
|
|
101
|
+
siblingData: any;
|
|
102
|
+
}) => Array<{
|
|
103
|
+
label: string;
|
|
104
|
+
value: string;
|
|
105
|
+
}>);
|
|
100
106
|
dynamicOptions?: string;
|
|
101
107
|
hasMany?: boolean;
|
|
102
108
|
defaultValue?: string | string[];
|
|
@@ -106,7 +112,13 @@ interface RadioField extends BaseField {
|
|
|
106
112
|
options: Array<{
|
|
107
113
|
label: string;
|
|
108
114
|
value: string;
|
|
109
|
-
}
|
|
115
|
+
}> | ((args: {
|
|
116
|
+
data: any;
|
|
117
|
+
siblingData: any;
|
|
118
|
+
}) => Array<{
|
|
119
|
+
label: string;
|
|
120
|
+
value: string;
|
|
121
|
+
}>);
|
|
110
122
|
defaultValue?: string;
|
|
111
123
|
}
|
|
112
124
|
interface ColorField extends BaseField {
|
package/package.json
CHANGED
package/dist/chunk-6JHNHMGB.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkQ3Q7BJVQ_cjs=require('./chunk-Q3Q7BJVQ.cjs'),graphql=require('graphql');var Z=class{db;tenantID;user;caches=new Map;pending=new Map;waiting=new Map;flushScheduled=false;constructor(r){this.db=r.db,this.tenantID=r.tenantID,this.user=r.user;}getCacheKey(r){return r}async load(r,e){let l=this.getCacheKey(r),y=this.caches.get(l);if(y||(y=new Map,this.caches.set(l,y)),y.has(e))return y.get(e);let a=this.pending.get(l);return a||(a=new Set,this.pending.set(l,a)),a.add(e),y.set(e,void 0),this.flushScheduled||(this.flushScheduled=true,queueMicrotask(()=>{this.flushScheduled=false,this.flushAll();})),new Promise(i=>{let o=this.waiting.get(`${l}:${e}`);o||(o=[],this.waiting.set(`${l}:${e}`,o)),o.push(i);})}async flushAll(){for(let[r,e]of this.pending){if(e.size===0)continue;let l=this.caches.get(r),y=await this.db.find({collection:r,where:{id:{in:Array.from(e)}},limit:e.size,tenantID:this.tenantID,draft:!!this.user});for(let a of y.docs||[])if(a&&a.id){l.set(a.id,a);let i=this.waiting.get(`${r}:${a.id}`);i&&(i.forEach(o=>o(a)),this.waiting.delete(`${r}:${a.id}`));}}for(let[r,e]of this.waiting)e.forEach(l=>l(void 0));this.waiting.clear(),this.pending.clear();}resolveOne(r,e){return this.caches.get(this.getCacheKey(r))?.get(e)}},q=new graphql.GraphQLScalarType({name:"JSON",description:"Arbitrary JSON value",serialize(n){return n},parseValue(n){return n},parseLiteral(n){switch(n.kind){case graphql.Kind.STRING:return n.value;case graphql.Kind.INT:case graphql.Kind.FLOAT:return parseFloat(n.value);case graphql.Kind.BOOLEAN:return n.value;case graphql.Kind.OBJECT:{let r={};for(let e of n.fields)r[e.name.value]=q.parseLiteral(e.value);return r}case graphql.Kind.LIST:return n.values.map(r=>q.parseLiteral(r));case graphql.Kind.NULL:return null;default:return null}}});function se(n){return r=>{let e=0;return {Field(){e++,e>n&&r.reportError(new Error(`Query exceeds max depth of ${n}`));},leaveField(){e--;}}}}function I(n){return n.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function H(n){let r=I(n);return r.charAt(0).toLowerCase()+r.slice(1)}function v(n){return n.endsWith("s")&&n.length>1?n.slice(0,-1):n}async function E(n,r,e){let l=n.access?.[r];if(e.apiKey){if(e.apiKey.permissions?.length>0){let a=n.slug,o=`${a}:${r==="read"?"read":r==="create"?"create":"update"}`;return !chunkNY47CFVP_cjs.h(e.apiKey.permissions,o)&&!chunkNY47CFVP_cjs.h(e.apiKey.permissions,`${a}:admin`)?{allowed:false}:{allowed:true}}if(l){let a=await chunkNY47CFVP_cjs.a(l,{req:e.req,user:e.user,tenantID:e.tenantID});return typeof a=="boolean"?{allowed:a}:{allowed:true,extraWhere:a}}return {allowed:true}}if(e.user){let a=n.slug,o=`${a}:${r==="read"?"read":r==="create"?"create":r==="update"?"update":"delete"}`;if(!chunkQ3Q7BJVQ_cjs.a({id:e.user.id,email:e.user.email,role:e.user.role},o)&&!chunkQ3Q7BJVQ_cjs.a({id:e.user.id,email:e.user.email,role:e.user.role},`${a}:admin`)&&!l)return {allowed:false}}if(!l)return e.user?{allowed:true}:{allowed:false};let y=await chunkNY47CFVP_cjs.a(l,{req:e.req,user:e.user,tenantID:e.tenantID});return typeof y=="boolean"?{allowed:y}:{allowed:true,extraWhere:y}}async function X(n,r,e){let l=n.access?.[r];if(e.apiKey){if(e.apiKey.permissions?.length>0){let a=n.slug,i=`${a}:${r}`;return !chunkNY47CFVP_cjs.h(e.apiKey.permissions,i)&&!chunkNY47CFVP_cjs.h(e.apiKey.permissions,`${a}:admin`)&&!chunkNY47CFVP_cjs.h(e.apiKey.permissions,`${a}:*`)?{allowed:false}:{allowed:true}}if(l){let a=await chunkNY47CFVP_cjs.a(l,{req:e.req,user:e.user,tenantID:e.tenantID});return {allowed:typeof a=="boolean"?a:true}}return {allowed:true}}if(!l){if(!e.user)return {allowed:false};let a=e.user.role;return a==="super_admin"||a==="admin"?{allowed:true}:{allowed:false}}let y=await chunkNY47CFVP_cjs.a(l,{req:e.req,user:e.user,tenantID:e.tenantID});return typeof y=="boolean"?{allowed:y}:{allowed:true}}function x(n,r){return n?n.startsWith("http://")||n.startsWith("https://")||n.startsWith("blob:")||n.startsWith("data:")?n:`${(process.env.KYRO_BASE_URL||r||"http://localhost:4321").replace(/\/+$/,"")}${n.startsWith("/")?"":"/"}${n}`:null}function K(n,r){return n&&(n.url&&(n.url=x(n.url,r)),n.thumbnailUrl&&(n.thumbnailUrl=x(n.thumbnailUrl,r)),n)}function k(n,r,e,l=false,y="Root",a=new Map){switch(n.type){case "text":case "email":case "password":case "textarea":case "color":case "code":case "markdown":case "date":case "select":case "radio":return n.hasMany?new graphql.GraphQLList(graphql.GraphQLString):graphql.GraphQLString;case "list":return new graphql.GraphQLList(graphql.GraphQLString);case "upload":{let i=n;if(l)return i.hasMany?new graphql.GraphQLList(graphql.GraphQLString):graphql.GraphQLString;if(i.relationTo&&e?.[i.relationTo]){let o=e[i.relationTo];return i.hasMany?new graphql.GraphQLList(o):o}return q}case "image":{if(l)return graphql.GraphQLString;let i=n;return i.relationTo&&e?.[i.relationTo]?e[i.relationTo]:q}case "number":{let i=n.integer?graphql.GraphQLInt:graphql.GraphQLFloat;return n.hasMany?new graphql.GraphQLList(i):i}case "checkbox":return graphql.GraphQLBoolean;case "json":case "richtext":return q;case "blocks":{if(l)return q;let i=n,o=(i.blocks||[]).map(b=>{let w=`Block_${I(b.slug)}`,u=a.get(w);return u||(u=new graphql.GraphQLObjectType({name:w,fields:()=>{let m=j(b.fields||[],r,e,w,a);return m.blockType={type:graphql.GraphQLString},m.name={type:graphql.GraphQLString},m}}),a.set(w,u)),u});if(o.length===0)return q;let p=`${y}_${I(i.name)}_Blocks`,D=a.get(p);return D||(D=new graphql.GraphQLUnionType({name:p,types:o,resolveType:b=>`Block_${I(b.blockType||b.type)}`}),a.set(p,D)),new graphql.GraphQLList(D)}case "tabs":{if(l)return q;let i=n,o=`${y}_${I(i.name)}_Tabs`,p=a.get(o);return p||(p=new graphql.GraphQLObjectType({name:o,fields:()=>j(i.tabs?.flatMap(D=>D.fields||[])||[],r,e,o,a)}),a.set(o,p)),p}case "relationship":{let i=n.relationTo;if((i==="*"||Array.isArray(i)&&i.includes("*"))&&(i=r.getCollections().map(o=>o.slug)),typeof i=="string"){if(l)return n.hasMany?new graphql.GraphQLList(graphql.GraphQLString):graphql.GraphQLString;if(e?.[i])return n.hasMany?new graphql.GraphQLList(e[i]):e[i];let o=r.getCollection(i);if(o)return new graphql.GraphQLObjectType({name:`${I(i)}Ref`,fields:()=>({id:{type:graphql.GraphQLString},...N(o,r,e,a)})})}else if(Array.isArray(i)){if(l)return n.hasMany?new graphql.GraphQLList(q):q;let o=i.map(u=>{if(e?.[u])return e[u];let m=r.getCollection(u);if(m){let c=a.get(`${I(u)}Ref`);return c||(c=new graphql.GraphQLObjectType({name:`${I(u)}Ref`,fields:()=>({id:{type:graphql.GraphQLString},...N(m,r,e,a)})}),a.set(`${I(u)}Ref`,c)),c}return null}).filter(Boolean);if(o.length===0)return q;let p=`${y}_${I(n.name||"Ref")}_PolyUnion`,D=a.get(p);D||(D=new graphql.GraphQLUnionType({name:p,types:o,resolveType:u=>{if(u.__collection&&u.__collection!=="*")return e?.[u.__collection]?e[u.__collection].name:`${I(u.__collection)}Ref`}}),a.set(p,D));let b=`${y}_${I(n.name||"Ref")}_PolyWrapper`,w=a.get(b);return w||(w=new graphql.GraphQLObjectType({name:b,fields:{relationTo:{type:graphql.GraphQLString},value:{type:D}}}),a.set(b,w)),n.hasMany?new graphql.GraphQLList(w):w}return q}case "array":{if(l)return new graphql.GraphQLList(q);let i=n,o=`${y}_${I(i.name)}_ArrayItem`,p=a.get(o);return p||(p=new graphql.GraphQLObjectType({name:o,fields:()=>{let D=j(i.fields||[],r,e,o,a);return D.id={type:graphql.GraphQLString},D}}),a.set(o,p)),new graphql.GraphQLList(p)}case "group":{if(l)return q;let i=n,o=`${y}_${I(i.name)}_Group`,p=a.get(o);return p||(p=new graphql.GraphQLObjectType({name:o,fields:()=>j(i.fields||[],r,e,o,a)}),a.set(o,p)),p}default:return graphql.GraphQLString}}function j(n,r,e,l,y=new Map){let a={};for(let i of n){if(i.type==="tabs"&&!i.name){for(let o of i.tabs||[]){let p=j(o.fields||[],r,e,l,y);Object.assign(a,p);}continue}if(i.type==="row"||i.type==="collapsible"){let o=j(i.fields||[],r,e,l,y);Object.assign(a,o);continue}if(i.name&&i.admin?.hidden!==true){let o=ie(i,r,e,l,y);o&&(a[i.name]=o);}}return a}function N(n,r,e,l=new Map){return j(n.fields,r,e,I(v(n.slug)),l)}function ie(n,r,e,l,y=new Map){if(!n.name)return null;let a=n.deprecated||void 0;if(n.type==="upload"){let o=k(n,r,e,false,l,y),p=n;return {type:n.required?new graphql.GraphQLNonNull(o):o,description:n.admin?.description||n.label,deprecationReason:a,resolve:async(D,b,w)=>{let u=w?.relationLoader,m=D?.[p.name],c=w?.req?.url?new URL(w.req.url).origin:void 0;if(!m)return null;if(p.hasMany){let L=Array.isArray(m)?m:[];return Promise.all(L.map(async f=>{let G=typeof f=="string"?f:f?.id;if(!G||typeof f=="object"&&f?.url)return K(f,c);if(u){let S=u.resolveOne(p.relationTo,G);if(S)return K(S,c);let t=await u.load(p.relationTo,G);return t?K(t,c):null}return {id:G}}))}let h=typeof m=="string"?m:m?.id;if(!h||typeof m=="object"&&m?.url)return K(m,c);if(u){let L=u.resolveOne(p.relationTo,h);if(L)return K(L,c);let f=await u.load(p.relationTo,h);return f?K(f,c):null}return {id:h}}}}if(n.type==="relationship"&&!n.hasMany){let o=k(n,r,e,false,l,y);return {type:n.required?new graphql.GraphQLNonNull(o):o,description:n.admin?.description||n.label,deprecationReason:a,resolve:async(p,D,b)=>{let w=b?.relationLoader,u=n,m=p?.[u.name];if(!m)return null;let c=Array.isArray(u.relationTo)||u.relationTo==="*",h=c?m?.relationTo:u.relationTo,L=c?m?.value:m;if(c&&typeof m=="string"&&(h=u.relationTo[0],L=m),c&&h==="*")return null;if(w&&typeof L=="string"&&typeof h=="string"&&h!=="*"){let f=w.resolveOne(h,L);if(f)return c?{relationTo:h,value:{...f,__collection:h}}:f;let G=await w.load(h,L);return G?c?{relationTo:h,value:{...G,__collection:h}}:G:null}return c?{relationTo:h,value:{id:L,__collection:h}}:{id:L}}}}if(n.type==="relationship"&&n.hasMany)return {type:k(n,r,e,false,l,y),description:n.admin?.description||n.label,deprecationReason:a,resolve:async(p,D,b)=>{let w=b?.relationLoader,u=n,m=p?.[u.name]||[];if(!m.length)return [];let c=Array.isArray(u.relationTo)||u.relationTo==="*";if(w){let h=[];for(let L of m){let f=c?L?.relationTo:u.relationTo,G=c?L?.value:L;if(c&&typeof L=="string"&&(f=u.relationTo[0],G=L),!(c&&f==="*")){if(typeof G=="string"&&typeof f=="string"&&f!=="*"){let S=w.resolveOne(f,G);if(S){h.push(c?{relationTo:f,value:{...S,__collection:f}}:S);continue}let t=await w.load(f,G);if(t){h.push(c?{relationTo:f,value:{...t,__collection:f}}:t);continue}continue}h.push(c?{relationTo:f,value:{id:G,__collection:f}}:{id:G});}}return h}return m.map(h=>{let L=c?h?.relationTo:u.relationTo,f=c?h?.value:h;return c&&typeof h=="string"&&(L=u.relationTo[0],f=h),c?{relationTo:L,value:{id:f}}:{id:f}})}};if(n.type==="blocks"){let o=k(n,r,e,false,l,y);return {type:n.required?new graphql.GraphQLNonNull(o):o,description:n.admin?.description||n.label,deprecationReason:a,resolve:p=>{let D=p?.[n.name];return Array.isArray(D)?D.map(b=>b&&b.data&&b.type?{...b.data,id:b.id,type:b.type,blockType:b.type,name:b.name}:b):D}}}let i=k(n,r,e,false,l,y);return {type:n.required?new graphql.GraphQLNonNull(i):i,description:n.admin?.description||n.label,deprecationReason:a}}function ee(n){let{registry:r,db:e,user:l,req:y,tenantID:a,apiKey:i,settings:o}=n;if(o?.access?.apiAccess?.graphqlEnabled===false)throw new Error("GraphQL API is disabled");let D=r.getCollections(),b=r.getGlobals(),w={},u={},m=new Map;for(let t of D){w[t.slug]=new graphql.GraphQLObjectType({name:I(v(t.slug)),fields:()=>({id:{type:graphql.GraphQLString},...N(t,r,w,m),...t.timestamps?{createdAt:{type:graphql.GraphQLString},updatedAt:{type:graphql.GraphQLString}}:{},...t.tenantScoped?{tenantID:{type:graphql.GraphQLString}}:{}})});let Q={};for(let _ of t.fields)_.name&&_.name!=="id"&&(Q[_.name]={type:k(_,r,w,true)});u[t.slug]=new graphql.GraphQLInputObjectType({name:`${I(v(t.slug))}Input`,fields:()=>Q});}let c={},h={};for(let t of b)c[t.slug]=new graphql.GraphQLObjectType({name:`${I(t.slug)}Global`,fields:()=>({id:{type:graphql.GraphQLString},...N({slug:t.slug,fields:t.fields},r,w)})}),h[t.slug]=new graphql.GraphQLInputObjectType({name:`${I(t.slug)}GlobalInput`,fields:()=>{let Q={};for(let _ of t.fields)_.name&&_.name!=="id"&&(Q[_.name]={type:k(_,r,w,true)});return Q}});let L={};for(let t of D){let Q=w[t.slug];Q&&(L[H(t.slug)]={type:new graphql.GraphQLObjectType({name:`${I(v(t.slug))}FindResult`,fields:{docs:{type:new graphql.GraphQLList(Q)},totalDocs:{type:graphql.GraphQLInt},page:{type:graphql.GraphQLInt},totalPages:{type:graphql.GraphQLInt},hasNextPage:{type:graphql.GraphQLBoolean},hasPrevPage:{type:graphql.GraphQLBoolean}}}),args:{where:{type:graphql.GraphQLString},sort:{type:graphql.GraphQLString},limit:{type:graphql.GraphQLInt},page:{type:graphql.GraphQLInt},draft:{type:graphql.GraphQLBoolean}},resolve:async(_,T,s)=>{let d=await E(t,"read",{user:s.user,req:s.req,tenantID:s.tenantID,apiKey:s.apiKey});if(!d.allowed)throw new Error("Access denied");s.tenantID&&e.setTenantContext({tenantId:s.tenantID,userId:s.user?.id??"",role:s.user?.role,isSuperAdmin:s.user?.role==="super_admin"});let A={};if(T.where)try{A=JSON.parse(T.where);}catch{}d.extraWhere&&(A={...A,...d.extraWhere});let O=T.draft??!!s.user;return e.find({collection:t.slug,where:A,sort:T.sort,limit:T.limit||10,page:T.page||1,tenantID:s.tenantID,draft:O})}},L[H(v(t.slug))]={type:Q,args:{id:{type:graphql.GraphQLString},slug:{type:graphql.GraphQLString},draft:{type:graphql.GraphQLBoolean}},resolve:async(_,T,s)=>{if(!T.id&&!T.slug)throw new Error("Either id or slug is required");if(!(await E(t,"read",{user:s.user,req:s.req,tenantID:s.tenantID,apiKey:s.apiKey})).allowed)throw new Error("Access denied");s.tenantID&&e.setTenantContext({tenantId:s.tenantID,userId:s.user?.id??"",role:s.user?.role,isSuperAdmin:s.user?.role==="super_admin"});let A=T.draft??!!s.user;return T.id?e.findByID({collection:t.slug,id:T.id,tenantID:s.tenantID,draft:A}):(await e.find({collection:t.slug,where:{slug:{equals:T.slug}},limit:1,page:1,tenantID:s.tenantID,draft:A})).docs?.[0]||null}},L[`count${I(t.slug)}`]={type:new graphql.GraphQLObjectType({name:`${I(v(t.slug))}Count`,fields:{totalDocs:{type:graphql.GraphQLInt}}}),args:{where:{type:graphql.GraphQLString}},resolve:async(_,T,s)=>{if(!(await E(t,"read",{user:s.user,req:s.req,tenantID:s.tenantID,apiKey:s.apiKey})).allowed)return {totalDocs:0};let A={};if(T.where)try{A=JSON.parse(T.where);}catch{}return {totalDocs:await e.count({collection:t.slug,where:A,tenantID:s.tenantID})}}});}for(let t of b){let Q=c[t.slug];Q&&(L[H(v(t.slug))]={type:Q,resolve:async(_,T,s)=>{if(!(await X(t,"read",{user:s.user,req:s.req,tenantID:s.tenantID,apiKey:s.apiKey})).allowed)throw new Error("Access denied: cannot read global");return s.tenantID&&e.setTenantContext({tenantId:s.tenantID,userId:s.user?.id??"",role:s.user?.role,isSuperAdmin:s.user?.role==="super_admin"}),e.findOne({collection:`_globals_${t.slug}`,where:{},tenantID:s.tenantID})}});}let f=new graphql.GraphQLObjectType({name:"Query",fields:L}),G={};for(let t of D){let Q=w[t.slug],_=u[t.slug];!Q||!_||(G[`create${I(v(t.slug))}`]={type:new graphql.GraphQLObjectType({name:`${I(v(t.slug))}CreateResult`,fields:{doc:{type:Q},message:{type:graphql.GraphQLString}}}),args:{data:{type:new graphql.GraphQLNonNull(_)}},resolve:async(T,s,d)=>{if(!(await E(t,"create",{user:d.user,req:d.req,tenantID:d.tenantID,apiKey:d.apiKey})).allowed)throw new Error("Access denied: cannot create");d.tenantID&&e.setTenantContext({tenantId:d.tenantID,userId:d.user?.id??"",role:d.user?.role,isSuperAdmin:d.user?.role==="super_admin"});let J=r.getCreateZodSchema(t.slug).parse(s.data);return {doc:await e.create({collection:t.slug,data:J,tenantID:d.tenantID}),message:"Created successfully"}}},G[`update${I(v(t.slug))}`]={type:new graphql.GraphQLObjectType({name:`${I(v(t.slug))}UpdateResult`,fields:{doc:{type:Q},message:{type:graphql.GraphQLString}}}),args:{id:{type:new graphql.GraphQLNonNull(graphql.GraphQLString)},data:{type:new graphql.GraphQLNonNull(_)},baseUpdatedAt:{type:graphql.GraphQLString}},resolve:async(T,s,d)=>{if(!(await E(t,"update",{user:d.user,req:d.req,tenantID:d.tenantID,apiKey:d.apiKey})).allowed)throw new Error("Access denied: cannot update");if(d.tenantID&&e.setTenantContext({tenantId:d.tenantID,userId:d.user?.id??"",role:d.user?.role,isSuperAdmin:d.user?.role==="super_admin"}),s.baseUpdatedAt){let W=await e.findByID({collection:t.slug,id:s.id,tenantID:d.tenantID,draft:true});if(W&&W.updatedAt&&s.baseUpdatedAt!==W.updatedAt)throw new Error(`Revision conflict: document has changed since ${s.baseUpdatedAt}. Current updatedAt: ${W.updatedAt}`)}let J=r.getUpdateZodSchema(t.slug).parse(s.data);return {doc:await e.update({collection:t.slug,id:s.id,data:J,tenantID:d.tenantID}),message:"Updated successfully"}}},G[`delete${I(v(t.slug))}`]={type:new graphql.GraphQLObjectType({name:`${I(v(t.slug))}DeleteResult`,fields:{doc:{type:Q},message:{type:graphql.GraphQLString}}}),args:{id:{type:new graphql.GraphQLNonNull(graphql.GraphQLString)}},resolve:async(T,s,d)=>{if(!(await E(t,"delete",{user:d.user,req:d.req,tenantID:d.tenantID,apiKey:d.apiKey})).allowed)throw new Error("Access denied: cannot delete");return d.tenantID&&e.setTenantContext({tenantId:d.tenantID,userId:d.user?.id??"",role:d.user?.role,isSuperAdmin:d.user?.role==="super_admin"}),{doc:await e.delete({collection:t.slug,id:s.id,tenantID:d.tenantID}),message:"Deleted successfully"}}});}for(let t of b){let Q=h[t.slug];Q&&(G[`update${I(t.slug)}`]={type:new graphql.GraphQLObjectType({name:`${I(t.slug)}UpdateResult`,fields:{doc:{type:c[t.slug]||graphql.GraphQLString},message:{type:graphql.GraphQLString}}}),args:{data:{type:new graphql.GraphQLNonNull(Q)}},resolve:async(_,T,s)=>{if(!(await X(t,"update",{user:s.user,req:s.req,tenantID:s.tenantID,apiKey:s.apiKey})).allowed)throw new Error("Access denied: cannot update global");s.tenantID&&e.setTenantContext({tenantId:s.tenantID,userId:s.user?.id??"",role:s.user?.role,isSuperAdmin:s.user?.role==="super_admin"});let A=await e.findOne({collection:`_globals_${t.slug}`,where:{},tenantID:s.tenantID}),O;return A?O=await e.update({collection:`_globals_${t.slug}`,id:A.id,data:T.data,tenantID:s.tenantID}):O=await e.create({collection:`_globals_${t.slug}`,data:T.data,tenantID:s.tenantID}),{doc:O,message:"Updated successfully"}}});}let S=new graphql.GraphQLObjectType({name:"Mutation",fields:G});return new graphql.GraphQLSchema({query:f,mutation:S})}function oe(n,r,e){return ee({registry:n,db:r,user:e?.user,req:e?.req,tenantID:e?.tenantID,apiKey:e?.apiKey})}
|
|
2
|
-
Object.defineProperty(exports,"e",{enumerable:true,get:function(){return graphql.printSchema}});exports.a=Z;exports.b=se;exports.c=ee;exports.d=oe;
|
package/dist/chunk-GT5P64DV.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-NZ35PV5R.js';import {a as a$2,i}from'./chunk-GJQH6NV7.js';import {c as c$1,a as a$1}from'./chunk-YLEVWUTV.js';import {f,s,a as a$4,b as b$2,c as c$3}from'./chunk-WQKF57FY.js';import {o,f as f$1,g as g$1}from'./chunk-QIP7PY2U.js';import {d,f as f$2,e,g as g$2}from'./chunk-HLSB2MCK.js';import {b,d as d$1}from'./chunk-SL3LZQCF.js';import {c}from'./chunk-GDMLWVJO.js';import {g}from'./chunk-OG7CNQGU.js';import {a as a$3,c as c$2,b as b$1,d as d$2}from'./chunk-4YYBWCDJ.js';import {z as z$1}from'zod';import {createYoga}from'graphql-yoga';import {createRequire}from'module';import {randomBytes}from'crypto';function O(s,e){for(let t of s){if(t.name===e)return true;if("tabs"in t&&t.tabs){for(let n of t.tabs)if(O(n.fields,e))return true}if("fields"in t&&t.fields&&O(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 V(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=N(s.fields,s.slug);e.push(...t);}if(s.access)for(let[t,n]of Object.entries(s.access))typeof n!="boolean"&&typeof n!="function"&&e.push(`Collection "${s.slug}" has invalid access.${t} (must be boolean or function)`);if(s.admin?.useAsTitle&&(O(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)O(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(a=>a.name==="email"),n=s.fields.some(a=>a.name==="password");t||e.push(`Collection "${s.slug}" with auth enabled requires an "email" field`),n||e.push(`Collection "${s.slug}" with auth enabled requires a "password" field`);}return e}function B(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=N(s.fields,`global:${s.slug}`);e.push(...t);}return e}function N(s,e){let t=[],n=new Set;for(let a=0;a<s.length;a++){let i=s[a];if(i.type==="row"||i.type==="collapsible"||i.type==="tabs"){if("fields"in i&&i.fields){let r=N(i.fields,e);t.push(...r);}else if("tabs"in i)for(let r of i.tabs){let c=N(r.fields,e);t.push(...c);}continue}let o=i.name;if(!o){t.push(`${e}: Field at index ${a} is missing a "name" property`);continue}if(n.has(o)&&t.push(`${e}: Duplicate field name "${o}"`),n.add(o),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(o)||t.push(`${e}: Field name "${o}" must be alphanumeric with underscores`),!i.type){t.push(`${e}: Field "${o}" is missing a "type" property`);continue}switch(i.type){case "relationship":i.relationTo||t.push(`${e}: Relationship field "${o}" is missing "relationTo"`);break;case "array":if(!i.fields||i.fields.length===0)t.push(`${e}: Array field "${o}" has no fields defined`);else {let r=N(i.fields,`${e}.${o}`);t.push(...r);}break;case "group":if(!i.fields||i.fields.length===0)t.push(`${e}: Group field "${o}" has no fields defined`);else {let r=N(i.fields,`${e}.${o}`);t.push(...r);}break;case "blocks":if(!i.blocks||i.blocks.length===0)t.push(`${e}: Blocks field "${o}" has no blocks defined`);else {let r=we(i.blocks,`${e}.${o}`);t.push(...r);}break;case "select":case "radio":if((!i.options||i.options.length===0)&&!i.dynamicOptions)t.push(`${e}: ${i.type} field "${o}" has no options defined`);else if(i.options){let r=i.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${i.type} field "${o}" has duplicate option values`);}break;case "upload":i.relationTo||t.push(`${e}: Upload field "${o}" is missing "relationTo"`);break}"min"in i&&"max"in i&&i.min>i.max&&t.push(`${e}: Field "${o}" has min greater than max`),"minLength"in i&&"maxLength"in i&&i.minLength>i.maxLength&&t.push(`${e}: Field "${o}" has minLength greater than maxLength`),"minRows"in i&&"maxRows"in i&&i.minRows>i.maxRows&&t.push(`${e}: Field "${o}" has minRows greater than maxRows`);}return t}function we(s,e){let t=[],n=new Set;for(let a of s){if(!a.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(n.has(a.slug)&&t.push(`${e}: Duplicate block slug "${a.slug}"`),n.add(a.slug),a.label||t.push(`${e}: Block "${a.slug}" is missing a "label" property`),!a.fields||a.fields.length===0)t.push(`${e}: Block "${a.slug}" has no fields defined`);else {let i=N(a.fields,`${e}.${a.slug}`);t.push(...i);}}return t}function pe(s,e=[]){let t=[],n=new Set;for(let a of s)n.has(a.slug)&&t.push(`Duplicate collection slug "${a.slug}"`),n.add(a.slug);for(let a of e)n.has(a.slug)&&t.push(`Duplicate global slug "${a.slug}"`),n.add(a.slug);for(let a of s){let i=V(a);t.push(...i);}for(let a of e){let i=B(a);t.push(...i);}for(let a of s){let i=$(a.fields,s);t.push(...i);}if(t.length>0)throw new K(t)}function $(s,e){let t=[],n=new Set(e.map(a=>a.slug));for(let a of s){if(a.type==="relationship"){let i=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let o of i)n.has(o)||console.warn(`[Kyro Config Warning]: Relationship field "${a.name}" references unknown collection "${o}". Select options will not be available until this collection is registered.`);}if(a.type==="upload"){let i=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let o of i)n.has(o)||t.push(`Upload field "${a.name}" references unknown collection "${o}"`);}if("fields"in a&&a.fields){let i=$(a.fields,e);t.push(...i);}if("tabs"in a)for(let i of a.tabs){let o=$(i.fields,e);t.push(...o);}if("blocks"in a)for(let i of a.blocks){let o=$(i.fields,e);t.push(...o);}}return t}function C(s){switch(s.type){case "text":return Fe(s);case "number":return Ie(s);case "checkbox":return $e(s);case "date":return Oe(s);case "email":return Pe(s);case "password":return Le(s);case "textarea":return ke(s);case "select":return _e(s);case "radio":return je(s);case "color":return Ze(s);case "richtext":return qe(s);case "json":return Ue(s);case "code":return Ge(s);case "upload":return fe(s);case "image":return fe(s);case "markdown":return Ke(s);case "relationship":return ye(s);case "relationship-block":return ye(s);case "array":return Ve(s);case "list":return Be(s);case "group":return Me(s);case "blocks":return ze(s);case "row":return We(s);case "collapsible":return Xe(s);case "tabs":return Je(s);default:return z$1.any()}}function Fe(s){let e=z$1.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=z$1.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ie(s){let e=s.integer?z$1.coerce.number().int():z$1.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=z$1.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function $e(s){let e=z$1.boolean();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Oe(s){let e=z$1.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=T(e,s.validate)),e}function Pe(s){let e=z$1.string().email("Invalid email");return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Le(s){let e=z$1.string().min(6,"Password must be at least 6 characters");return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function ke(s){let e=z$1.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=T(e,s.validate)),e}function _e(s){let e;if(s.options&&s.options.length>0){let t=s.options.map(n=>n.value);s.hasMany?e=z$1.array(z$1.enum(t)):e=z$1.enum(t);}else e=s.hasMany?z$1.array(z$1.string()):z$1.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function je(s){let e=s.options.map(n=>n.value),t=z$1.enum(e);return s.required||(t=t.optional().nullable()),s.validate&&(t=T(t,s.validate)),t}function Ze(s){let e=z$1.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=T(e,s.validate)),e}function qe(s){let e=z$1.array(z$1.record(z$1.any()));return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ue(s){let e=z$1.union([z$1.record(z$1.any()),z$1.array(z$1.any())]);return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ge(s){let e=z$1.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function fe(s){let e;if(s.relationTo){let t=z$1.object({id:z$1.string(),url:z$1.string().optional(),filename:z$1.string().optional(),mimeType:z$1.string().optional()});e=z$1.union([z$1.string(),t]);}else e=z$1.string();return s.hasMany&&(e=z$1.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ke(s){let e=z$1.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function ye(s){let e;return Array.isArray(s.relationTo)?e=z$1.object({relationTo:z$1.enum(s.relationTo),value:z$1.string()}):e=z$1.union([z$1.string(),z$1.object({relationTo:z$1.string(),value:z$1.string()})]),s.hasMany&&(e=z$1.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ve(s){let e=z$1.object(Object.fromEntries(s.fields.filter(n=>n.name).map(n=>[n.name,C(n)]))).passthrough(),t=z$1.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=T(t,s.validate)),t}function Be(s){let e=z$1.array(z$1.string());return s.required||(e=e.optional().nullable()),e}function Me(s){let e=z$1.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])));return s.required?e:e.optional().nullable()}function ze(s){let e=s.blocks||[];e.map(i=>z$1.object({blockType:z$1.literal(i.slug),...Object.fromEntries(i.fields.filter(o=>o.name).map(o=>[o.name,C(o)]))}));let n=e.map(i=>i.slug),a;if(n.length>0){let i=z$1.object({blockType:z$1.enum(n)}).catchall(z$1.any()),o=z$1.object({blockType:z$1.string()}).catchall(z$1.any());a=z$1.array(z$1.union([i,o,z$1.record(z$1.any())]));}else a=z$1.array(z$1.union([z$1.object({blockType:z$1.string()}).catchall(z$1.any()),z$1.record(z$1.any())]));return s.minRows&&(a=a.min(s.minRows)),s.maxRows&&(a=a.max(s.maxRows)),s.required||(a=a.optional().nullable()),s.validate&&(a=T(a,s.validate)),a}function We(s){return z$1.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function Xe(s){return z$1.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function Je(s){let e={};for(let t of s.tabs)for(let n of t.fields)n.name&&(e[n.name]=C(n));return z$1.object(e).passthrough().optional()}function T(s,e){return s.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function R(s){let e={};for(let t of s)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs){let i=R(a.fields);Object.assign(n,i);}e[t.name]=z$1.object(n).passthrough().optional();}else if(t.type==="row"&&"fields"in t){let n=R(t.fields);Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(R(t.fields)).passthrough().optional():e[t.name]=C(t);return e}function E(s){let e={};for(let t of s)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs){let i=E(a.fields);Object.assign(n,i);}e[t.name]=z$1.object(n).passthrough().optional().nullable();}else if(t.type==="row"&&"fields"in t){let n=E(t.fields);Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).passthrough().optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).passthrough().optional().nullable():e[t.name]=C(t).optional().nullable();return e}function he(s){let e=R(s.fields);return s.timestamps&&(e.createdAt=z$1.string().optional(),e.updatedAt=z$1.string().optional()),s.tenantScoped&&(e.tenantID=z$1.string().optional()),e.id=z$1.string().optional(),z$1.object(e).passthrough()}function ge(s){let e=R(s.fields);return z$1.object(e).passthrough()}function me(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs)for(let i of a.fields)i.name&&(n[i.name]=C(i).optional().nullable());e[t.name]=z$1.object(n).optional().nullable();}else if(t.type==="row"&&"fields"in t){let n={};for(let a of t.fields)a.name&&(n[a.name]=C(a).optional().nullable());Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return z$1.object(e).passthrough()}function be(s){let e={};for(let t of s.fields)t.name&&(e[t.name]=z$1.object({equals:z$1.any().optional(),not_equals:z$1.any().optional(),in:z$1.array(z$1.any()).optional(),not_in:z$1.array(z$1.any()).optional(),greater_than:z$1.number().optional(),greater_than_equal:z$1.number().optional(),less_than:z$1.number().optional(),less_than_equal:z$1.number().optional(),like:z$1.string().optional(),not_like:z$1.string().optional(),contains:z$1.string().optional(),exists:z$1.boolean().optional()}).optional());return e.AND=z$1.array(z$1.lazy(()=>z$1.object(e))).optional(),e.OR=z$1.array(z$1.lazy(()=>z$1.object(e))).optional(),z$1.object(e).optional()}function Te(s){let e=R(s.fields);return e.id=z$1.string().optional(),z$1.object(e).passthrough()}function Ce(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs)for(let i of a.fields)i.name&&(n[i.name]=C(i).optional().nullable());e[t.name]=z$1.object(n).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return z$1.object(e).passthrough()}var w=class{storageProviders=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};for(let a of this.plugins)a.extendCollection&&(t=a.extendCollection(t.slug,t));t.fields=this.applyFieldDefaults(t);let n=V(t);if(n.length>0)throw new Error(`Invalid collection config: ${n.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=B(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let n={...e};for(let a of this.plugins)a.extendGlobal&&(n=a.extendGlobal(n.slug,n));this.globals.set(n.slug,n),this.clearSchemaCache(`global:${n.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 n=this.collections.get(e);if(n){let i=he(n);return this.schemaCache.set(e,i),i}let a=this.globals.get(e);if(a){let i=Te(a);return this.schemaCache.set(`global:${e}`,i),i}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let i=ge(a);return this.schemaCache.set(t,i),i}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let o=me(a);return this.schemaCache.set(t,o),o}let i=this.globals.get(e);if(i){let o=Ce(i);return this.schemaCache.set(`global:${e}:update`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let i=be(a);return this.schemaCache.set(t,i),i}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return C(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(n=>n.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(n=>n.name==="tenantID")&&t.push({name:"tenantID",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(n=>n.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(n=>n.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(n=>n.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 n=this.globals.get(e);if(n)return n.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),n=new Map,a=i=>{for(let o of i){if(o.name&&n.set(o.name,o),"fields"in o&&o.fields&&a(o.fields),"tabs"in o)for(let r of o.tabs)a(r.fields);if("blocks"in o)for(let r of o.blocks)a(r.fields);}};return a(t),n}getVisibleFields(e){return this.getFields(e).filter(n=>!n.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();pe(e,t);}async init(e){this.validate();for(let t of this.plugins)t.init&&await t.init(e||this);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 n=this.collections.get(e)?.admin?.useAsTitle;return n||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(a=>a.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 Ye(){v=null;}function M(){return v=new w,v}var Qe={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 et(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 Ae(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:et(s,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function tt(s,e,t){let n=t[e.configKey]||{};return Ae(s,n)}function st(s,e,t){let n=t?.[e.configKey]||t;return Ae(s,n)}var Se={name:"@kyro-cms/storage-s3",version:"1.0.0",description:"S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)",init:s=>{let e=s.registry?.storageProviders;if(!e)return;let t="@kyro-cms/storage-s3";for(let n of Object.values(Qe))e.register({type:n.type,displayName:n.displayName,pluginName:t,configKey:n.configKey,configFields:n.configFields,extractConfig:a=>tt(n.type,n,a),extractRawConfig:a=>st(n.type,n,a),factory:a=>a$4(a)});}};var Ee={name:"@kyro-cms/storage-cloudinary",version:"1.0.0",description:"Cloudinary image and video storage",init:s=>{let e=s.registry?.storageProviders;e&&e.register({type:"cloudinary",displayName:"Cloudinary",pluginName:"@kyro-cms/storage-cloudinary",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:t=>({cloudName:t.cloudinary?.cloudName||"",apiKey:t.cloudinary?.apiKey||"",apiSecret:t.cloudinary?.apiSecret||"",folder:t.cloudinary?.folder,uploadPreset:t.cloudinary?.uploadPreset}),extractRawConfig:t=>{let n=t?.cloudinary||t;return {cloudName:n?.cloudName||"",apiKey:n?.apiKey||"",apiSecret:n?.apiSecret||"",folder:n?.folder,uploadPreset:n?.uploadPreset}},factory:t=>b$2(t)});}};var xe={name:"@kyro-cms/storage-ftp",version:"1.0.0",description:"FTP/SFTP storage provider",init:s=>{let e=s.registry?.storageProviders;e&&e.register({type:"ftp",displayName:"FTP",pluginName:"@kyro-cms/storage-ftp",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:t=>({host:t.ftp?.host||"",port:t.ftp?.port||21,user:t.ftp?.user||"",password:t.ftp?.password||"",secure:t.ftp?.secure||false,baseUrl:t.ftp?.baseUrl||"",prefix:t.ftp?.prefix,type:"ftp"}),extractRawConfig:t=>{let n=t?.ftp||t;return {host:n?.host||"",port:n?.port||21,user:n?.user||"",password:n?.password||"",secure:n?.secure||false,baseUrl:n?.baseUrl||"",prefix:n?.prefix,type:"ftp"}},factory:t=>c$3(t)});}};var at=[Se,Ee,xe];function z(s,e,t){let n=e.split(".");if(n.length===0)return false;let a=n[0],i=n.slice(1).join(".");for(let o of s)if(o.name===a)return i?o.fields&&Array.isArray(o.fields)||o.type==="array"&&o.fields&&Array.isArray(o.fields)?z(o.fields,i,t):false:(Object.assign(o,t),true);return false}function it(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:a,...i}=n;if(t.admin={...t.admin,...i},a&&t.fields&&Array.isArray(t.fields))for(let[o,r]of Object.entries(a))z(t.fields,o,r);}}}var W=class{registry;db;pubsub;webhookService;settings;wsServer;config;constructor(e){this.config=e,this.registry=M(),this.db=e.adapter,this.pubsub=new b(this.registry),this.webhookService=o(this.db);for(let t of at)this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&it(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.registry.init(this),this.registry.addGlobalPostInit(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: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"}]},n={slug:f$1,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:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},a$1={slug:g$1,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"}]},i=this.registry.getGlobals();if(this.db instanceof c&&this.db.dialect==="postgres"){let o=this.db,r=d.replace(/-/g,"_");o.schema[r]||(o.schema[r]=g);}await this.db.init([...this.registry.getCollections(),t,n,a$1],i),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(),n={};try{let a=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});a&&a.states&&(n=a.states);}catch{}for(let a of t)n[a]!==void 0&&e.setPluginEnabled(a,n[a]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,n=t?.secret,a=t?.checkSession!==false;return s({registry:this.registry,db:this.db,authSecret:n,authAdapter:this.config.authAdapter,checkSession:a,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e$1){let t=c$1({registry:this.registry,db:this.db,settings:this.settings});return {fetch:createYoga({schema:t,context:async({request:a})=>{let i=f$2(a),o,r;if(i&&this.db){let d=await e(i,this.db);d.user&&(o=d.user,r=g$2(d));}let c=e$1?.tenantID;return {db:this.db,registry:this.registry,user:o,req:a,tenantID:c,apiKey:r,relationLoader:new a$1({db:this.db,tenantID:c,user:o})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,n)=>{let i$1=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[o,...r]=i$1.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!o||!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 d=await a$2({db:this.db,registry:this.registry,req:t,user:e?.user,tenantID:e?.tenantID,settings:this.settings}),p=i(d)[o];if(!p)return new Response(JSON.stringify({error:{message:`Collection '${o}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let m=p[c];if(typeof m!="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 y={};if(t.method==="POST"||t.method==="PATCH")y=await t.json().catch(()=>({}));else {let A=new URL(t.url).searchParams.get("input");if(A)try{y=JSON.parse(decodeURIComponent(A));}catch{}}let h=y?.["0"]??y,f=await m({...h,collection:o});return new Response(JSON.stringify({result:{data:f}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(y){let h=y.message||"Internal error",f=h.includes("not found")?404:h.includes("denied")||h.includes("authentication required")?403:h.includes("conflict")?409:500,A=f===404?-32601:f===403?-32001:f===409?-32002:-32603;return new Response(JSON.stringify({error:{message:h,code:A,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:f}}}),{status:f,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e$1){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let n=async a=>{let i=await e(a,this.db);if(!i.valid)throw new Error(i.error||"Invalid API key");if(!i.user)throw new Error("API key has no associated user");return i.user};return this.wsServer=d$1({pubsub:this.pubsub,port:e$1?.port||8080,requireAuth:e$1?.requireAuth??t?.requireAuth,verifyToken:e$1?.verifyToken||n}),this.wsServer}async shutdown(){this.wsServer&&await this.wsServer.close(),await this.db.disconnect();}};function Wt(s){return new W(s)}var rt=createRequire(import.meta.url),lt="node:sqlite",{DatabaseSync:ct}=rt(lt);function x(s){let e=[];for(let t of s)if(t.type==="tabs"&&"tabs"in t)for(let n of t.tabs)e.push(...x(n.fields));else t.type==="row"&&"fields"in t?e.push(...x(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...x(t.fields)):e.push(t);return e}function ut(s,e){let t=e,n=s[t.name];if(t.type==="json"||t.type==="richtext"||t.type==="array"||t.type==="group"||t.type==="blocks"||t.type==="list"||t.type==="relationship-block")try{n=n?JSON.parse(n):null;}catch{n=null;}if(t.type==="checkbox"&&(n=!!n),t.type==="date"&&n)try{let a=new Date(n);isNaN(a.getTime())?n=null:n=a.toISOString();}catch{n=null;}if((t.type==="upload"||t.type==="image")&&n)try{let a=JSON.parse(n);Array.isArray(a)?n=a.map(i=>typeof i=="object"&&i!==null?i:{id:i}):n=typeof a=="object"?a:{id:a};}catch{n={id:n};}if(t.type==="relationship"&&n)try{let a=JSON.parse(n);Array.isArray(a),n=a;}catch{n={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:n};}if(t.type==="list"&&n)try{let a=JSON.parse(n);n=Array.isArray(a)?a:[];}catch{n=[];}if(t.type==="relationship-block"&&n)try{let a=JSON.parse(n);n=Array.isArray(a)?a:[];}catch{n=[];}return n}function X(s,e){try{return s.prepare(`PRAGMA table_info(${e})`).all().map(n=>n.name)}catch{return []}}var J=class extends a$3{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(this.db||(this.db=new ct(this.path||":memory:")),this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),t=n=>{let a=e(n),i=o=>typeof o=="boolean"?o?1:0:o===void 0?null:o;return new Proxy(a,{get(o,r,c){if(r==="all")return (...u)=>o.all(...u.map(i));if(r==="get")return (...u)=>o.get(...u.map(i));if(r==="run")return (...u)=>o.run(...u.map(i));let d=Reflect.get(o,r,c);return typeof d=="function"?d.bind(o):d}})};t.__wrapped=true,this.db.prepare=t;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){this.db&&this.db.close(),this.connected=false;}ensureTable(e,t){let n=t||this.getTableNameFor(e.slug),a=["id TEXT PRIMARY KEY"];for(let r of x(e.fields)){if(!r.name||r.name==="id")continue;let c=this.fieldToSQL(r);c&&a.push(c);}let i=x(e.fields);i.some(r=>r.name==="createdAt")||a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),i.some(r=>r.name==="updatedAt")||a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),i.some(r=>r.name==="status")||a.push("status TEXT DEFAULT 'draft'"),i.some(r=>r.name==="hasDraft")||a.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let o=X(this.db,n);if(o.length===0){let r=`CREATE TABLE IF NOT EXISTS ${n} (${a.join(", ")})`;this.db.exec(r),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let c of x(e.fields))c.name&&c.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${c.name} ON ${n}(${this.col(c.name)})`),c.name&&c.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${c.name}_unique ON ${n}(${this.col(c.name)})`);}else {let r=new Set(o);for(let c of a){let d=c.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!r.has(d)&&d!=="id")try{d==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} TEXT DEFAULT 'published'`):d==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(d)} TEXT`);}catch{}}}this.migrations.set(n,true);}ensureVersionsTable(){this.db.exec(`
|
|
4
|
-
CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
|
|
5
|
-
id TEXT PRIMARY KEY,
|
|
6
|
-
collection_slug TEXT NOT NULL,
|
|
7
|
-
document_id TEXT NOT NULL,
|
|
8
|
-
tenant_id TEXT,
|
|
9
|
-
version INTEGER NOT NULL,
|
|
10
|
-
status TEXT NOT NULL DEFAULT 'draft',
|
|
11
|
-
autosave INTEGER NOT NULL DEFAULT 0,
|
|
12
|
-
data TEXT NOT NULL,
|
|
13
|
-
created_by TEXT,
|
|
14
|
-
change_description TEXT,
|
|
15
|
-
published_at TEXT,
|
|
16
|
-
created_at TEXT DEFAULT (datetime('now')),
|
|
17
|
-
updated_at TEXT DEFAULT (datetime('now'))
|
|
18
|
-
)
|
|
19
|
-
`);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}col(e){return `"${e}"`}fieldToSQL(e){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":case "code":case "markdown":case "url":return this.col(e.name)+" TEXT";case "number":return this.col(e.name)+" REAL";case "checkbox":return this.col(e.name)+" INTEGER DEFAULT 0";case "date":return this.col(e.name)+" TEXT";case "select":case "radio":return this.col(e.name)+" TEXT";case "relationship":case "upload":return this.col(e.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(e.name)+" TEXT";default:return null}}parseGlobalsSlug(e){if(e.startsWith("_globals_")){let t=e.replace("_globals_","");return {isGlobal:true,globalSlug:t,tableName:`global_${t.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:t,where:n={},sort:a,limit:i=10,page:o=1,tenantID:r,draft:c=false}=e,d=this.parseGlobalsSlug(t),u=d.isGlobal?this.globals.get(d.globalSlug):this.getCollection(t);this.ensureTable(u,d.tableName);let m=`SELECT * FROM ${d.tableName}`,y=[],h=[],f={...n};this.tenantContext&&u.tenantScoped&&(f=c$2({where:f},t,this.tenantContext,b$1).where||{});let A=u.fields.find(b=>b.name==="status"),g=A?.type==="select"&&A.options?.some(b=>b.value==="published");!c&&g&&(h.push("status = ?"),y.push("published")),r&&u.tenantScoped&&(h.push("tenant_id = ?"),y.push(r));for(let[b,S]of Object.entries(f))b==="AND"||b==="OR"||(typeof S=="object"&&S!==null?(S.equals!==void 0&&(h.push(`${this.col(b)} = ?`),y.push(S.equals)),S.in!==void 0&&(h.push(`${this.col(b)} IN (${S.in.map(()=>"?").join(", ")})`),y.push(...S.in)),S.not_equals!==void 0&&(h.push(`${this.col(b)} != ?`),y.push(S.not_equals))):(h.push(`${this.col(b)} = ?`),y.push(S)));h.length>0&&(m+=` WHERE ${h.join(" AND ")}`);let Ne=this.col(a?.replace("-","")||"createdAt"),Re=a?.startsWith("-")?"DESC":"ASC";m+=` ORDER BY ${Ne} ${Re}`;let ve=m.replace("SELECT *","SELECT COUNT(*) as count"),F=this.db.prepare(ve).get(...y)?.count||0;m+=" LIMIT ? OFFSET ?",y.push(i,(o-1)*i);let D=this.db.prepare(m).all(...y).map(b=>this.rowToDoc(b,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(D=D.filter(b=>d$2(b,t,this.tenantContext,b$1))),c&&(D=await Promise.all(D.map(async b=>{let S=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t,b.id);if(S){let De=S.data?JSON.parse(S.data):{};return {...b,...De,status:b.status}}return b}))),{docs:D,totalDocs:F,limit:i,totalPages:Math.ceil(F/i),page:o,pagingCounter:(o-1)*i+1,hasPrevPage:o>1,hasNextPage:o<Math.ceil(F/i),prevPage:o>1?o-1:null,nextPage:o<Math.ceil(F/i)?o+1:null}}async findByID(e){let{collection:t,id:n,tenantID:a,draft:i=false}=e,o=this.parseGlobalsSlug(t),r=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(r,o.tableName);let d=`SELECT * FROM ${o.tableName} WHERE id = ?`,u=[n];if(this.tenantContext&&r.tenantScoped){let f={id:n,tenant_id:this.tenantContext.tenantId};if(!d$2(f,t,this.tenantContext,b$1))return null}let p=r.fields.find(f=>f.name==="status"),m=p?.type==="select"&&p.options?.some(f=>f.value==="published");!i&&m&&(d+=" AND status = ?",u.push("published")),a&&r.tenantScoped&&(d+=" AND tenant_id = ?",u.push(a));let y=this.db.prepare(d).get(...u);if(!y)return null;let h=this.rowToDoc(y,r);if(i){let f=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t,h.id);if(f){let A=f.data?JSON.parse(f.data):{};h={...h,...A,status:h.status};}}return h}async create(e){let{collection:t,data:n,tenantID:a}=e,i=this.parseGlobalsSlug(t),o=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(t);this.ensureTable(o,i.tableName);let r=i.tableName,c=i.isGlobal?i.globalSlug:n.id||this.generateId(),d=this.prepareData(n,o);d.id=c,d.created_at=new Date().toISOString(),d.updated_at=new Date().toISOString(),a&&o.tenantScoped&&(d.tenant_id=a);let u=Object.keys(d),p=X(this.db,r),m={};for(let g of u)p.includes(g)&&(m[g]=d[g]);let y=Object.keys(m),h=y.map(g=>this.col(g)),f=y.map(()=>"?").join(", "),A=Object.values(m).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${r} (${h.join(", ")}) VALUES (${f})`).run(...A),this.ensureVersionsTable(),this.findByID({collection:t,id:c,tenantID:a,draft:true})}async update(e){let{collection:t,id:n,data:a,tenantID:i}=e,o=this.parseGlobalsSlug(t),r=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(r,o.tableName);let c=o.tableName,d=this.prepareData(a,r);d.updated_at=new Date().toISOString();let u=X(this.db,c),p={};for(let g of Object.keys(d))u.includes(g)&&(p[g]=d[g]);let y=Object.keys(p).map(g=>`${this.col(g)} = ?`).join(", "),h=Object.values(p).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g),f=`UPDATE ${c} SET ${y} WHERE id = ?`,A=[...h,n];return i&&r.tenantScoped&&(f+=" AND tenant_id = ?",A.push(i)),this.db.prepare(f).run(...A),this.ensureVersionsTable(),this.findByID({collection:t,id:n,tenantID:i,draft:true})}async delete(e){let{collection:t,id:n,tenantID:a}=e,i=this.parseGlobalsSlug(t),o=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(t);this.ensureTable(o,i.tableName),this.ensureVersionsTable();let r=await this.findByID({collection:t,id:n,tenantID:a,draft:true});if(!r)throw new Error(`Document not found: ${t}/${n}`);let d=`DELETE FROM ${i.tableName} WHERE id = ?`,u=[n];return a&&o.tenantScoped&&(d+=" AND tenant_id = ?",u.push(a)),this.db.prepare(d).run(...u),r}async count(e){let{collection:t,tenantID:n}=e,a=this.parseGlobalsSlug(t),i=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(t);this.ensureTable(i,a.tableName);let r=`SELECT COUNT(*) as count FROM ${a.tableName}`,c=[];return n&&i.tenantScoped&&(r+=" WHERE tenant_id = ?",c.push(n)),this.db.prepare(r).get(...c)?.count||0}async findOne(e){let t=this.parseGlobalsSlug(e.collection);if(t.isGlobal){let a=this.globals.get(t.globalSlug);if(!a)throw new Error(`Global "${t.globalSlug}" not found in adapter`);this.ensureTable(a,t.tableName);let i=`SELECT * FROM ${t.tableName}`,o=[],r=[],c=a.fields.find(p=>p.name==="status"),d=c?.type==="select"&&c.options?.some(p=>p.value==="published");!e.draft&&a.versions&&d&&o.push("status = 'published'"),o.length>0&&(i+=` WHERE ${o.join(" AND ")}`),i+=" LIMIT 1";let u=this.db.prepare(i).get(...r);if(u){let p=this.rowToDoc(u,a);if(e.draft){let m=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(e.collection,t.globalSlug);if(m){let y=m.data?JSON.parse(m.data):{};p={...p,...y,status:p.status};}}return p}return null}return (await this.find({...e,limit:1})).docs[0]||null}async findVersions(e){this.ensureVersionsTable();let{collection:t,documentId:n,tenantID:a,limit:i=20,page:o=1}=e,r=["collection_slug = ?","document_id = ?","autosave = 0"],c=[t,n];a?(r.push("tenant_id = ?"),c.push(a)):r.push("tenant_id IS NULL");let d=`WHERE ${r.join(" AND ")}`,p=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${d}`).get(...c)?.count||0,m=(o-1)*i;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${d} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...c,i,m).map(f=>this.rowToVersion(f)),totalDocs:p,limit:i,totalPages:Math.ceil(p/i),page:o,pagingCounter:(o-1)*i+1,hasPrevPage:o>1,hasNextPage:o<Math.ceil(p/i),prevPage:o>1?o-1:null,nextPage:o<Math.ceil(p/i)?o+1:null}}async findVersionByID(e){this.ensureVersionsTable();let t=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return t?this.rowToVersion(t):null}async createVersion(e){this.ensureVersionsTable();let t=new Date().toISOString();if(e.autosave){let r=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,c=[e.collection,e.documentId];e.tenantID?(r+=" AND tenant_id = ?",c.push(e.tenantID)):r+=" AND tenant_id IS NULL",r+=" LIMIT 1";let d=this.db.prepare(r).get(...c);if(d){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,t,d.id);let u=await this.findVersionByID({collection:e.collection,versionId:d.id});if(u)return u}}let n=this.generateId(),i=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(e.collection,e.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
|
|
20
|
-
id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
|
|
21
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,e.collection,e.documentId,e.tenantID??null,i,e.status,e.autosave?1:0,JSON.stringify(e.data),e.createdBy??null,e.changeDescription??null,e.status==="published"?t:null,t,t),!e.autosave){let c=this.collections.get(e.collection)?.versions?.maxPerDoc;c&&c>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:c,tenantID:e.tenantID});}return await this.findVersionByID({collection:e.collection,versionId:n})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:t,documentId:n,keepLatest:a,tenantID:i}=e;if(a&&a>0){let o=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(t,n),r=0,c=[];for(let d of o)d.status==="published"||d.autosave===1||(r++,r>a&&c.push(d.id));for(let d of c)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(d);}else {let o=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,r=[t,n];i&&(o+=" AND tenant_id = ?",r.push(i)),this.db.prepare(o).run(...r);}}rowToVersion(e){return {id:String(e.id),collection:e.collection_slug,documentId:e.document_id,version:e.version,status:e.status,data:e.data?JSON.parse(e.data):{},createdBy:e.created_by??void 0,changeDescription:e.change_description??void 0,publishedAt:e.published_at??null,createdAt:e.created_at,updatedAt:e.updated_at}}prepareData(e,t){let n={},a=x(t.fields),i=(o,r)=>{let c=o;if(c.type==="json"||c.type==="richtext"||c.type==="array"||c.type==="group"||c.type==="blocks"||c.type==="list"||c.type==="relationship-block")return r!=null?JSON.stringify(r):null;if(c.type==="checkbox")return r?1:0;if(c.type==="number")return r!==null&&r!==""?Number(r):null;if(c.type==="upload"||c.type==="image"){if(r==null)return null;if(Array.isArray(r)){let d=r.map(u=>typeof u=="string"?u:typeof u=="object"?u.id||u._id||u:String(u));return JSON.stringify(d)}return typeof r=="string"?r:typeof r=="object"?JSON.stringify(r):String(r)}else if(o.type==="relationship"){if(r==null)return null;if(Array.isArray(r)){let d=r.map(u=>typeof u=="string"?u:typeof u=="object"?JSON.stringify({relationTo:o.relationTo,value:u.id||u}):String(u));return JSON.stringify(d)}return typeof r=="string"?r:typeof r=="object"?JSON.stringify({relationTo:o.relationTo,value:r.id||r}):String(r)}return r};for(let o of a){if(!o.name||o.name==="id"||t.fields.some(d=>d.type==="tabs"&&"tabs"in d&&d.tabs.some(u=>u.fields.some(p=>p.name===o.name))))continue;let c=e[o.name];c!==void 0&&(n[o.name]=i(o,c));}for(let o of t.fields)if(o.type==="tabs"&&"tabs"in o&&o.name){let r=e[o.name];if(r&&typeof r=="object"){for(let c of o.tabs)for(let d of c.fields)if(d.name&&d.name!=="id"){let u=r[d.name];u!==void 0&&(n[d.name]=i(d,u));}}}return n}rowToDoc(e,t){let n={id:e.id};for(let a of x(t.fields)){if(!a.name||a.name==="id")continue;let i=a,o=e[i.name];if(i.type==="json"||i.type==="richtext"||i.type==="array"||i.type==="group"||i.type==="blocks"||i.type==="list"||i.type==="relationship-block")try{o=o?JSON.parse(o):null;}catch{o=null;}if(a.type==="checkbox"&&(o=!!o),a.type==="date"&&o)try{let r=new Date(o);isNaN(r.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${a.name}":`,o),o=null):o=r.toISOString();}catch{o=null;}if((a.type==="upload"||a.type==="image")&&o)try{let r=JSON.parse(o);Array.isArray(r)?o=r.map(c=>typeof c=="object"&&c!==null?c:{id:c}):o=typeof r=="object"?r:{id:r};}catch{o={id:o};}if(a.type==="relationship"&&o)try{let r=JSON.parse(o);Array.isArray(r),o=r;}catch{o={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:o};}n[a.name]=o;}for(let a of t.fields)if(!(!a.name||a.name==="id"||a.name==="row"||a.name==="collapsible")&&a.type==="tabs"&&"tabs"in a){let i={};for(let o of a.tabs)for(let r of o.fields)r.name&&r.name!=="id"&&(i[r.name]=ut(e,r));n[a.name]=i;}if(t.timestamps){let a=e.createdAt||e.created_at,i=e.updatedAt||e.updated_at;if(a)try{let o=new Date(a);isNaN(o.getTime())||(n.createdAt=o.toISOString());}catch{}if(i)try{let o=new Date(i);isNaN(o.getTime())||(n.updatedAt=o.toISOString());}catch{}}return t.tenantScoped&&(n.tenantID=e.tenant_id),n.status=e.status??"published",n.hasDraft=e.hasDraft?!!e.hasDraft:false,n}generateId(){let e=Date.now().toString(16).padStart(12,"0"),t=randomBytes(6).toString("hex");return e+t}getMediaById(e){try{let t=this.getTableNameFor("media"),n=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${t} WHERE id = ?`).get(e);if(n)return {id:n.id,url:n.url,thumbnailUrl:n.thumbnail_url||n.url}}catch{}return null}getTableNameFor(e){return e.replace(/-/g,"_")}async migrate(){for(let e of this.collections.values())this.ensureTable(e);}async rollback(){}async transaction(e){return new Promise((t,n)=>{let a=this.db.transaction(async()=>e({db:this.db}));try{let i=a();t(i);}catch(i){n(i);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function cs(s){return new J(s||{})}export{K as a,V as b,B as c,N as d,pe as e,C as f,he as g,ge as h,me as i,be as j,Te as k,w as l,He as m,Ye as n,M as o,W as p,Wt as q,J as r,cs as s};
|