diff --git a/packages/core/dist/app-CYEm1ytG.d.cts b/packages/core/dist/app-CYEm1ytG.d.cts deleted file mode 100644 index 165643841..000000000 --- a/packages/core/dist/app-CYEm1ytG.d.cts +++ /dev/null @@ -1,101 +0,0 @@ -import { Hono, Context } from 'hono'; -import { D1Database, KVNamespace, R2Bucket } from '@cloudflare/workers-types'; - -/** - * Main Application Factory - * - * Creates a configured SonicJS application with all core functionality - */ - -interface Bindings { - DB: D1Database; - CACHE_KV: KVNamespace; - MEDIA_BUCKET: R2Bucket; - ASSETS: Fetcher; - EMAIL_QUEUE?: Queue; - SENDGRID_API_KEY?: string; - DEFAULT_FROM_EMAIL?: string; - IMAGES_ACCOUNT_ID?: string; - IMAGES_API_TOKEN?: string; - ENVIRONMENT?: string; - BUCKET_NAME?: string; - GOOGLE_MAPS_API_KEY?: string; -} -interface Variables { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; - requestId?: string; - startTime?: number; - appVersion?: string; -} -interface SonicJSConfig { - collections?: { - directory?: string; - autoSync?: boolean; - }; - plugins?: { - directory?: string; - autoLoad?: boolean; - disableAll?: boolean; - }; - routes?: Array<{ - path: string; - handler: Hono; - }>; - middleware?: { - beforeAuth?: Array<(c: Context, next: () => Promise) => Promise>; - afterAuth?: Array<(c: Context, next: () => Promise) => Promise>; - }; - version?: string; - name?: string; -} -type SonicJSApp = Hono<{ - Bindings: Bindings; - Variables: Variables; -}>; -/** - * Create a SonicJS application with core functionality - * - * @param config - Application configuration - * @returns Configured Hono application - * - * @example - * ```typescript - * import { createSonicJSApp } from '@sonicjs-cms/core' - * - * const app = createSonicJSApp({ - * collections: { - * directory: './src/collections', - * autoSync: true - * }, - * plugins: { - * directory: './src/plugins', - * autoLoad: true - * } - * }) - * - * export default app - * ``` - */ -declare function createSonicJSApp(config?: SonicJSConfig): SonicJSApp; -/** - * Setup core middleware (backward compatibility) - * - * @param _app - Hono application - * @deprecated Use createSonicJSApp() instead - */ -declare function setupCoreMiddleware(_app: SonicJSApp): void; -/** - * Setup core routes (backward compatibility) - * - * @param _app - Hono application - * @deprecated Use createSonicJSApp() instead - */ -declare function setupCoreRoutes(_app: SonicJSApp): void; - -export { type Bindings as B, type SonicJSConfig as S, type Variables as V, setupCoreRoutes as a, type SonicJSApp as b, createSonicJSApp as c, setupCoreMiddleware as s }; diff --git a/packages/core/dist/app-CYEm1ytG.d.ts b/packages/core/dist/app-CYEm1ytG.d.ts deleted file mode 100644 index 165643841..000000000 --- a/packages/core/dist/app-CYEm1ytG.d.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { Hono, Context } from 'hono'; -import { D1Database, KVNamespace, R2Bucket } from '@cloudflare/workers-types'; - -/** - * Main Application Factory - * - * Creates a configured SonicJS application with all core functionality - */ - -interface Bindings { - DB: D1Database; - CACHE_KV: KVNamespace; - MEDIA_BUCKET: R2Bucket; - ASSETS: Fetcher; - EMAIL_QUEUE?: Queue; - SENDGRID_API_KEY?: string; - DEFAULT_FROM_EMAIL?: string; - IMAGES_ACCOUNT_ID?: string; - IMAGES_API_TOKEN?: string; - ENVIRONMENT?: string; - BUCKET_NAME?: string; - GOOGLE_MAPS_API_KEY?: string; -} -interface Variables { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; - requestId?: string; - startTime?: number; - appVersion?: string; -} -interface SonicJSConfig { - collections?: { - directory?: string; - autoSync?: boolean; - }; - plugins?: { - directory?: string; - autoLoad?: boolean; - disableAll?: boolean; - }; - routes?: Array<{ - path: string; - handler: Hono; - }>; - middleware?: { - beforeAuth?: Array<(c: Context, next: () => Promise) => Promise>; - afterAuth?: Array<(c: Context, next: () => Promise) => Promise>; - }; - version?: string; - name?: string; -} -type SonicJSApp = Hono<{ - Bindings: Bindings; - Variables: Variables; -}>; -/** - * Create a SonicJS application with core functionality - * - * @param config - Application configuration - * @returns Configured Hono application - * - * @example - * ```typescript - * import { createSonicJSApp } from '@sonicjs-cms/core' - * - * const app = createSonicJSApp({ - * collections: { - * directory: './src/collections', - * autoSync: true - * }, - * plugins: { - * directory: './src/plugins', - * autoLoad: true - * } - * }) - * - * export default app - * ``` - */ -declare function createSonicJSApp(config?: SonicJSConfig): SonicJSApp; -/** - * Setup core middleware (backward compatibility) - * - * @param _app - Hono application - * @deprecated Use createSonicJSApp() instead - */ -declare function setupCoreMiddleware(_app: SonicJSApp): void; -/** - * Setup core routes (backward compatibility) - * - * @param _app - Hono application - * @deprecated Use createSonicJSApp() instead - */ -declare function setupCoreRoutes(_app: SonicJSApp): void; - -export { type Bindings as B, type SonicJSConfig as S, type Variables as V, setupCoreRoutes as a, type SonicJSApp as b, createSonicJSApp as c, setupCoreMiddleware as s }; diff --git a/packages/core/dist/chunk-5HMR2SJW.cjs b/packages/core/dist/chunk-5HMR2SJW.cjs deleted file mode 100644 index b8ead1ed7..000000000 --- a/packages/core/dist/chunk-5HMR2SJW.cjs +++ /dev/null @@ -1,621 +0,0 @@ -'use strict'; - -// src/utils/sanitize.ts -function escapeHtml(text) { - if (typeof text !== "string") { - return ""; - } - const map = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'" - }; - return text.replace(/[&<>"']/g, (char) => map[char] || char); -} -function sanitizeInput(input) { - if (!input) { - return ""; - } - return escapeHtml(String(input).trim()); -} -function sanitizeObject(obj, fields) { - const sanitized = { ...obj }; - for (const field of fields) { - if (typeof obj[field] === "string") { - sanitized[field] = sanitizeInput(obj[field]); - } - } - return sanitized; -} - -// src/utils/slug-utils.ts -function generateSlug(text) { - if (!text) return ""; - return text.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-z0-9\s_-]/g, "").replace(/\s+/g, "-").replace(/[-_]+/g, "-").replace(/^[-_]+|[-_]+$/g, "").substring(0, 100); -} - -// src/utils/template-renderer.ts -var TemplateRenderer = class { - templateCache = /* @__PURE__ */ new Map(); - constructor() { - } - /** - * Simple Handlebars-like template engine - */ - renderTemplate(template, data) { - let rendered = template; - rendered = rendered.replace(/\{\{#each\s+([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g, (_match, arrayName, content) => { - const array = this.getNestedValue(data, arrayName.trim()); - if (!Array.isArray(array)) return ""; - return array.map((item, index) => { - const itemContext = { - ...data, - // Handle primitive items (for {{.}} syntax) - ".": item, - // Spread item properties if it's an object - ...typeof item === "object" && item !== null ? item : {}, - "@index": index, - "@first": index === 0, - "@last": index === array.length - 1 - }; - return this.renderTemplate(content, itemContext); - }).join(""); - }); - let ifCount = 0; - while (rendered.includes("{{#if ") && ifCount < 100) { - const previousRendered = rendered; - rendered = rendered.replace(/\{\{#if\s+([^}]+)\}\}([\s\S]*?)\{\{\/if\}\}/g, (_match, condition, content) => { - const value = this.getNestedValue(data, condition.trim()); - const isTruthy = value === true || value && value !== 0 && value !== "" && value !== null && value !== void 0; - return isTruthy ? this.renderTemplate(content, data) : ""; - }); - if (previousRendered === rendered) break; - ifCount++; - } - rendered = rendered.replace(/\{\{\{([^}]+)\}\}\}/g, (_match, variable) => { - const value = this.getNestedValue(data, variable.trim()); - return value !== void 0 && value !== null ? String(value) : ""; - }); - rendered = rendered.replace(/\{\{([^}#\/]+)\s+([^}]+)\}\}/g, (match, helper, variable) => { - const helperName = helper.trim(); - const varName = variable.trim(); - if (helperName === "titleCase") { - const value = this.getNestedValue(data, varName); - if (value !== void 0 && value !== null) { - return this.titleCase(String(value)); - } - } - return match; - }); - rendered = rendered.replace(/\{\{([^}#\/]+)\}\}/g, (match, variable) => { - const trimmed = variable.trim(); - if (trimmed.includes(" ")) { - return match; - } - const value = this.getNestedValue(data, trimmed); - if (value === null) return ""; - if (value === void 0) return ""; - return String(value); - }); - return rendered; - } - /** - * Get nested value from object using dot notation - */ - getNestedValue(obj, path) { - if (!obj || path === "") return void 0; - return path.split(".").reduce((current, key) => { - if (current === null || current === void 0) return void 0; - return current[key]; - }, obj); - } - /** - * Title case helper function - */ - titleCase(str) { - return str.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase()); - } - /** - * Render a template string with data - */ - render(template, data = {}) { - return this.renderTemplate(template, data); - } - /** - * Clear template cache (useful for development) - */ - clearCache() { - this.templateCache.clear(); - } -}; -var templateRenderer = new TemplateRenderer(); -function renderTemplate(template, data = {}) { - return templateRenderer.render(template, data); -} - -// src/utils/query-filter.ts -var QueryFilterBuilder = class { - params = []; - errors = []; - /** - * Build a complete SQL query from filter object - */ - build(baseTable, filter) { - this.params = []; - this.errors = []; - let sql = `SELECT * FROM ${baseTable}`; - if (filter.where) { - const whereClause = this.buildWhereClause(filter.where); - if (whereClause) { - sql += ` WHERE ${whereClause}`; - } - } - if (filter.sort && filter.sort.length > 0) { - const orderClauses = filter.sort.map((s) => `${this.sanitizeFieldName(s.field)} ${s.order.toUpperCase()}`).join(", "); - sql += ` ORDER BY ${orderClauses}`; - } - if (filter.limit) { - sql += ` LIMIT ?`; - this.params.push(filter.limit); - } - if (filter.offset) { - sql += ` OFFSET ?`; - this.params.push(filter.offset); - } - return { - sql, - params: this.params, - errors: this.errors - }; - } - /** - * Build WHERE clause from filter group - */ - buildWhereClause(group) { - const clauses = []; - if (group.and && group.and.length > 0) { - const andClauses = group.and.map((condition) => this.buildCondition(condition)).filter((clause) => clause !== null); - if (andClauses.length > 0) { - clauses.push(`(${andClauses.join(" AND ")})`); - } - } - if (group.or && group.or.length > 0) { - const orClauses = group.or.map((condition) => this.buildCondition(condition)).filter((clause) => clause !== null); - if (orClauses.length > 0) { - clauses.push(`(${orClauses.join(" OR ")})`); - } - } - return clauses.join(" AND "); - } - /** - * Build a single condition - */ - buildCondition(condition) { - const field = this.sanitizeFieldName(condition.field); - switch (condition.operator) { - case "equals": - return this.buildEquals(field, condition.value); - case "not_equals": - return this.buildNotEquals(field, condition.value); - case "greater_than": - return this.buildComparison(field, ">", condition.value); - case "greater_than_equal": - return this.buildComparison(field, ">=", condition.value); - case "less_than": - return this.buildComparison(field, "<", condition.value); - case "less_than_equal": - return this.buildComparison(field, "<=", condition.value); - case "like": - return this.buildLike(field, condition.value); - case "contains": - return this.buildContains(field, condition.value); - case "in": - return this.buildIn(field, condition.value); - case "not_in": - return this.buildNotIn(field, condition.value); - case "all": - return this.buildAll(field, condition.value); - case "exists": - return this.buildExists(field, condition.value); - case "near": - this.errors.push(`'near' operator not supported in SQLite. Use spatial extension or application-level filtering.`); - return null; - case "within": - this.errors.push(`'within' operator not supported in SQLite. Use spatial extension or application-level filtering.`); - return null; - case "intersects": - this.errors.push(`'intersects' operator not supported in SQLite. Use spatial extension or application-level filtering.`); - return null; - default: - this.errors.push(`Unknown operator: ${condition.operator}`); - return null; - } - } - /** - * Build equals condition - */ - buildEquals(field, value) { - if (value === null) { - return `${field} IS NULL`; - } - this.params.push(value); - return `${field} = ?`; - } - /** - * Build not equals condition - */ - buildNotEquals(field, value) { - if (value === null) { - return `${field} IS NOT NULL`; - } - this.params.push(value); - return `${field} != ?`; - } - /** - * Build comparison condition (>, >=, <, <=) - */ - buildComparison(field, operator, value) { - this.params.push(value); - return `${field} ${operator} ?`; - } - /** - * Build LIKE condition (case-insensitive, all words must be present) - */ - buildLike(field, value) { - const words = value.split(/\s+/).filter((w) => w.length > 0); - if (words.length === 0) { - return `1=1`; - } - const conditions = words.map((word) => { - this.params.push(`%${word}%`); - return `${field} LIKE ?`; - }); - return `(${conditions.join(" AND ")})`; - } - /** - * Build CONTAINS condition (case-insensitive substring) - */ - buildContains(field, value) { - this.params.push(`%${value}%`); - return `${field} LIKE ?`; - } - /** - * Build IN condition - */ - buildIn(field, value) { - let values; - if (typeof value === "string") { - values = value.split(",").map((v) => v.trim()).filter((v) => v.length > 0); - } else if (Array.isArray(value)) { - values = value; - } else { - values = [value]; - } - if (values.length === 0) { - return `1=0`; - } - const placeholders = values.map((v) => { - this.params.push(v); - return "?"; - }).join(", "); - return `${field} IN (${placeholders})`; - } - /** - * Build NOT IN condition - */ - buildNotIn(field, value) { - let values; - if (typeof value === "string") { - values = value.split(",").map((v) => v.trim()).filter((v) => v.length > 0); - } else if (Array.isArray(value)) { - values = value; - } else { - values = [value]; - } - if (values.length === 0) { - return `1=1`; - } - const placeholders = values.map((v) => { - this.params.push(v); - return "?"; - }).join(", "); - return `${field} NOT IN (${placeholders})`; - } - /** - * Build ALL condition (value must contain all items in list) - * For SQLite, we'll check if a JSON array contains all values - */ - buildAll(field, value) { - let values; - if (typeof value === "string") { - values = value.split(",").map((v) => v.trim()).filter((v) => v.length > 0); - } else if (Array.isArray(value)) { - values = value; - } else { - values = [value]; - } - if (values.length === 0) { - return `1=1`; - } - const conditions = values.map((val) => { - this.params.push(`%${val}%`); - return `${field} LIKE ?`; - }); - return `(${conditions.join(" AND ")})`; - } - /** - * Build EXISTS condition - */ - buildExists(field, value) { - if (value) { - return `${field} IS NOT NULL AND ${field} != ''`; - } else { - return `(${field} IS NULL OR ${field} = '')`; - } - } - /** - * Sanitize field names to prevent SQL injection - */ - sanitizeFieldName(field) { - const sanitized = field.replace(/[^a-zA-Z0-9_$.]/g, ""); - if (sanitized.includes(".")) { - const [table, ...path] = sanitized.split("."); - return `json_extract(${table}, '$.${path.join(".")}')`; - } - return sanitized; - } - /** - * Parse filter from query string - */ - static parseFromQuery(query) { - const filter = {}; - if (query.where) { - try { - filter.where = typeof query.where === "string" ? JSON.parse(query.where) : query.where; - } catch (e) { - console.error("Failed to parse where clause:", e); - } - } - if (!filter.where) { - filter.where = { and: [] }; - } - if (!filter.where.and) { - filter.where.and = []; - } - const simpleFieldMappings = { - "status": "status", - "collection_id": "collection_id" - }; - for (const [queryParam, dbField] of Object.entries(simpleFieldMappings)) { - if (query[queryParam]) { - filter.where.and.push({ - field: dbField, - operator: "equals", - value: query[queryParam] - }); - } - } - if (query.limit) { - filter.limit = Math.min(parseInt(query.limit), 1e3); - } - if (query.offset) { - filter.offset = parseInt(query.offset); - } - if (query.sort) { - try { - filter.sort = typeof query.sort === "string" ? JSON.parse(query.sort) : query.sort; - } catch (e) { - console.error("Failed to parse sort clause:", e); - } - } - return filter; - } -}; -function buildQuery(table, filter) { - const builder = new QueryFilterBuilder(); - return builder.build(table, filter); -} - -// package.json -var package_default = { - name: "@sonicjs-cms/core", - version: "2.8.0", - description: "Core framework for SonicJS headless CMS - Edge-first, TypeScript-native CMS built for Cloudflare Workers", - type: "module", - main: "./dist/index.cjs", - module: "./dist/index.js", - types: "./dist/index.d.ts", - bin: { - "sonicjs-db-reset": "./bin/db-reset.js" - }, - exports: { - ".": { - types: "./dist/index.d.ts", - import: "./dist/index.js", - require: "./dist/index.cjs" - }, - "./services": { - types: "./dist/services.d.ts", - import: "./dist/services.js", - require: "./dist/services.cjs" - }, - "./middleware": { - types: "./dist/middleware.d.ts", - import: "./dist/middleware.js", - require: "./dist/middleware.cjs" - }, - "./routes": { - types: "./dist/routes.d.ts", - import: "./dist/routes.js", - require: "./dist/routes.cjs" - }, - "./templates": { - types: "./dist/templates.d.ts", - import: "./dist/templates.js", - require: "./dist/templates.cjs" - }, - "./plugins": { - types: "./dist/plugins.d.ts", - import: "./dist/plugins.js", - require: "./dist/plugins.cjs" - }, - "./utils": { - types: "./dist/utils.d.ts", - import: "./dist/utils.js", - require: "./dist/utils.cjs" - }, - "./types": { - types: "./dist/types.d.ts", - import: "./dist/types.js", - require: "./dist/types.cjs" - }, - "./package.json": "./package.json" - }, - files: [ - "bin", - "dist", - "migrations", - "README.md", - "LICENSE" - ], - scripts: { - "generate:migrations": "npx tsx scripts/generate-migrations.ts", - prebuild: "npm run generate:migrations", - build: "tsup", - dev: "tsup --watch", - "type-check": "tsc --noEmit", - lint: "eslint src/", - "lint:fix": "eslint src/ --fix", - test: "vitest --run", - "test:cov": "vitest --run --coverage", - "test:watch": "vitest", - prepublishOnly: "npm run build" - }, - keywords: [ - "cms", - "headless-cms", - "cloudflare", - "workers", - "edge", - "typescript", - "hono", - "content-management", - "api", - "sonicjs" - ], - author: "SonicJS Team", - license: "MIT", - repository: { - type: "git", - url: "git+https://github.com/sonicjs/sonicjs.git", - directory: "packages/core" - }, - bugs: { - url: "https://github.com/sonicjs/sonicjs/issues" - }, - homepage: "https://sonicjs.com", - peerDependencies: { - "@cloudflare/workers-types": "^4.0.0", - "drizzle-orm": "^0.44.0", - hono: "^4.0.0", - zod: "^3.0.0 || ^4.0.0" - }, - dependencies: { - "drizzle-zod": "^0.8.3", - "highlight.js": "^11.11.1", - marked: "^16.4.1", - semver: "^7.7.3" - }, - devDependencies: { - "@vitest/coverage-v8": "^4.0.5", - "@cloudflare/workers-types": "^4.20251014.0", - "@types/node": "^24.9.2", - "@typescript-eslint/eslint-plugin": "^8.50.0", - "@typescript-eslint/parser": "^8.50.0", - "drizzle-orm": "^0.44.7", - eslint: "^9.39.2", - glob: "^10.5.0", - hono: "^4.11.7", - tsup: "^8.5.0", - typescript: "^5.9.3", - vitest: "^4.0.5", - zod: "^4.1.12" - }, - engines: { - node: ">=18.0.0" - }, - publishConfig: { - access: "public", - registry: "https://registry.npmjs.org/" - } -}; - -// src/utils/version.ts -var SONICJS_VERSION = package_default.version; -function getCoreVersion() { - return SONICJS_VERSION; -} - -// src/utils/blocks.ts -function getBlocksFieldConfig(fieldOptions) { - if (!fieldOptions || typeof fieldOptions !== "object") return null; - const itemsConfig = fieldOptions.items && typeof fieldOptions.items === "object" ? fieldOptions.items : null; - if (!itemsConfig || !itemsConfig.blocks || typeof itemsConfig.blocks !== "object") { - return null; - } - const discriminator = typeof itemsConfig.discriminator === "string" && itemsConfig.discriminator ? itemsConfig.discriminator : "blockType"; - return { - blocks: itemsConfig.blocks, - discriminator - }; -} -function parseBlocksValue(value, config) { - const errors = []; - let rawValue = value; - if (rawValue === null || rawValue === void 0 || rawValue === "") { - return { value: [], errors }; - } - if (typeof rawValue === "string") { - try { - rawValue = JSON.parse(rawValue); - } catch { - return { value: [], errors: ["Blocks value must be valid JSON"] }; - } - } - if (!Array.isArray(rawValue)) { - return { value: [], errors: ["Blocks value must be an array"] }; - } - const normalized = rawValue.map((item, index) => { - if (!item || typeof item !== "object") { - errors.push(`Block #${index + 1} must be an object`); - return null; - } - if (item.blockType && item.data && typeof item.data === "object") { - return { [config.discriminator]: item.blockType, ...item.data }; - } - if (!(config.discriminator in item)) { - errors.push(`Block #${index + 1} is missing "${config.discriminator}"`); - } - return item; - }).filter((item) => item !== null); - return { value: normalized, errors }; -} - -exports.QueryFilterBuilder = QueryFilterBuilder; -exports.SONICJS_VERSION = SONICJS_VERSION; -exports.TemplateRenderer = TemplateRenderer; -exports.buildQuery = buildQuery; -exports.escapeHtml = escapeHtml; -exports.generateSlug = generateSlug; -exports.getBlocksFieldConfig = getBlocksFieldConfig; -exports.getCoreVersion = getCoreVersion; -exports.package_default = package_default; -exports.parseBlocksValue = parseBlocksValue; -exports.renderTemplate = renderTemplate; -exports.sanitizeInput = sanitizeInput; -exports.sanitizeObject = sanitizeObject; -exports.templateRenderer = templateRenderer; -//# sourceMappingURL=chunk-5HMR2SJW.cjs.map -//# sourceMappingURL=chunk-5HMR2SJW.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-6FHNRRJ3.cjs b/packages/core/dist/chunk-6FHNRRJ3.cjs deleted file mode 100644 index 31289c44a..000000000 --- a/packages/core/dist/chunk-6FHNRRJ3.cjs +++ /dev/null @@ -1,594 +0,0 @@ -'use strict'; - -var hono = require('hono'); -var zod = require('zod'); - -// src/plugins/sdk/plugin-builder.ts -var PluginBuilder = class _PluginBuilder { - plugin; - constructor(options) { - this.plugin = { - name: options.name, - version: options.version, - description: options.description, - author: options.author, - dependencies: options.dependencies, - routes: [], - middleware: [], - models: [], - services: [], - adminPages: [], - adminComponents: [], - menuItems: [], - hooks: [] - }; - } - /** - * Create a new plugin builder - */ - static create(options) { - return new _PluginBuilder(options); - } - /** - * Add metadata to the plugin - */ - metadata(metadata) { - Object.assign(this.plugin, metadata); - return this; - } - /** - * Add routes to plugin - */ - addRoutes(routes) { - this.plugin.routes = [...this.plugin.routes || [], ...routes]; - return this; - } - /** - * Add a single route to plugin - */ - addRoute(path, handler, options) { - const route = { - path, - handler, - ...options - }; - this.plugin.routes = [...this.plugin.routes || [], route]; - return this; - } - /** - * Add middleware to plugin - */ - addMiddleware(middleware) { - this.plugin.middleware = [...this.plugin.middleware || [], ...middleware]; - return this; - } - /** - * Add a single middleware to plugin - */ - addSingleMiddleware(name, handler, options) { - const middleware = { - name, - handler, - ...options - }; - this.plugin.middleware = [...this.plugin.middleware || [], middleware]; - return this; - } - /** - * Add models to plugin - */ - addModels(models) { - this.plugin.models = [...this.plugin.models || [], ...models]; - return this; - } - /** - * Add a single model to plugin - */ - addModel(name, options) { - const model = { - name, - ...options - }; - this.plugin.models = [...this.plugin.models || [], model]; - return this; - } - /** - * Add services to plugin - */ - addServices(services) { - this.plugin.services = [...this.plugin.services || [], ...services]; - return this; - } - /** - * Add a single service to plugin - */ - addService(name, implementation, options) { - const service = { - name, - implementation, - ...options - }; - this.plugin.services = [...this.plugin.services || [], service]; - return this; - } - /** - * Add admin pages to plugin - */ - addAdminPages(pages) { - this.plugin.adminPages = [...this.plugin.adminPages || [], ...pages]; - return this; - } - /** - * Add a single admin page to plugin - */ - addAdminPage(path, title, component, options) { - const page = { - path, - title, - component, - ...options - }; - this.plugin.adminPages = [...this.plugin.adminPages || [], page]; - return this; - } - /** - * Add admin components to plugin - */ - addComponents(components) { - this.plugin.adminComponents = [...this.plugin.adminComponents || [], ...components]; - return this; - } - /** - * Add a single admin component to plugin - */ - addComponent(name, template, options) { - const component = { - name, - template, - ...options - }; - this.plugin.adminComponents = [...this.plugin.adminComponents || [], component]; - return this; - } - /** - * Add menu items to plugin - */ - addMenuItems(items) { - this.plugin.menuItems = [...this.plugin.menuItems || [], ...items]; - return this; - } - /** - * Add a single menu item to plugin - */ - addMenuItem(label, path, options) { - const menuItem = { - label, - path, - ...options - }; - this.plugin.menuItems = [...this.plugin.menuItems || [], menuItem]; - return this; - } - /** - * Add hooks to plugin - */ - addHooks(hooks) { - this.plugin.hooks = [...this.plugin.hooks || [], ...hooks]; - return this; - } - /** - * Add a single hook to plugin - */ - addHook(name, handler, options) { - const hook = { - name, - handler, - ...options - }; - this.plugin.hooks = [...this.plugin.hooks || [], hook]; - return this; - } - /** - * Add lifecycle hooks - */ - lifecycle(hooks) { - Object.assign(this.plugin, hooks); - return this; - } - /** - * Build the plugin - */ - build() { - if (!this.plugin.name || !this.plugin.version) { - throw new Error("Plugin name and version are required"); - } - return this.plugin; - } -}; -var PluginHelpers = class { - /** - * Create a REST API route for a model. - * - * @experimental This method returns placeholder routes. Full implementation coming soon. - */ - static createModelAPI(modelName, options) { - const app = new hono.Hono(); - options?.basePath || `/${modelName.toLowerCase()}`; - app.get("/", async (c) => { - return c.json({ message: `List ${modelName} items` }); - }); - app.get("/:id", async (c) => { - const id = c.req.param("id"); - return c.json({ message: `Get ${modelName} with ID: ${id}` }); - }); - app.post("/", async (c) => { - return c.json({ message: `Create new ${modelName}` }); - }); - app.put("/:id", async (c) => { - const id = c.req.param("id"); - return c.json({ message: `Update ${modelName} with ID: ${id}` }); - }); - app.delete("/:id", async (c) => { - const id = c.req.param("id"); - return c.json({ message: `Delete ${modelName} with ID: ${id}` }); - }); - return app; - } - /** - * Create an admin CRUD interface for a model. - * - * @experimental This method generates basic admin page structures. Full implementation coming soon. - */ - static createAdminInterface(modelName, options) { - const basePath = `/admin/${modelName.toLowerCase()}`; - const displayName = modelName.charAt(0).toUpperCase() + modelName.slice(1); - const pages = [ - { - path: basePath, - title: `${displayName} List`, - component: `${modelName}List`, - permissions: options?.permissions, - icon: options?.icon - }, - { - path: `${basePath}/new`, - title: `New ${displayName}`, - component: `${modelName}Form`, - permissions: options?.permissions - }, - { - path: `${basePath}/:id`, - title: `Edit ${displayName}`, - component: `${modelName}Form`, - permissions: options?.permissions - } - ]; - const menuItems = [ - { - label: displayName, - path: basePath, - icon: options?.icon, - permissions: options?.permissions - } - ]; - return { pages, menuItems }; - } - /** - * Create a database migration for a model - */ - static createMigration(tableName, fields) { - const columns = fields.map((field) => { - let definition = `${field.name} ${field.type}`; - if (field.primaryKey) definition += " PRIMARY KEY"; - if (field.unique) definition += " UNIQUE"; - if (!field.nullable && !field.primaryKey) definition += " NOT NULL"; - if (field.defaultValue) definition += ` DEFAULT ${field.defaultValue}`; - return definition; - }).join(",\n "); - return ` -CREATE TABLE IF NOT EXISTS ${tableName} ( - ${columns}, - created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), - updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) -); - -CREATE TRIGGER IF NOT EXISTS ${tableName}_updated_at - AFTER UPDATE ON ${tableName} -BEGIN - UPDATE ${tableName} SET updated_at = strftime('%s', 'now') WHERE id = NEW.id; -END; - `.trim(); - } - /** - * Create a Zod schema for a model - */ - static createSchema(fields) { - const shape = {}; - const applyValidation = (field, schema) => { - if (field.validation) { - if (field.type === "string" && field.validation.min) { - schema = schema.min(field.validation.min); - } - if (field.type === "string" && field.validation.max) { - schema = schema.max(field.validation.max); - } - if (field.type === "string" && field.validation.email) { - schema = schema.email(); - } - if (field.type === "string" && field.validation.url) { - schema = schema.url(); - } - } - return schema; - }; - const buildSchema = (field) => { - let schema; - switch (field.type) { - case "string": - schema = zod.z.string(); - break; - case "number": - schema = zod.z.number(); - break; - case "boolean": - schema = zod.z.boolean(); - break; - case "date": - schema = zod.z.date(); - break; - case "array": - if (field.items?.blocks && typeof field.items.blocks === "object") { - const discriminator = typeof field.items.discriminator === "string" && field.items.discriminator ? field.items.discriminator : "blockType"; - const blockSchemas = Object.entries(field.items.blocks).map(([blockName, blockDef]) => { - const properties = blockDef?.properties && typeof blockDef.properties === "object" ? blockDef.properties : {}; - const blockShape = { - [discriminator]: zod.z.literal(blockName) - }; - Object.entries(properties).forEach(([propertyName, propertyConfigRaw]) => { - const propertyConfig = propertyConfigRaw && typeof propertyConfigRaw === "object" ? propertyConfigRaw : {}; - const propertySchema = buildSchema({ - ...propertyConfig, - optional: propertyConfig.required === false - }); - blockShape[propertyName] = propertySchema; - }); - return zod.z.object(blockShape); - }); - if (blockSchemas.length === 1 && blockSchemas[0]) { - schema = zod.z.array(blockSchemas[0]); - } else if (blockSchemas.length > 1) { - schema = zod.z.array(zod.z.union(blockSchemas)); - } else { - schema = zod.z.array(zod.z.any()); - } - break; - } - if (field.items) { - schema = zod.z.array(buildSchema(field.items)); - break; - } - schema = zod.z.array(zod.z.any()); - break; - case "object": - if (field.properties && typeof field.properties === "object") { - const objectShape = {}; - Object.entries(field.properties).forEach(([propertyName, propertyConfigRaw]) => { - const propertyConfig = propertyConfigRaw && typeof propertyConfigRaw === "object" ? propertyConfigRaw : {}; - objectShape[propertyName] = buildSchema({ - ...propertyConfig, - optional: propertyConfig.required === false - }); - }); - schema = zod.z.object(objectShape); - break; - } - schema = zod.z.object({}); - break; - default: - schema = zod.z.any(); - } - schema = applyValidation(field, schema); - if (field.optional || field.required === false) { - schema = schema.optional(); - } - return schema; - }; - for (const field of fields) { - shape[field.name] = buildSchema(field); - } - return zod.z.object(shape); - } -}; - -// src/plugins/core-plugins/turnstile-plugin/manifest.json -var manifest_default = { - id: "turnstile", - name: "Cloudflare Turnstile", - description: "CAPTCHA-free bot protection using Cloudflare Turnstile. Provides reusable verification for any form.", - version: "1.0.0", - author: "SonicJS", - category: "security", - icon: "shield-check", - homepage: "https://developers.cloudflare.com/turnstile/", - repository: "https://github.com/sonicjs/sonicjs", - license: "MIT", - permissions: ["settings:write", "admin:access"], - dependencies: [], - configSchema: { - siteKey: { - type: "string", - label: "Site Key", - description: "Your Cloudflare Turnstile site key (public)", - required: true - }, - secretKey: { - type: "string", - label: "Secret Key", - description: "Your Cloudflare Turnstile secret key (private)", - required: true, - sensitive: true - }, - theme: { - type: "select", - label: "Widget Theme", - description: "Visual theme for the Turnstile widget", - default: "auto", - options: [ - { value: "light", label: "Light" }, - { value: "dark", label: "Dark" }, - { value: "auto", label: "Auto" } - ] - }, - size: { - type: "select", - label: "Widget Size", - description: "Size of the Turnstile widget", - default: "normal", - options: [ - { value: "normal", label: "Normal" }, - { value: "compact", label: "Compact" } - ] - }, - mode: { - type: "select", - label: "Widget Mode", - description: "Managed: Adaptive challenge. Non-Interactive: Always visible, minimal friction. Invisible: No visible widget", - default: "managed", - options: [ - { value: "managed", label: "Managed (Recommended)" }, - { value: "non-interactive", label: "Non-Interactive" }, - { value: "invisible", label: "Invisible" } - ] - }, - appearance: { - type: "select", - label: "Appearance", - description: "When the Turnstile challenge is executed. Always: Verifies immediately. Execute: Challenge on form submit. Interaction Only: Only after user interaction", - default: "always", - options: [ - { value: "always", label: "Always" }, - { value: "execute", label: "Execute" }, - { value: "interaction-only", label: "Interaction Only" } - ] - }, - preClearance: { - type: "boolean", - label: "Enable Pre-clearance", - description: "Issue a clearance cookie that bypasses Cloudflare Firewall Rules (as if the user passed a challenge on your proxied site)", - default: false - }, - preClearanceLevel: { - type: "select", - label: "Pre-clearance Level", - description: "Controls which Cloudflare Firewall Rules the clearance cookie bypasses. Only applies if Pre-clearance is enabled", - default: "managed", - options: [ - { value: "interactive", label: "Interactive - Bypasses Interactive, Managed & JS Challenge Rules" }, - { value: "managed", label: "Managed - Bypasses Managed & JS Challenge Rules" }, - { value: "non-interactive", label: "Non-interactive - Bypasses JS Challenge Rules only" } - ] - }, - enabled: { - type: "boolean", - label: "Enable Turnstile", - description: "Enable or disable Turnstile verification globally", - default: true - } - }, - adminMenu: { - label: "Turnstile", - icon: "shield-check", - href: "/admin/plugins/turnstile/settings", - parentId: "plugins", - order: 100 - } -}; - -// src/plugins/core-plugins/turnstile-plugin/services/turnstile.ts -var TurnstileService = class { - db; - VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"; - constructor(db) { - this.db = db; - } - /** - * Get Turnstile settings from database - */ - async getSettings() { - try { - const plugin = await this.db.prepare(`SELECT settings FROM plugins WHERE id = ? LIMIT 1`).bind(manifest_default.id).first(); - if (!plugin || !plugin.settings) { - return null; - } - return JSON.parse(plugin.settings); - } catch (error) { - console.error("Error getting Turnstile settings:", error); - return null; - } - } - /** - * Verify a Turnstile token with Cloudflare - */ - async verifyToken(token, remoteIp) { - try { - const settings = await this.getSettings(); - if (!settings) { - return { success: false, error: "Turnstile not configured" }; - } - if (!settings.enabled) { - return { success: true }; - } - if (!settings.secretKey) { - return { success: false, error: "Turnstile secret key not configured" }; - } - const formData = new FormData(); - formData.append("secret", settings.secretKey); - formData.append("response", token); - if (remoteIp) { - formData.append("remoteip", remoteIp); - } - const response = await fetch(this.VERIFY_URL, { - method: "POST", - body: formData - }); - if (!response.ok) { - return { success: false, error: "Turnstile verification request failed" }; - } - const result = await response.json(); - if (!result.success) { - const errorCode = result["error-codes"]?.[0] || "unknown-error"; - return { success: false, error: `Turnstile verification failed: ${errorCode}` }; - } - return { success: true }; - } catch (error) { - console.error("Error verifying Turnstile token:", error); - return { success: false, error: "Turnstile verification error" }; - } - } - /** - * Save Turnstile settings to database - */ - async saveSettings(settings) { - try { - await this.db.prepare(`UPDATE plugins SET settings = ?, updated_at = ? WHERE id = ?`).bind(JSON.stringify(settings), Date.now(), manifest_default.id).run(); - console.log("Turnstile settings saved successfully"); - } catch (error) { - console.error("Error saving Turnstile settings:", error); - throw new Error("Failed to save Turnstile settings"); - } - } - /** - * Check if Turnstile is enabled - */ - async isEnabled() { - const settings = await this.getSettings(); - return settings?.enabled === true && !!settings.siteKey && !!settings.secretKey; - } -}; - -exports.PluginBuilder = PluginBuilder; -exports.PluginHelpers = PluginHelpers; -exports.TurnstileService = TurnstileService; -exports.manifest_default = manifest_default; -//# sourceMappingURL=chunk-6FHNRRJ3.cjs.map -//# sourceMappingURL=chunk-6FHNRRJ3.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-DVQA5II3.cjs b/packages/core/dist/chunk-DVQA5II3.cjs deleted file mode 100644 index 89d63d97c..000000000 --- a/packages/core/dist/chunk-DVQA5II3.cjs +++ /dev/null @@ -1,243 +0,0 @@ -'use strict'; - -var chunkMPT5PA6U_cjs = require('./chunk-MPT5PA6U.cjs'); -var chunkFQSMNIY2_cjs = require('./chunk-FQSMNIY2.cjs'); -var chunkRCQ2HIQD_cjs = require('./chunk-RCQ2HIQD.cjs'); -var jwt = require('hono/jwt'); -var cookie = require('hono/cookie'); - -// src/middleware/bootstrap.ts -var bootstrapComplete = false; -function bootstrapMiddleware(config = {}) { - return async (c, next) => { - if (bootstrapComplete) { - return next(); - } - const path = c.req.path; - if (path.startsWith("/images/") || path.startsWith("/assets/") || path === "/health" || path.endsWith(".js") || path.endsWith(".css") || path.endsWith(".png") || path.endsWith(".jpg") || path.endsWith(".ico")) { - return next(); - } - try { - console.log("[Bootstrap] Starting system initialization..."); - console.log("[Bootstrap] Running database migrations..."); - const migrationService = new chunkFQSMNIY2_cjs.MigrationService(c.env.DB); - await migrationService.runPendingMigrations(); - console.log("[Bootstrap] Syncing collection configurations..."); - try { - await chunkMPT5PA6U_cjs.syncCollections(c.env.DB); - } catch (error) { - console.error("[Bootstrap] Error syncing collections:", error); - } - if (!config.plugins?.disableAll) { - console.log("[Bootstrap] Bootstrapping core plugins..."); - const bootstrapService = new chunkMPT5PA6U_cjs.PluginBootstrapService(c.env.DB); - const needsBootstrap = await bootstrapService.isBootstrapNeeded(); - if (needsBootstrap) { - await bootstrapService.bootstrapCorePlugins(); - } - } else { - console.log("[Bootstrap] Plugin bootstrap skipped (disableAll is true)"); - } - bootstrapComplete = true; - console.log("[Bootstrap] System initialization completed"); - } catch (error) { - console.error("[Bootstrap] Error during system initialization:", error); - } - return next(); - }; -} -var JWT_SECRET = "your-super-secret-jwt-key-change-in-production"; -var AuthManager = class { - static async generateToken(userId, email, role) { - const payload = { - userId, - email, - role, - exp: Math.floor(Date.now() / 1e3) + 60 * 60 * 24, - // 24 hours - iat: Math.floor(Date.now() / 1e3) - }; - return await jwt.sign(payload, JWT_SECRET, "HS256"); - } - static async verifyToken(token) { - try { - const payload = await jwt.verify(token, JWT_SECRET, "HS256"); - if (payload.exp < Math.floor(Date.now() / 1e3)) { - return null; - } - return payload; - } catch (error) { - console.error("Token verification failed:", error); - return null; - } - } - static async hashPassword(password) { - const encoder = new TextEncoder(); - const data = encoder.encode(password + "salt-change-in-production"); - const hashBuffer = await crypto.subtle.digest("SHA-256", data); - const hashArray = Array.from(new Uint8Array(hashBuffer)); - return hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); - } - static async verifyPassword(password, hash) { - const passwordHash = await this.hashPassword(password); - return passwordHash === hash; - } - /** - * Set authentication cookie - useful for plugins implementing alternative auth methods - * @param c - Hono context - * @param token - JWT token to set in cookie - * @param options - Optional cookie configuration - */ - static setAuthCookie(c, token, options) { - cookie.setCookie(c, "auth_token", token, { - httpOnly: options?.httpOnly ?? true, - secure: options?.secure ?? true, - sameSite: options?.sameSite ?? "Strict", - maxAge: options?.maxAge ?? 60 * 60 * 24 - // 24 hours default - }); - } -}; -var requireAuth = () => { - return async (c, next) => { - try { - let token = c.req.header("Authorization")?.replace("Bearer ", ""); - if (!token) { - token = cookie.getCookie(c, "auth_token"); - } - if (!token) { - const acceptHeader = c.req.header("Accept") || ""; - if (acceptHeader.includes("text/html")) { - return c.redirect("/auth/login?error=Please login to access the admin area"); - } - return c.json({ error: "Authentication required" }, 401); - } - const kv = c.env?.KV; - let payload = null; - if (kv) { - const cacheKey = `auth:${token.substring(0, 20)}`; - const cached = await kv.get(cacheKey, "json"); - if (cached) { - payload = cached; - } - } - if (!payload) { - payload = await AuthManager.verifyToken(token); - if (payload && kv) { - const cacheKey = `auth:${token.substring(0, 20)}`; - await kv.put(cacheKey, JSON.stringify(payload), { expirationTtl: 300 }); - } - } - if (!payload) { - const acceptHeader = c.req.header("Accept") || ""; - if (acceptHeader.includes("text/html")) { - return c.redirect("/auth/login?error=Your session has expired, please login again"); - } - return c.json({ error: "Invalid or expired token" }, 401); - } - c.set("user", payload); - return await next(); - } catch (error) { - console.error("Auth middleware error:", error); - const acceptHeader = c.req.header("Accept") || ""; - if (acceptHeader.includes("text/html")) { - return c.redirect("/auth/login?error=Authentication failed, please login again"); - } - return c.json({ error: "Authentication failed" }, 401); - } - }; -}; -var requireRole = (requiredRole) => { - return async (c, next) => { - const user = c.get("user"); - if (!user) { - const acceptHeader = c.req.header("Accept") || ""; - if (acceptHeader.includes("text/html")) { - return c.redirect("/auth/login?error=Please login to access the admin area"); - } - return c.json({ error: "Authentication required" }, 401); - } - const roles = Array.isArray(requiredRole) ? requiredRole : [requiredRole]; - if (!roles.includes(user.role)) { - const acceptHeader = c.req.header("Accept") || ""; - if (acceptHeader.includes("text/html")) { - return c.redirect("/auth/login?error=You do not have permission to access this area"); - } - return c.json({ error: "Insufficient permissions" }, 403); - } - return await next(); - }; -}; -var optionalAuth = () => { - return async (c, next) => { - try { - let token = c.req.header("Authorization")?.replace("Bearer ", ""); - if (!token) { - token = cookie.getCookie(c, "auth_token"); - } - if (token) { - const payload = await AuthManager.verifyToken(token); - if (payload) { - c.set("user", payload); - } - } - return await next(); - } catch (error) { - console.error("Optional auth error:", error); - return await next(); - } - }; -}; - -// src/middleware/metrics.ts -var metricsMiddleware = () => { - return async (c, next) => { - const path = new URL(c.req.url).pathname; - if (path !== "/admin/dashboard/api/metrics") { - chunkRCQ2HIQD_cjs.metricsTracker.recordRequest(); - } - await next(); - }; -}; - -// src/middleware/index.ts -var loggingMiddleware = () => async (_c, next) => await next(); -var detailedLoggingMiddleware = () => async (_c, next) => await next(); -var securityLoggingMiddleware = () => async (_c, next) => await next(); -var performanceLoggingMiddleware = () => async (_c, next) => await next(); -var cacheHeaders = () => async (_c, next) => await next(); -var compressionMiddleware = async (_c, next) => await next(); -var securityHeaders = () => async (_c, next) => await next(); -var PermissionManager = {}; -var requirePermission = () => async (_c, next) => await next(); -var requireAnyPermission = () => async (_c, next) => await next(); -var logActivity = () => { -}; -var requireActivePlugin = () => async (_c, next) => await next(); -var requireActivePlugins = () => async (_c, next) => await next(); -var getActivePlugins = () => []; -var isPluginActive = () => false; - -exports.AuthManager = AuthManager; -exports.PermissionManager = PermissionManager; -exports.bootstrapMiddleware = bootstrapMiddleware; -exports.cacheHeaders = cacheHeaders; -exports.compressionMiddleware = compressionMiddleware; -exports.detailedLoggingMiddleware = detailedLoggingMiddleware; -exports.getActivePlugins = getActivePlugins; -exports.isPluginActive = isPluginActive; -exports.logActivity = logActivity; -exports.loggingMiddleware = loggingMiddleware; -exports.metricsMiddleware = metricsMiddleware; -exports.optionalAuth = optionalAuth; -exports.performanceLoggingMiddleware = performanceLoggingMiddleware; -exports.requireActivePlugin = requireActivePlugin; -exports.requireActivePlugins = requireActivePlugins; -exports.requireAnyPermission = requireAnyPermission; -exports.requireAuth = requireAuth; -exports.requirePermission = requirePermission; -exports.requireRole = requireRole; -exports.securityHeaders = securityHeaders; -exports.securityLoggingMiddleware = securityLoggingMiddleware; -//# sourceMappingURL=chunk-DVQA5II3.cjs.map -//# sourceMappingURL=chunk-DVQA5II3.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-FQSMNIY2.cjs b/packages/core/dist/chunk-FQSMNIY2.cjs deleted file mode 100644 index 9b446c600..000000000 --- a/packages/core/dist/chunk-FQSMNIY2.cjs +++ /dev/null @@ -1,2112 +0,0 @@ -'use strict'; - -// src/db/migrations-bundle.ts -var bundledMigrations = [ - { - id: "001", - name: "Initial Schema", - filename: "001_initial_schema.sql", - description: "Migration 001: Initial Schema", - sql: `-- Initial schema for SonicJS AI --- Create users table for authentication -CREATE TABLE IF NOT EXISTS users ( - id TEXT PRIMARY KEY, - email TEXT NOT NULL UNIQUE, - username TEXT NOT NULL UNIQUE, - first_name TEXT NOT NULL, - last_name TEXT NOT NULL, - password_hash TEXT, - role TEXT NOT NULL DEFAULT 'viewer', - avatar TEXT, - is_active INTEGER NOT NULL DEFAULT 1, - last_login_at INTEGER, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL -); - --- Create collections table for content schema definitions -CREATE TABLE IF NOT EXISTS collections ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL UNIQUE, - display_name TEXT NOT NULL, - description TEXT, - schema TEXT NOT NULL, -- JSON schema definition - is_active INTEGER NOT NULL DEFAULT 1, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL -); - --- Create content table for actual content data -CREATE TABLE IF NOT EXISTS content ( - id TEXT PRIMARY KEY, - collection_id TEXT NOT NULL REFERENCES collections(id), - slug TEXT NOT NULL, - title TEXT NOT NULL, - data TEXT NOT NULL, -- JSON content data - status TEXT NOT NULL DEFAULT 'draft', - published_at INTEGER, - author_id TEXT NOT NULL REFERENCES users(id), - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL -); - --- Create content_versions table for versioning -CREATE TABLE IF NOT EXISTS content_versions ( - id TEXT PRIMARY KEY, - content_id TEXT NOT NULL REFERENCES content(id), - version INTEGER NOT NULL, - data TEXT NOT NULL, -- JSON data - author_id TEXT NOT NULL REFERENCES users(id), - created_at INTEGER NOT NULL -); - --- Create media/files table with comprehensive R2 integration -CREATE TABLE IF NOT EXISTS media ( - id TEXT PRIMARY KEY, - filename TEXT NOT NULL, - original_name TEXT NOT NULL, - mime_type TEXT NOT NULL, - size INTEGER NOT NULL, - width INTEGER, - height INTEGER, - folder TEXT NOT NULL DEFAULT 'uploads', - r2_key TEXT NOT NULL, -- R2 storage key - public_url TEXT NOT NULL, -- CDN URL - thumbnail_url TEXT, -- Cloudflare Images URL - alt TEXT, - caption TEXT, - tags TEXT, -- JSON array of tags - uploaded_by TEXT NOT NULL REFERENCES users(id), - uploaded_at INTEGER NOT NULL, - updated_at INTEGER, - published_at INTEGER, - scheduled_at INTEGER, - archived_at INTEGER, - deleted_at INTEGER -); - --- Create API tokens table for programmatic access -CREATE TABLE IF NOT EXISTS api_tokens ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - token TEXT NOT NULL UNIQUE, - user_id TEXT NOT NULL REFERENCES users(id), - permissions TEXT NOT NULL, -- JSON array of permissions - expires_at INTEGER, - last_used_at INTEGER, - created_at INTEGER NOT NULL -); - --- Create workflow history table for content workflow tracking -CREATE TABLE IF NOT EXISTS workflow_history ( - id TEXT PRIMARY KEY, - content_id TEXT NOT NULL REFERENCES content(id), - action TEXT NOT NULL, - from_status TEXT NOT NULL, - to_status TEXT NOT NULL, - user_id TEXT NOT NULL REFERENCES users(id), - comment TEXT, - created_at INTEGER NOT NULL -); - --- Create indexes for better performance -CREATE INDEX IF NOT EXISTS idx_users_email ON users(email); -CREATE INDEX IF NOT EXISTS idx_users_username ON users(username); -CREATE INDEX IF NOT EXISTS idx_users_role ON users(role); - -CREATE INDEX IF NOT EXISTS idx_collections_name ON collections(name); -CREATE INDEX IF NOT EXISTS idx_collections_active ON collections(is_active); - -CREATE INDEX IF NOT EXISTS idx_content_collection ON content(collection_id); -CREATE INDEX IF NOT EXISTS idx_content_author ON content(author_id); -CREATE INDEX IF NOT EXISTS idx_content_status ON content(status); -CREATE INDEX IF NOT EXISTS idx_content_published ON content(published_at); -CREATE INDEX IF NOT EXISTS idx_content_slug ON content(slug); - -CREATE INDEX IF NOT EXISTS idx_content_versions_content ON content_versions(content_id); -CREATE INDEX IF NOT EXISTS idx_content_versions_version ON content_versions(version); - -CREATE INDEX IF NOT EXISTS idx_media_folder ON media(folder); -CREATE INDEX IF NOT EXISTS idx_media_type ON media(mime_type); -CREATE INDEX IF NOT EXISTS idx_media_uploaded_by ON media(uploaded_by); -CREATE INDEX IF NOT EXISTS idx_media_uploaded_at ON media(uploaded_at); -CREATE INDEX IF NOT EXISTS idx_media_deleted ON media(deleted_at); - -CREATE INDEX IF NOT EXISTS idx_api_tokens_user ON api_tokens(user_id); -CREATE INDEX IF NOT EXISTS idx_api_tokens_token ON api_tokens(token); - -CREATE INDEX IF NOT EXISTS idx_workflow_history_content ON workflow_history(content_id); -CREATE INDEX IF NOT EXISTS idx_workflow_history_user ON workflow_history(user_id); - --- Note: Admin user is created via the seed script with user-provided credentials --- Run 'npm run seed' after migrations to create the admin user - --- Insert sample collections -INSERT OR IGNORE INTO collections ( - id, name, display_name, description, schema, - is_active, created_at, updated_at -) VALUES ( - 'blog-posts-collection', - 'blog_posts', - 'Blog Posts', - 'Blog post content collection', - '{"type":"object","properties":{"title":{"type":"string","title":"Title","required":true},"content":{"type":"string","title":"Content","format":"richtext"},"excerpt":{"type":"string","title":"Excerpt"},"featured_image":{"type":"string","title":"Featured Image","format":"media"},"tags":{"type":"array","title":"Tags","items":{"type":"string"}},"status":{"type":"string","title":"Status","enum":["draft","published","archived"],"default":"draft"}},"required":["title"]}', - 1, - strftime('%s', 'now') * 1000, - strftime('%s', 'now') * 1000 -), -( - 'pages-collection', - 'pages', - 'Pages', - 'Static page content collection', - '{"type":"object","properties":{"title":{"type":"string","title":"Title","required":true},"content":{"type":"string","title":"Content","format":"richtext"},"slug":{"type":"string","title":"Slug"},"meta_description":{"type":"string","title":"Meta Description"},"featured_image":{"type":"string","title":"Featured Image","format":"media"}},"required":["title"]}', - 1, - strftime('%s', 'now') * 1000, - strftime('%s', 'now') * 1000 -), -( - 'news-collection', - 'news', - 'News', - 'News article content collection', - '{"type":"object","properties":{"title":{"type":"string","title":"Title","required":true},"content":{"type":"string","title":"Content","format":"richtext"},"publish_date":{"type":"string","title":"Publish Date","format":"date"},"author":{"type":"string","title":"Author"},"category":{"type":"string","title":"Category","enum":["technology","business","general"]}},"required":["title"]}', - 1, - strftime('%s', 'now') * 1000, - strftime('%s', 'now') * 1000 -); - --- Note: Sample content can be created via the admin interface after the admin user is seeded` - }, - { - id: "002", - name: "Faq Plugin", - filename: "002_faq_plugin.sql", - description: "Migration 002: Faq Plugin", - sql: `-- FAQ Plugin Migration (DEPRECATED - Now managed by third-party plugin) --- Creates FAQ table for the FAQ plugin --- NOTE: This migration is kept for historical purposes. --- The FAQ functionality is now provided by the faq-plugin third-party plugin. - -CREATE TABLE IF NOT EXISTS faqs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - question TEXT NOT NULL, - answer TEXT NOT NULL, - category TEXT, - tags TEXT, - isPublished INTEGER NOT NULL DEFAULT 1, - sortOrder INTEGER NOT NULL DEFAULT 0, - created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), - updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) -); - --- Create indexes for better performance -CREATE INDEX IF NOT EXISTS idx_faqs_category ON faqs(category); -CREATE INDEX IF NOT EXISTS idx_faqs_published ON faqs(isPublished); -CREATE INDEX IF NOT EXISTS idx_faqs_sort_order ON faqs(sortOrder); - --- Create trigger to update updated_at timestamp -CREATE TRIGGER IF NOT EXISTS faqs_updated_at - AFTER UPDATE ON faqs -BEGIN - UPDATE faqs SET updated_at = strftime('%s', 'now') WHERE id = NEW.id; -END; - --- Insert sample FAQ data -INSERT OR IGNORE INTO faqs (question, answer, category, tags, isPublished, sortOrder) VALUES -('What is SonicJS AI?', -'SonicJS AI is a modern, TypeScript-first headless CMS built for Cloudflare''s edge platform. It provides a complete content management system with admin interface, API endpoints, and plugin architecture.', -'general', -'sonicjs, cms, cloudflare', -1, -1), - -('How do I get started with SonicJS AI?', -'To get started: 1) Clone the repository, 2) Install dependencies with npm install, 3) Set up your Cloudflare account and services, 4) Run the development server with npm run dev, 5) Access the admin interface at /admin.', -'general', -'getting-started, setup', -1, -2), - -('What technologies does SonicJS AI use?', -'SonicJS AI is built with: TypeScript for type safety, Hono.js as the web framework, Cloudflare D1 for the database, Cloudflare R2 for media storage, Cloudflare Workers for serverless execution, and Tailwind CSS for styling.', -'technical', -'technology-stack, typescript, cloudflare', -1, -3), - -('How do I create content in SonicJS AI?', -'Content creation is done through the admin interface. Navigate to /admin, log in with your credentials, go to Content section, select a collection, and click "New Content" to create articles, pages, or other content types.', -'general', -'content-creation, admin', -1, -4), - -('Is SonicJS AI free to use?', -'SonicJS AI is open source and free to use. You only pay for the Cloudflare services you consume (D1 database, R2 storage, Workers execution time). Cloudflare offers generous free tiers for development and small projects.', -'billing', -'pricing, open-source, cloudflare', -1, -5), - -('How do I add custom functionality?', -'SonicJS AI features a plugin system that allows you to extend functionality. You can create plugins using the PluginBuilder API, add custom routes, models, admin pages, and integrate with external services.', -'technical', -'plugins, customization, development', -1, -6), - -('Can I customize the admin interface?', -'Yes! The admin interface is built with TypeScript templates and can be customized. You can modify existing templates, create new components, add custom pages, and integrate your own styling while maintaining the dark theme.', -'technical', -'admin-interface, customization, templates', -1, -7), - -('How does authentication work?', -'SonicJS AI includes a built-in authentication system with JWT tokens, role-based access control (admin, editor, viewer), secure password hashing, and session management. Users can be managed through the admin interface.', -'technical', -'authentication, security, users', -1, -8);` - }, - { - id: "003", - name: "Stage5 Enhancements", - filename: "003_stage5_enhancements.sql", - description: "Migration 003: Stage5 Enhancements", - sql: `-- Stage 5: Advanced Content Management enhancements --- Add scheduling and workflow features to content table - --- Add content scheduling columns -ALTER TABLE content ADD COLUMN scheduled_publish_at INTEGER; -ALTER TABLE content ADD COLUMN scheduled_unpublish_at INTEGER; - --- Add workflow and review columns -ALTER TABLE content ADD COLUMN review_status TEXT DEFAULT 'none'; -- none, pending, approved, rejected -ALTER TABLE content ADD COLUMN reviewer_id TEXT REFERENCES users(id); -ALTER TABLE content ADD COLUMN reviewed_at INTEGER; -ALTER TABLE content ADD COLUMN review_notes TEXT; - --- Add content metadata -ALTER TABLE content ADD COLUMN meta_title TEXT; -ALTER TABLE content ADD COLUMN meta_description TEXT; -ALTER TABLE content ADD COLUMN featured_image_id TEXT REFERENCES media(id); -ALTER TABLE content ADD COLUMN content_type TEXT DEFAULT 'standard'; -- standard, template, component - --- Create content_fields table for dynamic field definitions -CREATE TABLE IF NOT EXISTS content_fields ( - id TEXT PRIMARY KEY, - collection_id TEXT NOT NULL REFERENCES collections(id), - field_name TEXT NOT NULL, - field_type TEXT NOT NULL, -- text, richtext, number, boolean, date, select, media, relationship - field_label TEXT NOT NULL, - field_options TEXT, -- JSON for select options, validation rules, etc. - field_order INTEGER NOT NULL DEFAULT 0, - is_required INTEGER NOT NULL DEFAULT 0, - is_searchable INTEGER NOT NULL DEFAULT 0, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL, - UNIQUE(collection_id, field_name) -); - --- Create content_relationships table for content relationships -CREATE TABLE IF NOT EXISTS content_relationships ( - id TEXT PRIMARY KEY, - source_content_id TEXT NOT NULL REFERENCES content(id), - target_content_id TEXT NOT NULL REFERENCES content(id), - relationship_type TEXT NOT NULL, -- references, tags, categories - created_at INTEGER NOT NULL, - UNIQUE(source_content_id, target_content_id, relationship_type) -); - --- Create workflow_templates table for reusable workflows -CREATE TABLE IF NOT EXISTS workflow_templates ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - description TEXT, - collection_id TEXT REFERENCES collections(id), -- null means applies to all collections - workflow_steps TEXT NOT NULL, -- JSON array of workflow steps - is_active INTEGER NOT NULL DEFAULT 1, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL -); - --- Add indexes for new columns -CREATE INDEX IF NOT EXISTS idx_content_scheduled_publish ON content(scheduled_publish_at); -CREATE INDEX IF NOT EXISTS idx_content_scheduled_unpublish ON content(scheduled_unpublish_at); -CREATE INDEX IF NOT EXISTS idx_content_review_status ON content(review_status); -CREATE INDEX IF NOT EXISTS idx_content_reviewer ON content(reviewer_id); -CREATE INDEX IF NOT EXISTS idx_content_content_type ON content(content_type); - -CREATE INDEX IF NOT EXISTS idx_content_fields_collection ON content_fields(collection_id); -CREATE INDEX IF NOT EXISTS idx_content_fields_name ON content_fields(field_name); -CREATE INDEX IF NOT EXISTS idx_content_fields_type ON content_fields(field_type); -CREATE INDEX IF NOT EXISTS idx_content_fields_order ON content_fields(field_order); - -CREATE INDEX IF NOT EXISTS idx_content_relationships_source ON content_relationships(source_content_id); -CREATE INDEX IF NOT EXISTS idx_content_relationships_target ON content_relationships(target_content_id); -CREATE INDEX IF NOT EXISTS idx_content_relationships_type ON content_relationships(relationship_type); - -CREATE INDEX IF NOT EXISTS idx_workflow_templates_collection ON workflow_templates(collection_id); -CREATE INDEX IF NOT EXISTS idx_workflow_templates_active ON workflow_templates(is_active); - --- Insert default workflow template -INSERT OR IGNORE INTO workflow_templates ( - id, name, description, workflow_steps, is_active, created_at, updated_at -) VALUES ( - 'default-content-workflow', - 'Default Content Workflow', - 'Standard content workflow: Draft \u2192 Review \u2192 Published', - '[ - {"step": "draft", "name": "Draft", "description": "Content is being created", "permissions": ["author", "editor", "admin"]}, - {"step": "review", "name": "Under Review", "description": "Content is pending review", "permissions": ["editor", "admin"]}, - {"step": "published", "name": "Published", "description": "Content is live", "permissions": ["editor", "admin"]}, - {"step": "archived", "name": "Archived", "description": "Content is archived", "permissions": ["admin"]} - ]', - 1, - strftime('%s', 'now') * 1000, - strftime('%s', 'now') * 1000 -); - --- Insert enhanced field definitions for existing collections -INSERT OR IGNORE INTO content_fields ( - id, collection_id, field_name, field_type, field_label, field_options, field_order, is_required, is_searchable, created_at, updated_at -) VALUES --- Blog Posts fields -('blog-title-field', 'blog-posts-collection', 'title', 'text', 'Title', '{"maxLength": 200, "placeholder": "Enter blog post title"}', 1, 1, 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('blog-content-field', 'blog-posts-collection', 'content', 'richtext', 'Content', '{"toolbar": "full", "height": 400}', 2, 1, 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('blog-excerpt-field', 'blog-posts-collection', 'excerpt', 'text', 'Excerpt', '{"maxLength": 500, "rows": 3, "placeholder": "Brief description of the post"}', 3, 0, 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('blog-tags-field', 'blog-posts-collection', 'tags', 'select', 'Tags', '{"multiple": true, "options": ["technology", "business", "tutorial", "news", "update"], "allowCustom": true}', 4, 0, 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('blog-featured-image-field', 'blog-posts-collection', 'featured_image', 'media', 'Featured Image', '{"accept": "image/*", "maxSize": "5MB"}', 5, 0, 0, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('blog-publish-date-field', 'blog-posts-collection', 'publish_date', 'date', 'Publish Date', '{"format": "YYYY-MM-DD", "defaultToday": true}', 6, 0, 0, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('blog-featured-field', 'blog-posts-collection', 'is_featured', 'boolean', 'Featured Post', '{"default": false}', 7, 0, 0, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), - --- Pages fields -('pages-title-field', 'pages-collection', 'title', 'text', 'Title', '{"maxLength": 200, "placeholder": "Enter page title"}', 1, 1, 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('pages-content-field', 'pages-collection', 'content', 'richtext', 'Content', '{"toolbar": "full", "height": 500}', 2, 1, 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('pages-slug-field', 'pages-collection', 'slug', 'text', 'URL Slug', '{"pattern": "^[a-z0-9-]+$", "placeholder": "url-friendly-slug"}', 3, 1, 0, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('pages-meta-desc-field', 'pages-collection', 'meta_description', 'text', 'Meta Description', '{"maxLength": 160, "rows": 2, "placeholder": "SEO description for search engines"}', 4, 0, 0, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('pages-template-field', 'pages-collection', 'template', 'select', 'Page Template', '{"options": ["default", "landing", "contact", "about"], "default": "default"}', 5, 0, 0, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), - --- News fields -('news-title-field', 'news-collection', 'title', 'text', 'Title', '{"maxLength": 200, "placeholder": "Enter news title"}', 1, 1, 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('news-content-field', 'news-collection', 'content', 'richtext', 'Content', '{"toolbar": "news", "height": 400}', 2, 1, 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('news-category-field', 'news-collection', 'category', 'select', 'Category', '{"options": ["technology", "business", "politics", "sports", "entertainment", "health"], "required": true}', 3, 1, 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('news-author-field', 'news-collection', 'author', 'text', 'Author', '{"placeholder": "Author name"}', 4, 1, 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('news-source-field', 'news-collection', 'source', 'text', 'Source', '{"placeholder": "News source"}', 5, 0, 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000), -('news-priority-field', 'news-collection', 'priority', 'select', 'Priority', '{"options": ["low", "normal", "high", "breaking"], "default": "normal"}', 6, 0, 0, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000);` - }, - { - id: "004", - name: "Stage6 User Management", - filename: "004_stage6_user_management.sql", - description: "Migration 004: Stage6 User Management", - sql: "-- Stage 6: User Management & Permissions enhancements\n-- Enhanced user system with profiles, teams, permissions, and activity logging\n\n-- Add user profile and preferences columns\nALTER TABLE users ADD COLUMN phone TEXT;\nALTER TABLE users ADD COLUMN bio TEXT;\nALTER TABLE users ADD COLUMN avatar_url TEXT;\nALTER TABLE users ADD COLUMN timezone TEXT DEFAULT 'UTC';\nALTER TABLE users ADD COLUMN language TEXT DEFAULT 'en';\nALTER TABLE users ADD COLUMN email_notifications INTEGER DEFAULT 1;\nALTER TABLE users ADD COLUMN theme TEXT DEFAULT 'dark';\nALTER TABLE users ADD COLUMN two_factor_enabled INTEGER DEFAULT 0;\nALTER TABLE users ADD COLUMN two_factor_secret TEXT;\nALTER TABLE users ADD COLUMN password_reset_token TEXT;\nALTER TABLE users ADD COLUMN password_reset_expires INTEGER;\nALTER TABLE users ADD COLUMN email_verified INTEGER DEFAULT 0;\nALTER TABLE users ADD COLUMN email_verification_token TEXT;\nALTER TABLE users ADD COLUMN invitation_token TEXT;\nALTER TABLE users ADD COLUMN invited_by TEXT REFERENCES users(id);\nALTER TABLE users ADD COLUMN invited_at INTEGER;\nALTER TABLE users ADD COLUMN accepted_invitation_at INTEGER;\n\n-- Create teams table for team-based collaboration\nCREATE TABLE IF NOT EXISTS teams (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n description TEXT,\n slug TEXT NOT NULL UNIQUE,\n owner_id TEXT NOT NULL REFERENCES users(id),\n settings TEXT, -- JSON for team settings\n is_active INTEGER NOT NULL DEFAULT 1,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n);\n\n-- Create team memberships table\nCREATE TABLE IF NOT EXISTS team_memberships (\n id TEXT PRIMARY KEY,\n team_id TEXT NOT NULL REFERENCES teams(id) ON DELETE CASCADE,\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n role TEXT NOT NULL DEFAULT 'member', -- owner, admin, editor, member, viewer\n permissions TEXT, -- JSON for specific permissions\n joined_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n UNIQUE(team_id, user_id)\n);\n\n-- Create permissions table for granular access control\nCREATE TABLE IF NOT EXISTS permissions (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL UNIQUE,\n description TEXT,\n category TEXT NOT NULL, -- content, users, collections, media, settings\n created_at INTEGER NOT NULL\n);\n\n-- Create role permissions mapping\nCREATE TABLE IF NOT EXISTS role_permissions (\n id TEXT PRIMARY KEY,\n role TEXT NOT NULL,\n permission_id TEXT NOT NULL REFERENCES permissions(id),\n created_at INTEGER NOT NULL,\n UNIQUE(role, permission_id)\n);\n\n-- Create user sessions table for better session management\nCREATE TABLE IF NOT EXISTS user_sessions (\n id TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n token_hash TEXT NOT NULL,\n ip_address TEXT,\n user_agent TEXT,\n is_active INTEGER NOT NULL DEFAULT 1,\n expires_at INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n last_used_at INTEGER\n);\n\n-- Create activity log table for audit trails\nCREATE TABLE IF NOT EXISTS activity_logs (\n id TEXT PRIMARY KEY,\n user_id TEXT REFERENCES users(id),\n action TEXT NOT NULL,\n resource_type TEXT, -- users, content, collections, media, etc.\n resource_id TEXT,\n details TEXT, -- JSON with additional details\n ip_address TEXT,\n user_agent TEXT,\n created_at INTEGER NOT NULL\n);\n\n-- Create password history table for security\nCREATE TABLE IF NOT EXISTS password_history (\n id TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n password_hash TEXT NOT NULL,\n created_at INTEGER NOT NULL\n);\n\n-- Insert default permissions\nINSERT OR IGNORE INTO permissions (id, name, description, category, created_at) VALUES\n ('perm_content_create', 'content.create', 'Create new content', 'content', strftime('%s', 'now') * 1000),\n ('perm_content_read', 'content.read', 'View content', 'content', strftime('%s', 'now') * 1000),\n ('perm_content_update', 'content.update', 'Edit existing content', 'content', strftime('%s', 'now') * 1000),\n ('perm_content_delete', 'content.delete', 'Delete content', 'content', strftime('%s', 'now') * 1000),\n ('perm_content_publish', 'content.publish', 'Publish/unpublish content', 'content', strftime('%s', 'now') * 1000),\n \n ('perm_collections_create', 'collections.create', 'Create new collections', 'collections', strftime('%s', 'now') * 1000),\n ('perm_collections_read', 'collections.read', 'View collections', 'collections', strftime('%s', 'now') * 1000),\n ('perm_collections_update', 'collections.update', 'Edit collections', 'collections', strftime('%s', 'now') * 1000),\n ('perm_collections_delete', 'collections.delete', 'Delete collections', 'collections', strftime('%s', 'now') * 1000),\n ('perm_collections_fields', 'collections.fields', 'Manage collection fields', 'collections', strftime('%s', 'now') * 1000),\n \n ('perm_media_upload', 'media.upload', 'Upload media files', 'media', strftime('%s', 'now') * 1000),\n ('perm_media_read', 'media.read', 'View media files', 'media', strftime('%s', 'now') * 1000),\n ('perm_media_update', 'media.update', 'Edit media metadata', 'media', strftime('%s', 'now') * 1000),\n ('perm_media_delete', 'media.delete', 'Delete media files', 'media', strftime('%s', 'now') * 1000),\n \n ('perm_users_create', 'users.create', 'Invite new users', 'users', strftime('%s', 'now') * 1000),\n ('perm_users_read', 'users.read', 'View user profiles', 'users', strftime('%s', 'now') * 1000),\n ('perm_users_update', 'users.update', 'Edit user profiles', 'users', strftime('%s', 'now') * 1000),\n ('perm_users_delete', 'users.delete', 'Deactivate users', 'users', strftime('%s', 'now') * 1000),\n ('perm_users_roles', 'users.roles', 'Manage user roles', 'users', strftime('%s', 'now') * 1000),\n \n ('perm_settings_read', 'settings.read', 'View system settings', 'settings', strftime('%s', 'now') * 1000),\n ('perm_settings_update', 'settings.update', 'Modify system settings', 'settings', strftime('%s', 'now') * 1000),\n ('perm_activity_read', 'activity.read', 'View activity logs', 'settings', strftime('%s', 'now') * 1000);\n\n-- Assign permissions to default roles\nINSERT OR IGNORE INTO role_permissions (id, role, permission_id, created_at) VALUES\n -- Admin has all permissions\n ('rp_admin_content_create', 'admin', 'perm_content_create', strftime('%s', 'now') * 1000),\n ('rp_admin_content_read', 'admin', 'perm_content_read', strftime('%s', 'now') * 1000),\n ('rp_admin_content_update', 'admin', 'perm_content_update', strftime('%s', 'now') * 1000),\n ('rp_admin_content_delete', 'admin', 'perm_content_delete', strftime('%s', 'now') * 1000),\n ('rp_admin_content_publish', 'admin', 'perm_content_publish', strftime('%s', 'now') * 1000),\n ('rp_admin_collections_create', 'admin', 'perm_collections_create', strftime('%s', 'now') * 1000),\n ('rp_admin_collections_read', 'admin', 'perm_collections_read', strftime('%s', 'now') * 1000),\n ('rp_admin_collections_update', 'admin', 'perm_collections_update', strftime('%s', 'now') * 1000),\n ('rp_admin_collections_delete', 'admin', 'perm_collections_delete', strftime('%s', 'now') * 1000),\n ('rp_admin_collections_fields', 'admin', 'perm_collections_fields', strftime('%s', 'now') * 1000),\n ('rp_admin_media_upload', 'admin', 'perm_media_upload', strftime('%s', 'now') * 1000),\n ('rp_admin_media_read', 'admin', 'perm_media_read', strftime('%s', 'now') * 1000),\n ('rp_admin_media_update', 'admin', 'perm_media_update', strftime('%s', 'now') * 1000),\n ('rp_admin_media_delete', 'admin', 'perm_media_delete', strftime('%s', 'now') * 1000),\n ('rp_admin_users_create', 'admin', 'perm_users_create', strftime('%s', 'now') * 1000),\n ('rp_admin_users_read', 'admin', 'perm_users_read', strftime('%s', 'now') * 1000),\n ('rp_admin_users_update', 'admin', 'perm_users_update', strftime('%s', 'now') * 1000),\n ('rp_admin_users_delete', 'admin', 'perm_users_delete', strftime('%s', 'now') * 1000),\n ('rp_admin_users_roles', 'admin', 'perm_users_roles', strftime('%s', 'now') * 1000),\n ('rp_admin_settings_read', 'admin', 'perm_settings_read', strftime('%s', 'now') * 1000),\n ('rp_admin_settings_update', 'admin', 'perm_settings_update', strftime('%s', 'now') * 1000),\n ('rp_admin_activity_read', 'admin', 'perm_activity_read', strftime('%s', 'now') * 1000),\n \n -- Editor permissions\n ('rp_editor_content_create', 'editor', 'perm_content_create', strftime('%s', 'now') * 1000),\n ('rp_editor_content_read', 'editor', 'perm_content_read', strftime('%s', 'now') * 1000),\n ('rp_editor_content_update', 'editor', 'perm_content_update', strftime('%s', 'now') * 1000),\n ('rp_editor_content_publish', 'editor', 'perm_content_publish', strftime('%s', 'now') * 1000),\n ('rp_editor_collections_read', 'editor', 'perm_collections_read', strftime('%s', 'now') * 1000),\n ('rp_editor_media_upload', 'editor', 'perm_media_upload', strftime('%s', 'now') * 1000),\n ('rp_editor_media_read', 'editor', 'perm_media_read', strftime('%s', 'now') * 1000),\n ('rp_editor_media_update', 'editor', 'perm_media_update', strftime('%s', 'now') * 1000),\n ('rp_editor_users_read', 'editor', 'perm_users_read', strftime('%s', 'now') * 1000),\n \n -- Viewer permissions\n ('rp_viewer_content_read', 'viewer', 'perm_content_read', strftime('%s', 'now') * 1000),\n ('rp_viewer_collections_read', 'viewer', 'perm_collections_read', strftime('%s', 'now') * 1000),\n ('rp_viewer_media_read', 'viewer', 'perm_media_read', strftime('%s', 'now') * 1000),\n ('rp_viewer_users_read', 'viewer', 'perm_users_read', strftime('%s', 'now') * 1000);\n\n-- Create indexes for performance\nCREATE INDEX IF NOT EXISTS idx_team_memberships_team_id ON team_memberships(team_id);\nCREATE INDEX IF NOT EXISTS idx_team_memberships_user_id ON team_memberships(user_id);\nCREATE INDEX IF NOT EXISTS idx_user_sessions_user_id ON user_sessions(user_id);\nCREATE INDEX IF NOT EXISTS idx_user_sessions_token_hash ON user_sessions(token_hash);\nCREATE INDEX IF NOT EXISTS idx_activity_logs_user_id ON activity_logs(user_id);\nCREATE INDEX IF NOT EXISTS idx_activity_logs_created_at ON activity_logs(created_at);\nCREATE INDEX IF NOT EXISTS idx_activity_logs_resource ON activity_logs(resource_type, resource_id);\nCREATE INDEX IF NOT EXISTS idx_password_history_user_id ON password_history(user_id);\nCREATE INDEX IF NOT EXISTS idx_users_email_verification_token ON users(email_verification_token);\nCREATE INDEX IF NOT EXISTS idx_users_password_reset_token ON users(password_reset_token);\nCREATE INDEX IF NOT EXISTS idx_users_invitation_token ON users(invitation_token);" - }, - { - id: "005", - name: "Stage7 Workflow Automation", - filename: "005_stage7_workflow_automation.sql", - description: "Migration 005: Stage7 Workflow Automation", - sql: "-- Stage 7: Workflow & Automation Migration\n-- This migration adds workflow and automation capabilities to SonicJS\n\n-- Workflow States Table\nCREATE TABLE IF NOT EXISTS workflow_states (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n name TEXT NOT NULL,\n description TEXT,\n color TEXT DEFAULT '#6B7280',\n is_initial INTEGER DEFAULT 0,\n is_final INTEGER DEFAULT 0,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP\n);\n\n-- Insert default workflow states\nINSERT OR IGNORE INTO workflow_states (id, name, description, color, is_initial, is_final) VALUES\n('draft', 'Draft', 'Content is being worked on', '#F59E0B', 1, 0),\n('pending-review', 'Pending Review', 'Content is waiting for review', '#3B82F6', 0, 0),\n('approved', 'Approved', 'Content has been approved', '#10B981', 0, 0),\n('published', 'Published', 'Content is live', '#059669', 0, 1),\n('rejected', 'Rejected', 'Content was rejected', '#EF4444', 0, 1),\n('archived', 'Archived', 'Content has been archived', '#6B7280', 0, 1);\n\n-- Workflows Table\nCREATE TABLE IF NOT EXISTS workflows (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n name TEXT NOT NULL,\n description TEXT,\n collection_id TEXT,\n is_active INTEGER DEFAULT 1,\n auto_publish INTEGER DEFAULT 0,\n require_approval INTEGER DEFAULT 1,\n approval_levels INTEGER DEFAULT 1,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE\n);\n\n-- Workflow Transitions Table\nCREATE TABLE IF NOT EXISTS workflow_transitions (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n workflow_id TEXT NOT NULL,\n from_state_id TEXT NOT NULL,\n to_state_id TEXT NOT NULL,\n required_permission TEXT,\n auto_transition INTEGER DEFAULT 0,\n transition_conditions TEXT, -- JSON\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (workflow_id) REFERENCES workflows(id) ON DELETE CASCADE,\n FOREIGN KEY (from_state_id) REFERENCES workflow_states(id),\n FOREIGN KEY (to_state_id) REFERENCES workflow_states(id)\n);\n\n-- Content Workflow Status Table\nCREATE TABLE IF NOT EXISTS content_workflow_status (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n content_id TEXT NOT NULL,\n workflow_id TEXT NOT NULL,\n current_state_id TEXT NOT NULL,\n assigned_to TEXT,\n due_date DATETIME,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (content_id) REFERENCES content(id) ON DELETE CASCADE,\n FOREIGN KEY (workflow_id) REFERENCES workflows(id),\n FOREIGN KEY (current_state_id) REFERENCES workflow_states(id),\n FOREIGN KEY (assigned_to) REFERENCES users(id),\n UNIQUE(content_id, workflow_id)\n);\n\n-- Workflow History Table\nCREATE TABLE IF NOT EXISTS workflow_history (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n content_id TEXT NOT NULL,\n workflow_id TEXT NOT NULL,\n from_state_id TEXT,\n to_state_id TEXT NOT NULL,\n user_id TEXT NOT NULL,\n comment TEXT,\n metadata TEXT, -- JSON\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (content_id) REFERENCES content(id) ON DELETE CASCADE,\n FOREIGN KEY (workflow_id) REFERENCES workflows(id),\n FOREIGN KEY (from_state_id) REFERENCES workflow_states(id),\n FOREIGN KEY (to_state_id) REFERENCES workflow_states(id),\n FOREIGN KEY (user_id) REFERENCES users(id)\n);\n\n-- Scheduled Content Table\nCREATE TABLE IF NOT EXISTS scheduled_content (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n content_id TEXT NOT NULL,\n action TEXT NOT NULL, -- 'publish', 'unpublish', 'archive'\n scheduled_at DATETIME NOT NULL,\n timezone TEXT DEFAULT 'UTC',\n user_id TEXT NOT NULL,\n status TEXT DEFAULT 'pending', -- 'pending', 'completed', 'failed', 'cancelled'\n executed_at DATETIME,\n error_message TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (content_id) REFERENCES content(id) ON DELETE CASCADE,\n FOREIGN KEY (user_id) REFERENCES users(id)\n);\n\n-- Notifications Table\nCREATE TABLE IF NOT EXISTS notifications (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n user_id TEXT NOT NULL,\n type TEXT NOT NULL, -- 'workflow', 'schedule', 'system'\n title TEXT NOT NULL,\n message TEXT NOT NULL,\n data TEXT, -- JSON\n is_read INTEGER DEFAULT 0,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE\n);\n\n-- Notification Preferences Table\nCREATE TABLE IF NOT EXISTS notification_preferences (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n user_id TEXT NOT NULL,\n notification_type TEXT NOT NULL,\n email_enabled INTEGER DEFAULT 1,\n in_app_enabled INTEGER DEFAULT 1,\n digest_frequency TEXT DEFAULT 'daily', -- 'immediate', 'hourly', 'daily', 'weekly'\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,\n UNIQUE(user_id, notification_type)\n);\n\n-- Webhooks Table\nCREATE TABLE IF NOT EXISTS webhooks (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n name TEXT NOT NULL,\n url TEXT NOT NULL,\n secret TEXT,\n events TEXT NOT NULL, -- JSON array of event types\n is_active INTEGER DEFAULT 1,\n retry_count INTEGER DEFAULT 3,\n timeout_seconds INTEGER DEFAULT 30,\n last_success_at DATETIME,\n last_failure_at DATETIME,\n failure_count INTEGER DEFAULT 0,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP\n);\n\n-- Webhook Deliveries Table\nCREATE TABLE IF NOT EXISTS webhook_deliveries (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n webhook_id TEXT NOT NULL,\n event_type TEXT NOT NULL,\n payload TEXT NOT NULL, -- JSON\n response_status INTEGER,\n response_body TEXT,\n attempt_count INTEGER DEFAULT 1,\n delivered_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (webhook_id) REFERENCES webhooks(id) ON DELETE CASCADE\n);\n\n-- Content Versions Table (for rollback functionality)\nCREATE TABLE IF NOT EXISTS content_versions (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n content_id TEXT NOT NULL,\n version_number INTEGER NOT NULL,\n title TEXT NOT NULL,\n content TEXT NOT NULL,\n fields TEXT, -- JSON\n user_id TEXT NOT NULL,\n change_summary TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (content_id) REFERENCES content(id) ON DELETE CASCADE,\n FOREIGN KEY (user_id) REFERENCES users(id),\n UNIQUE(content_id, version_number)\n);\n\n-- Automation Rules Table\nCREATE TABLE IF NOT EXISTS automation_rules (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n name TEXT NOT NULL,\n description TEXT,\n trigger_type TEXT NOT NULL, -- 'content_created', 'content_updated', 'workflow_transition', 'schedule'\n trigger_conditions TEXT, -- JSON\n action_type TEXT NOT NULL, -- 'workflow_transition', 'send_notification', 'webhook_call', 'auto_save'\n action_config TEXT, -- JSON\n is_active INTEGER DEFAULT 1,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP\n);\n\n-- Auto-save Drafts Table\nCREATE TABLE IF NOT EXISTS auto_save_drafts (\n id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),\n content_id TEXT,\n user_id TEXT NOT NULL,\n title TEXT,\n content TEXT,\n fields TEXT, -- JSON\n last_saved_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (content_id) REFERENCES content(id) ON DELETE CASCADE,\n FOREIGN KEY (user_id) REFERENCES users(id),\n UNIQUE(content_id, user_id)\n);\n\n-- Add workflow-related columns to existing content table (skip existing columns)\nALTER TABLE content ADD COLUMN workflow_state_id TEXT DEFAULT 'draft';\nALTER TABLE content ADD COLUMN embargo_until DATETIME;\nALTER TABLE content ADD COLUMN expires_at DATETIME;\nALTER TABLE content ADD COLUMN version_number INTEGER DEFAULT 1;\nALTER TABLE content ADD COLUMN is_auto_saved INTEGER DEFAULT 0;\n\n-- Create indexes for performance\nCREATE INDEX IF NOT EXISTS idx_content_workflow_status_content_id ON content_workflow_status(content_id);\nCREATE INDEX IF NOT EXISTS idx_content_workflow_status_workflow_id ON content_workflow_status(workflow_id);\nCREATE INDEX IF NOT EXISTS idx_workflow_history_content_id ON workflow_history(content_id);\nCREATE INDEX IF NOT EXISTS idx_scheduled_content_scheduled_at ON scheduled_content(scheduled_at);\nCREATE INDEX IF NOT EXISTS idx_scheduled_content_status ON scheduled_content(status);\nCREATE INDEX IF NOT EXISTS idx_notifications_user_id ON notifications(user_id);\nCREATE INDEX IF NOT EXISTS idx_notifications_is_read ON notifications(is_read);\nCREATE INDEX IF NOT EXISTS idx_content_versions_content_id ON content_versions(content_id);\nCREATE INDEX IF NOT EXISTS idx_auto_save_drafts_user_id ON auto_save_drafts(user_id);\nCREATE INDEX IF NOT EXISTS idx_content_workflow_state ON content(workflow_state_id);\nCREATE INDEX IF NOT EXISTS idx_content_scheduled_publish ON content(scheduled_publish_at);\n\n-- Insert default workflow for collections\nINSERT OR IGNORE INTO workflows (id, name, description, collection_id, is_active, require_approval, approval_levels) \nSELECT \n 'default-' || id,\n 'Default Workflow for ' || name,\n 'Standard content approval workflow',\n id,\n 1,\n 1,\n 1\nFROM collections;\n\n-- Insert default workflow transitions\nINSERT OR IGNORE INTO workflow_transitions (workflow_id, from_state_id, to_state_id, required_permission) \nSELECT \n w.id,\n 'draft',\n 'pending-review',\n 'content:submit'\nFROM workflows w;\n\nINSERT OR IGNORE INTO workflow_transitions (workflow_id, from_state_id, to_state_id, required_permission) \nSELECT \n w.id,\n 'pending-review',\n 'approved',\n 'content:approve'\nFROM workflows w;\n\nINSERT OR IGNORE INTO workflow_transitions (workflow_id, from_state_id, to_state_id, required_permission) \nSELECT \n w.id,\n 'approved',\n 'published',\n 'content:publish'\nFROM workflows w;\n\nINSERT OR IGNORE INTO workflow_transitions (workflow_id, from_state_id, to_state_id, required_permission) \nSELECT \n w.id,\n 'pending-review',\n 'rejected',\n 'content:approve'\nFROM workflows w;\n\n-- Insert default notification preferences for all users\nINSERT OR IGNORE INTO notification_preferences (user_id, notification_type, email_enabled, in_app_enabled)\nSELECT \n id,\n 'workflow_assigned',\n 1,\n 1\nFROM users;\n\nINSERT OR IGNORE INTO notification_preferences (user_id, notification_type, email_enabled, in_app_enabled)\nSELECT \n id,\n 'workflow_status_change',\n 1,\n 1\nFROM users;\n\nINSERT OR IGNORE INTO notification_preferences (user_id, notification_type, email_enabled, in_app_enabled)\nSELECT \n id,\n 'content_scheduled',\n 1,\n 1\nFROM users;" - }, - { - id: "006", - name: "Plugin System", - filename: "006_plugin_system.sql", - description: "Migration 006: Plugin System", - sql: `-- Plugin System Tables --- Migration: 006_plugin_system --- Description: Add plugin management system tables - --- Plugins table -CREATE TABLE IF NOT EXISTS plugins ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL UNIQUE, - display_name TEXT NOT NULL, - description TEXT, - version TEXT NOT NULL, - author TEXT NOT NULL, - category TEXT NOT NULL, - icon TEXT, - status TEXT DEFAULT 'inactive' CHECK (status IN ('active', 'inactive', 'error')), - is_core BOOLEAN DEFAULT FALSE, - settings JSON, - permissions JSON, - dependencies JSON, - download_count INTEGER DEFAULT 0, - rating REAL DEFAULT 0, - installed_at INTEGER NOT NULL, - activated_at INTEGER, - last_updated INTEGER NOT NULL, - error_message TEXT, - created_at INTEGER DEFAULT (unixepoch()), - updated_at INTEGER DEFAULT (unixepoch()) -); - --- Plugin hooks table (registered hooks by plugins) -CREATE TABLE IF NOT EXISTS plugin_hooks ( - id TEXT PRIMARY KEY, - plugin_id TEXT NOT NULL, - hook_name TEXT NOT NULL, - handler_name TEXT NOT NULL, - priority INTEGER DEFAULT 10, - is_active BOOLEAN DEFAULT TRUE, - created_at INTEGER DEFAULT (unixepoch()), - FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE, - UNIQUE(plugin_id, hook_name, handler_name) -); - --- Plugin routes table -CREATE TABLE IF NOT EXISTS plugin_routes ( - id TEXT PRIMARY KEY, - plugin_id TEXT NOT NULL, - path TEXT NOT NULL, - method TEXT NOT NULL, - handler_name TEXT NOT NULL, - middleware JSON, - is_active BOOLEAN DEFAULT TRUE, - created_at INTEGER DEFAULT (unixepoch()), - FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE, - UNIQUE(plugin_id, path, method) -); - --- Plugin assets table (CSS, JS files provided by plugins) -CREATE TABLE IF NOT EXISTS plugin_assets ( - id TEXT PRIMARY KEY, - plugin_id TEXT NOT NULL, - asset_type TEXT NOT NULL CHECK (asset_type IN ('css', 'js', 'image', 'font')), - asset_path TEXT NOT NULL, - load_order INTEGER DEFAULT 100, - load_location TEXT DEFAULT 'footer' CHECK (load_location IN ('header', 'footer')), - is_active BOOLEAN DEFAULT TRUE, - created_at INTEGER DEFAULT (unixepoch()), - FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE -); - --- Plugin activity log -CREATE TABLE IF NOT EXISTS plugin_activity_log ( - id TEXT PRIMARY KEY, - plugin_id TEXT NOT NULL, - action TEXT NOT NULL, - user_id TEXT, - details JSON, - timestamp INTEGER DEFAULT (unixepoch()), - FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE -); - --- Create indexes -CREATE INDEX IF NOT EXISTS idx_plugins_status ON plugins(status); -CREATE INDEX IF NOT EXISTS idx_plugins_category ON plugins(category); -CREATE INDEX IF NOT EXISTS idx_plugin_hooks_plugin ON plugin_hooks(plugin_id); -CREATE INDEX IF NOT EXISTS idx_plugin_routes_plugin ON plugin_routes(plugin_id); -CREATE INDEX IF NOT EXISTS idx_plugin_assets_plugin ON plugin_assets(plugin_id); -CREATE INDEX IF NOT EXISTS idx_plugin_activity_plugin ON plugin_activity_log(plugin_id); -CREATE INDEX IF NOT EXISTS idx_plugin_activity_timestamp ON plugin_activity_log(timestamp); - --- Insert core plugins -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, installed_at, last_updated -) VALUES -( - 'core-auth', - 'core-auth', - 'Authentication System', - 'Core authentication and user management system', - '1.0.0', - 'SonicJS Team', - 'security', - '\u{1F510}', - 'active', - TRUE, - '["manage:users", "manage:roles", "manage:permissions"]', - unixepoch(), - unixepoch() -), -( - 'core-media', - 'core-media', - 'Media Manager', - 'Core media upload and management system', - '1.0.0', - 'SonicJS Team', - 'media', - '\u{1F4F8}', - 'active', - TRUE, - '["manage:media", "upload:files"]', - unixepoch(), - unixepoch() -), -( - 'core-workflow', - 'core-workflow', - 'Workflow Engine', - 'Content workflow and approval system', - '1.0.0', - 'SonicJS Team', - 'content', - '\u{1F504}', - 'active', - TRUE, - '["manage:workflows", "approve:content"]', - unixepoch(), - unixepoch() -); - --- FAQ Plugin will be added as a third-party plugin through the admin interface - --- Add plugin management permission -INSERT OR IGNORE INTO permissions (id, name, description, category, created_at) -VALUES ( - 'manage:plugins', - 'Manage Plugins', - 'Install, uninstall, activate, and configure plugins', - 'system', - unixepoch() -); - --- Grant plugin management permission to admin role -INSERT OR IGNORE INTO role_permissions (id, role, permission_id, created_at) -VALUES ('role-perm-manage-plugins', 'admin', 'manage:plugins', unixepoch());` - }, - { - id: "007", - name: "Demo Login Plugin", - filename: "007_demo_login_plugin.sql", - description: "Migration 007: Demo Login Plugin", - sql: "-- Demo Login Plugin Migration\n-- Migration: 007_demo_login_plugin\n-- Description: Add demo login prefill plugin to the plugin registry\n\n-- Insert demo login plugin\nINSERT INTO plugins (\n id, name, display_name, description, version, author, category, icon, \n status, is_core, permissions, installed_at, last_updated\n) VALUES (\n 'demo-login-prefill',\n 'demo-login-plugin',\n 'Demo Login Prefill',\n 'Prefills login form with demo credentials (admin@sonicjs.com/sonicjs!) for easy site demonstration',\n '1.0.0',\n 'SonicJS',\n 'demo',\n '\u{1F3AF}',\n 'inactive',\n TRUE,\n '[]',\n unixepoch(),\n unixepoch()\n);" - }, - { - id: "008", - name: "Fix Slug Validation", - filename: "008_fix_slug_validation.sql", - description: "Migration 008: Fix Slug Validation", - sql: `-- Migration: Fix overly restrictive slug validation patterns --- This migration relaxes the slug field validation to be more user-friendly - --- Update the pages collection slug field to allow underscores and be less restrictive -UPDATE content_fields -SET field_options = '{"pattern": "^[a-zA-Z0-9_-]+$", "placeholder": "url-friendly-slug", "help": "Use letters, numbers, underscores, and hyphens only"}' -WHERE field_name = 'slug' AND collection_id = 'pages-collection'; - --- Update blog posts slug field if it exists -UPDATE content_fields -SET field_options = '{"pattern": "^[a-zA-Z0-9_-]+$", "placeholder": "url-friendly-slug", "help": "Use letters, numbers, underscores, and hyphens only"}' -WHERE field_name = 'slug' AND collection_id = 'blog-posts-collection'; - --- Update news slug field if it exists -UPDATE content_fields -SET field_options = '{"pattern": "^[a-zA-Z0-9_-]+$", "placeholder": "url-friendly-slug", "help": "Use letters, numbers, underscores, and hyphens only"}' -WHERE field_name = 'slug' AND collection_id = 'news-collection'; - --- Update any other slug fields with the restrictive pattern -UPDATE content_fields -SET field_options = REPLACE(field_options, '"pattern": "^[a-z0-9-]+$"', '"pattern": "^[a-zA-Z0-9_-]+$"') -WHERE field_options LIKE '%"pattern": "^[a-z0-9-]+$"%';` - }, - { - id: "009", - name: "System Logging", - filename: "009_system_logging.sql", - description: "Migration 009: System Logging", - sql: "-- System Logging Tables\n-- Migration: 009_system_logging\n-- Description: Add system logging and configuration tables\n\n-- System logs table for tracking application events\nCREATE TABLE IF NOT EXISTS system_logs (\n id TEXT PRIMARY KEY,\n level TEXT NOT NULL CHECK (level IN ('debug', 'info', 'warn', 'error', 'fatal')),\n category TEXT NOT NULL CHECK (category IN ('auth', 'api', 'workflow', 'plugin', 'media', 'system', 'security', 'error')),\n message TEXT NOT NULL,\n data TEXT, -- JSON data\n user_id TEXT,\n session_id TEXT,\n request_id TEXT,\n ip_address TEXT,\n user_agent TEXT,\n method TEXT,\n url TEXT,\n status_code INTEGER,\n duration INTEGER, -- milliseconds\n stack_trace TEXT,\n tags TEXT, -- JSON array\n source TEXT, -- source of the log entry\n created_at INTEGER NOT NULL DEFAULT (unixepoch()),\n FOREIGN KEY (user_id) REFERENCES users(id)\n);\n\n-- Log configuration table for managing log settings per category\nCREATE TABLE IF NOT EXISTS log_config (\n id TEXT PRIMARY KEY,\n category TEXT NOT NULL UNIQUE CHECK (category IN ('auth', 'api', 'workflow', 'plugin', 'media', 'system', 'security', 'error')),\n enabled BOOLEAN NOT NULL DEFAULT TRUE,\n level TEXT NOT NULL DEFAULT 'info' CHECK (level IN ('debug', 'info', 'warn', 'error', 'fatal')),\n retention_days INTEGER NOT NULL DEFAULT 30,\n max_size_mb INTEGER NOT NULL DEFAULT 100,\n created_at INTEGER NOT NULL DEFAULT (unixepoch()),\n updated_at INTEGER NOT NULL DEFAULT (unixepoch())\n);\n\n-- Create indexes for better performance\nCREATE INDEX IF NOT EXISTS idx_system_logs_level ON system_logs(level);\nCREATE INDEX IF NOT EXISTS idx_system_logs_category ON system_logs(category);\nCREATE INDEX IF NOT EXISTS idx_system_logs_created_at ON system_logs(created_at);\nCREATE INDEX IF NOT EXISTS idx_system_logs_user_id ON system_logs(user_id);\nCREATE INDEX IF NOT EXISTS idx_system_logs_status_code ON system_logs(status_code);\nCREATE INDEX IF NOT EXISTS idx_system_logs_source ON system_logs(source);\n\n-- Insert default log configurations\nINSERT OR IGNORE INTO log_config (id, category, enabled, level, retention_days, max_size_mb) VALUES\n('log-config-auth', 'auth', TRUE, 'info', 90, 50),\n('log-config-api', 'api', TRUE, 'info', 30, 100),\n('log-config-workflow', 'workflow', TRUE, 'info', 60, 50),\n('log-config-plugin', 'plugin', TRUE, 'warn', 30, 25),\n('log-config-media', 'media', TRUE, 'info', 30, 50),\n('log-config-system', 'system', TRUE, 'info', 90, 100),\n('log-config-security', 'security', TRUE, 'warn', 180, 100),\n('log-config-error', 'error', TRUE, 'error', 90, 200);" - }, - { - id: "011", - name: "Config Managed Collections", - filename: "011_config_managed_collections.sql", - description: "Migration 011: Config Managed Collections", - sql: "-- Migration: Add Config-Managed Collections Support\n-- Description: Add 'managed' column to collections table to support config-based collection definitions\n-- Created: 2025-10-03\n\n-- Add 'managed' column to collections table\n-- This column indicates whether a collection is managed by configuration files (true) or user-created (false)\n-- Managed collections cannot be edited through the admin UI\n-- Use a safe approach to add the column only if it doesn't exist\nALTER TABLE collections ADD COLUMN managed INTEGER DEFAULT 0 NOT NULL;\n\n-- Create an index on the managed column for faster queries\nCREATE INDEX IF NOT EXISTS idx_collections_managed ON collections(managed);\n\n-- Create an index on managed + is_active for efficient filtering\nCREATE INDEX IF NOT EXISTS idx_collections_managed_active ON collections(managed, is_active);\n" - }, - { - id: "012", - name: "Testimonials Plugin", - filename: "012_testimonials_plugin.sql", - description: "Migration 012: Testimonials Plugin", - sql: `-- Testimonials Plugin Migration --- Creates testimonials table for the testimonials plugin --- This demonstrates a code-based collection defined in src/plugins/core-plugins/testimonials-plugin.ts - -CREATE TABLE IF NOT EXISTS testimonials ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - author_name TEXT NOT NULL, - author_title TEXT, - author_company TEXT, - testimonial_text TEXT NOT NULL, - rating INTEGER CHECK(rating >= 1 AND rating <= 5), - isPublished INTEGER NOT NULL DEFAULT 1, - sortOrder INTEGER NOT NULL DEFAULT 0, - created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), - updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) -); - --- Create indexes for better performance -CREATE INDEX IF NOT EXISTS idx_testimonials_published ON testimonials(isPublished); -CREATE INDEX IF NOT EXISTS idx_testimonials_sort_order ON testimonials(sortOrder); -CREATE INDEX IF NOT EXISTS idx_testimonials_rating ON testimonials(rating); - --- Create trigger to update updated_at timestamp -CREATE TRIGGER IF NOT EXISTS testimonials_updated_at - AFTER UPDATE ON testimonials -BEGIN - UPDATE testimonials SET updated_at = strftime('%s', 'now') WHERE id = NEW.id; -END; - --- Insert plugin record -INSERT OR IGNORE INTO plugins (name, display_name, description, version, status, category, settings) VALUES -('testimonials', - 'Customer Testimonials', - 'Manage customer testimonials and reviews with rating support. This is a code-based collection example.', - '1.0.0', - 'active', - 'content', - '{"defaultPublished": true, "requireRating": false}'); - --- Insert sample testimonial data -INSERT OR IGNORE INTO testimonials (author_name, author_title, author_company, testimonial_text, rating, isPublished, sortOrder) VALUES -('Jane Smith', - 'CTO', - 'TechStartup Inc', - 'SonicJS AI has transformed how we manage our content. The plugin architecture is brilliant and the edge deployment is blazing fast.', - 5, - 1, - 1), - -('Michael Chen', - 'Lead Developer', - 'Digital Agency Co', - 'We migrated from WordPress to SonicJS AI and couldn''t be happier. The TypeScript-first approach and modern tooling make development a joy.', - 5, - 1, - 2), - -('Sarah Johnson', - 'Product Manager', - 'E-commerce Solutions', - 'The headless CMS approach combined with Cloudflare Workers gives us unmatched performance. Our content is served globally with minimal latency.', - 4, - 1, - 3), - -('David Rodriguez', - 'Full Stack Developer', - 'Creative Studio', - 'Great CMS for modern web applications. The admin interface is clean and the API is well-designed. Plugin system is very flexible.', - 5, - 1, - 4), - -('Emily Watson', - 'Technical Director', - 'Media Company', - 'SonicJS AI solved our content distribution challenges. The R2 integration for media storage works flawlessly and scales effortlessly.', - 4, - 1, - 5); -` - }, - { - id: "013", - name: "Code Examples Plugin", - filename: "013_code_examples_plugin.sql", - description: "Migration 013: Code Examples Plugin", - sql: `-- Code Examples Plugin Migration --- Creates code_examples table for the code examples plugin --- This demonstrates a code-based collection for storing and managing code snippets - -CREATE TABLE IF NOT EXISTS code_examples ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - title TEXT NOT NULL, - description TEXT, - code TEXT NOT NULL, - language TEXT NOT NULL, - category TEXT, - tags TEXT, - isPublished INTEGER NOT NULL DEFAULT 1, - sortOrder INTEGER NOT NULL DEFAULT 0, - created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')), - updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) -); - --- Create indexes for better performance -CREATE INDEX IF NOT EXISTS idx_code_examples_published ON code_examples(isPublished); -CREATE INDEX IF NOT EXISTS idx_code_examples_sort_order ON code_examples(sortOrder); -CREATE INDEX IF NOT EXISTS idx_code_examples_language ON code_examples(language); -CREATE INDEX IF NOT EXISTS idx_code_examples_category ON code_examples(category); - --- Create trigger to update updated_at timestamp -CREATE TRIGGER IF NOT EXISTS code_examples_updated_at - AFTER UPDATE ON code_examples -BEGIN - UPDATE code_examples SET updated_at = strftime('%s', 'now') WHERE id = NEW.id; -END; - --- Insert plugin record -INSERT OR IGNORE INTO plugins (name, display_name, description, version, status, category, settings) VALUES -('code-examples', - 'Code Examples', - 'Manage code snippets and examples with syntax highlighting support. Perfect for documentation and tutorials.', - '1.0.0', - 'active', - 'content', - '{"defaultPublished": true, "supportedLanguages": ["javascript", "typescript", "python", "go", "rust", "java", "php", "ruby", "sql"]}'); - --- Insert sample code examples -INSERT OR IGNORE INTO code_examples (title, description, code, language, category, tags, isPublished, sortOrder) VALUES -('React useState Hook', - 'Basic example of using the useState hook in React for managing component state.', - 'import { useState } from ''react''; - -function Counter() { - const [count, setCount] = useState(0); - - return ( -
-

Count: {count}

- -
- ); -} - -export default Counter;', - 'javascript', - 'frontend', - 'react,hooks,state', - 1, - 1), - -('TypeScript Interface Example', - 'Defining a TypeScript interface for type-safe objects.', - 'interface User { - id: string; - email: string; - name: string; - role: ''admin'' | ''editor'' | ''viewer''; - createdAt: Date; -} - -function greetUser(user: User): string { - return \`Hello, \${user.name}!\`; -} - -const user: User = { - id: ''123'', - email: ''user@example.com'', - name: ''John Doe'', - role: ''admin'', - createdAt: new Date() -}; - -console.log(greetUser(user));', - 'typescript', - 'backend', - 'typescript,types,interface', - 1, - 2), - -('Python List Comprehension', - 'Elegant way to create lists in Python using list comprehensions.', - '# Basic list comprehension -squares = [x**2 for x in range(10)] -print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] - -# With condition -even_squares = [x**2 for x in range(10) if x % 2 == 0] -print(even_squares) # [0, 4, 16, 36, 64] - -# Nested list comprehension -matrix = [[i+j for j in range(3)] for i in range(3)] -print(matrix) # [[0, 1, 2], [1, 2, 3], [2, 3, 4]]', - 'python', - 'general', - 'python,lists,comprehension', - 1, - 3), - -('SQL Join Example', - 'Common SQL JOIN patterns for combining data from multiple tables.', - '-- INNER JOIN: Returns only matching rows -SELECT users.name, orders.total -FROM users -INNER JOIN orders ON users.id = orders.user_id; - --- LEFT JOIN: Returns all users, even without orders -SELECT users.name, orders.total -FROM users -LEFT JOIN orders ON users.id = orders.user_id; - --- Multiple JOINs -SELECT - users.name, - orders.order_date, - products.name AS product_name -FROM users -INNER JOIN orders ON users.id = orders.user_id -INNER JOIN order_items ON orders.id = order_items.order_id -INNER JOIN products ON order_items.product_id = products.id;', - 'sql', - 'database', - 'sql,joins,queries', - 1, - 4), - -('Go Error Handling', - 'Idiomatic error handling pattern in Go.', - 'package main - -import ( - "errors" - "fmt" -) - -func divide(a, b float64) (float64, error) { - if b == 0 { - return 0, errors.New("division by zero") - } - return a / b, nil -} - -func main() { - result, err := divide(10, 2) - if err != nil { - fmt.Println("Error:", err) - return - } - fmt.Printf("Result: %.2f\\n", result) - - // This will error - _, err = divide(10, 0) - if err != nil { - fmt.Println("Error:", err) - } -}', - 'go', - 'backend', - 'go,error-handling,functions', - 1, - 5); -` - }, - { - id: "014", - name: "Fix Plugin Registry", - filename: "014_fix_plugin_registry.sql", - description: "Migration 014: Fix Plugin Registry", - sql: `-- Fix Plugin Registry --- Migration: 014_fix_plugin_registry --- Description: Add missing plugins and fix plugin name mismatches - --- Note: Cannot easily update plugin names as they may be referenced elsewhere --- Instead we'll add the missing plugins with correct names - --- Insert missing plugins - --- Core Analytics Plugin -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, installed_at, last_updated -) VALUES ( - 'core-analytics', - 'core-analytics', - 'Analytics & Tracking', - 'Core analytics tracking and reporting plugin with page views and event tracking', - '1.0.0', - 'SonicJS Team', - 'seo', - '\u{1F4CA}', - 'active', - TRUE, - '["view:analytics", "manage:tracking"]', - unixepoch(), - unixepoch() -); - --- FAQ Plugin -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, installed_at, last_updated -) VALUES ( - 'faq-plugin', - 'faq-plugin', - 'FAQ Management', - 'Frequently Asked Questions management plugin with categories, search, and custom styling', - '1.0.0', - 'SonicJS', - 'content', - '\u2753', - 'active', - FALSE, - '["manage:faqs"]', - unixepoch(), - unixepoch() -); - --- Seed Data Plugin -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, installed_at, last_updated -) VALUES ( - 'seed-data', - 'seed-data', - 'Seed Data Generator', - 'Generate realistic example users and content for testing and development', - '1.0.0', - 'SonicJS Team', - 'development', - '\u{1F331}', - 'inactive', - FALSE, - '["admin"]', - unixepoch(), - unixepoch() -); - --- Database Tools Plugin -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, installed_at, last_updated -) VALUES ( - 'database-tools', - 'database-tools', - 'Database Tools', - 'Database management tools including truncate, backup, and validation', - '1.0.0', - 'SonicJS Team', - 'system', - '\u{1F5C4}\uFE0F', - 'active', - FALSE, - '["manage:database", "admin"]', - unixepoch(), - unixepoch() -); -` - }, - { - id: "015", - name: "Add Remaining Plugins", - filename: "015_add_remaining_plugins.sql", - description: "Migration 015: Add Remaining Plugins", - sql: `-- Add Remaining Plugins --- Migration: 015_add_remaining_plugins --- Description: Add all remaining core plugins that were missing from the registry - --- Testimonials Plugin (with correct name) -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, dependencies, settings, installed_at, last_updated -) VALUES ( - 'testimonials-plugin', - 'testimonials-plugin', - 'Customer Testimonials', - 'Manage customer testimonials and reviews with rating support', - '1.0.0', - 'SonicJS', - 'content', - '\u2B50', - 'active', - FALSE, - '["manage:testimonials"]', - '[]', - '{"defaultPublished": true, "requireRating": false}', - unixepoch(), - unixepoch() -); - --- Code Examples Plugin (with correct name) -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, dependencies, settings, installed_at, last_updated -) VALUES ( - 'code-examples-plugin', - 'code-examples-plugin', - 'Code Examples', - 'Manage code snippets and examples with syntax highlighting support', - '1.0.0', - 'SonicJS', - 'content', - '\u{1F4BB}', - 'active', - FALSE, - '["manage:code-examples"]', - '[]', - '{"defaultPublished": true, "supportedLanguages": ["javascript", "typescript", "python", "go", "rust", "java", "php", "ruby", "sql"]}', - unixepoch(), - unixepoch() -); - --- Workflow Plugin (with correct name) -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, dependencies, installed_at, last_updated -) VALUES ( - 'workflow-plugin', - 'workflow-plugin', - 'Workflow Engine', - 'Content workflow management with approval chains, scheduling, and automation', - '1.0.0', - 'SonicJS Team', - 'content', - '\u{1F504}', - 'active', - TRUE, - '["manage:workflows", "approve:content"]', - '[]', - unixepoch(), - unixepoch() -); - --- Demo Login Plugin (already exists with correct name from migration 007, but let's ensure it's there) -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, dependencies, installed_at, last_updated -) VALUES ( - 'demo-login-plugin', - 'demo-login-plugin', - 'Demo Login Prefill', - 'Prefills login form with demo credentials for easy site demonstration', - '1.0.0', - 'SonicJS', - 'demo', - '\u{1F3AF}', - 'active', - FALSE, - '[]', - '[]', - unixepoch(), - unixepoch() -); -` - }, - { - id: "016", - name: "Remove Duplicate Cache Plugin", - filename: "016_remove_duplicate_cache_plugin.sql", - description: "Migration 016: Remove Duplicate Cache Plugin", - sql: "-- Migration: Remove duplicate cache plugin entry\n-- Description: Removes the old 'cache' plugin (id: 'cache') that is a duplicate of 'core-cache'\n-- This fixes the issue where Cache System appears twice in the plugins list\n-- Created: 2025-10-14\n\n-- Remove the old 'cache' plugin entry if it exists\n-- The correct plugin is 'core-cache' which is managed by plugin-bootstrap.ts\nDELETE FROM plugins WHERE id = 'cache' AND name = 'cache';\n\n-- Clean up any related entries in plugin activity log\nDELETE FROM plugin_activity_log WHERE plugin_id = 'cache';\n\n-- Clean up any related entries in plugin hooks\nDELETE FROM plugin_hooks WHERE plugin_id = 'cache';\n\n-- Clean up any related entries in plugin routes\nDELETE FROM plugin_routes WHERE plugin_id = 'cache';\n" - }, - { - id: "017", - name: "Auth Configurable Fields", - filename: "017_auth_configurable_fields.sql", - description: "Migration 017: Auth Configurable Fields", - sql: `-- Migration: Make authentication fields configurable --- This migration updates the core-auth plugin to support configurable required fields - --- The settings will be stored in the plugins table as JSON --- Default settings for core-auth plugin include: --- { --- "requiredFields": { --- "email": { "required": true, "minLength": 5 }, --- "password": { "required": true, "minLength": 8 }, --- "username": { "required": true, "minLength": 3 }, --- "firstName": { "required": true, "minLength": 1 }, --- "lastName": { "required": true, "minLength": 1 } --- }, --- "validation": { --- "emailFormat": true, --- "allowDuplicateUsernames": false --- } --- } - --- Update core-auth plugin settings with configurable field requirements -UPDATE plugins -SET settings = json_object( - 'requiredFields', json_object( - 'email', json_object('required', 1, 'minLength', 5, 'label', 'Email', 'type', 'email'), - 'password', json_object('required', 1, 'minLength', 8, 'label', 'Password', 'type', 'password'), - 'username', json_object('required', 1, 'minLength', 3, 'label', 'Username', 'type', 'text'), - 'firstName', json_object('required', 1, 'minLength', 1, 'label', 'First Name', 'type', 'text'), - 'lastName', json_object('required', 1, 'minLength', 1, 'label', 'Last Name', 'type', 'text') - ), - 'validation', json_object( - 'emailFormat', 1, - 'allowDuplicateUsernames', 0, - 'passwordRequirements', json_object( - 'requireUppercase', 0, - 'requireLowercase', 0, - 'requireNumbers', 0, - 'requireSpecialChars', 0 - ) - ), - 'registration', json_object( - 'enabled', 1, - 'requireEmailVerification', 0, - 'defaultRole', 'viewer' - ) -) -WHERE id = 'core-auth'; - --- If core-auth plugin doesn't exist, this migration will be handled by bootstrap --- No need to insert here as plugin bootstrap handles initial plugin creation -` - }, - { - id: "018", - name: "Settings Table", - filename: "018_settings_table.sql", - description: "Migration 018: Settings Table", - sql: `-- Create settings table for storing application settings -CREATE TABLE IF NOT EXISTS settings ( - id TEXT PRIMARY KEY, - category TEXT NOT NULL, -- 'general', 'appearance', 'security', etc. - key TEXT NOT NULL, - value TEXT NOT NULL, -- JSON value - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL, - UNIQUE(category, key) -); - --- Insert default general settings -INSERT OR IGNORE INTO settings (id, category, key, value, created_at, updated_at) -VALUES - (lower(hex(randomblob(16))), 'general', 'siteName', '"SonicJS AI"', unixepoch() * 1000, unixepoch() * 1000), - (lower(hex(randomblob(16))), 'general', 'siteDescription', '"A modern headless CMS powered by AI"', unixepoch() * 1000, unixepoch() * 1000), - (lower(hex(randomblob(16))), 'general', 'timezone', '"UTC"', unixepoch() * 1000, unixepoch() * 1000), - (lower(hex(randomblob(16))), 'general', 'language', '"en"', unixepoch() * 1000, unixepoch() * 1000), - (lower(hex(randomblob(16))), 'general', 'maintenanceMode', 'false', unixepoch() * 1000, unixepoch() * 1000); - --- Create index for faster lookups -CREATE INDEX IF NOT EXISTS idx_settings_category ON settings(category); -CREATE INDEX IF NOT EXISTS idx_settings_category_key ON settings(category, key); -` - }, - { - id: "019", - name: "Remove Blog Posts Collection", - filename: "019_remove_blog_posts_collection.sql", - description: "Migration 019: Remove Blog Posts Collection", - sql: "-- Migration: Remove blog_posts from database-managed collections\n-- Description: Remove blog-posts-collection from the database so it can be managed by code-based collection\n-- Created: 2025-11-04\n\n-- Delete content associated with blog-posts-collection\nDELETE FROM content WHERE collection_id = 'blog-posts-collection';\n\n-- Delete content fields for blog-posts-collection\nDELETE FROM content_fields WHERE collection_id = 'blog-posts-collection';\n\n-- Delete the blog-posts collection itself\nDELETE FROM collections WHERE id = 'blog-posts-collection';\n\n-- The blog-posts collection will now be managed by the code-based collection\n-- in src/collections/blog-posts.collection.ts\n" - }, - { - id: "020", - name: "Add Email Plugin", - filename: "020_add_email_plugin.sql", - description: "Migration 020: Add Email Plugin", - sql: `-- Add Email Plugin --- Migration: 020_add_email_plugin --- Description: Add email plugin for transactional emails via Resend - -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, installed_at, last_updated -) VALUES ( - 'email', - 'email', - 'Email', - 'Send transactional emails using Resend', - '1.0.0-beta.1', - 'SonicJS Team', - 'utilities', - '\u{1F4E7}', - 'inactive', - TRUE, - '["email:manage", "email:send", "email:view-logs"]', - unixepoch(), - unixepoch() -); -` - }, - { - id: "021", - name: "Add Magic Link Auth Plugin", - filename: "021_add_magic_link_auth_plugin.sql", - description: "Migration 021: Add Magic Link Auth Plugin", - sql: `-- Add Magic Link Authentication Plugin --- Migration: 021_add_magic_link_auth_plugin --- Description: Add magic link authentication plugin for passwordless login - --- Create magic_links table -CREATE TABLE IF NOT EXISTS magic_links ( - id TEXT PRIMARY KEY, - user_email TEXT NOT NULL, - token TEXT NOT NULL UNIQUE, - expires_at INTEGER NOT NULL, - used INTEGER DEFAULT 0, - used_at INTEGER, - ip_address TEXT, - user_agent TEXT, - created_at INTEGER NOT NULL -); - --- Create indexes for performance -CREATE INDEX IF NOT EXISTS idx_magic_links_token ON magic_links(token); -CREATE INDEX IF NOT EXISTS idx_magic_links_email ON magic_links(user_email); -CREATE INDEX IF NOT EXISTS idx_magic_links_expires ON magic_links(expires_at); - --- Register the plugin -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, dependencies, installed_at, last_updated -) VALUES ( - 'magic-link-auth', - 'magic-link-auth', - 'Magic Link Authentication', - 'Passwordless authentication via email magic links. Users receive a secure one-time link to sign in without entering a password.', - '1.0.0', - 'SonicJS Team', - 'security', - '\u{1F517}', - 'inactive', - FALSE, - '["auth:manage", "auth:magic-link"]', - '["email"]', - unixepoch(), - unixepoch() -); -` - }, - { - id: "022", - name: "Add Tinymce Plugin", - filename: "022_add_tinymce_plugin.sql", - description: "Migration 022: Add Tinymce Plugin", - sql: `-- Add TinyMCE Rich Text Editor Plugin --- Migration: 022_add_tinymce_plugin --- Description: Add TinyMCE plugin for WYSIWYG rich text editing - --- Register the plugin (active by default since it replaces hardcoded TinyMCE) -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, dependencies, settings, installed_at, last_updated -) VALUES ( - 'tinymce-plugin', - 'tinymce-plugin', - 'TinyMCE Rich Text Editor', - 'Powerful WYSIWYG rich text editor for content creation. Provides a full-featured editor with formatting, media embedding, and customizable toolbars for richtext fields.', - '1.0.0', - 'SonicJS Team', - 'editor', - '\u270F\uFE0F', - 'active', - FALSE, - '[]', - '[]', - '{"apiKey":"no-api-key","defaultHeight":300,"defaultToolbar":"full","skin":"oxide-dark"}', - unixepoch(), - unixepoch() -); -` - }, - { - id: "023", - name: "Add Easy Mdx Plugin", - filename: "023_add_easy_mdx_plugin.sql", - description: "Migration 023: Add Easy Mdx Plugin", - sql: `-- Add EasyMDE Markdown Editor Plugin --- Migration: 023_add_easy_mdx_plugin --- Description: Add EasyMDE plugin for lightweight markdown editing - --- Register the plugin (active by default) -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, dependencies, settings, installed_at, last_updated -) VALUES ( - 'easy-mdx', - 'easy-mdx', - 'EasyMDE Markdown Editor', - 'Lightweight markdown editor with live preview. Provides a simple and efficient editor with markdown support for richtext fields.', - '1.0.0', - 'SonicJS Team', - 'editor', - '\u{1F4DD}', - 'active', - FALSE, - '[]', - '[]', - '{"defaultHeight":400,"theme":"dark","toolbar":"full","placeholder":"Start writing your content..."}', - unixepoch(), - unixepoch() -); -` - }, - { - id: "024", - name: "Add Quill Editor Plugin", - filename: "024_add_quill_editor_plugin.sql", - description: "Migration 024: Add Quill Editor Plugin", - sql: `-- Add Quill Rich Text Editor Plugin --- Migration: 024_add_quill_editor_plugin --- Description: Add Quill plugin for modern rich text editing - --- Register the plugin (active by default) -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, dependencies, settings, installed_at, last_updated -) VALUES ( - 'quill-editor', - 'quill-editor', - 'Quill Rich Text Editor', - 'Modern rich text editor for content creation. Provides a clean, intuitive WYSIWYG editor with customizable toolbars for richtext fields.', - '1.0.0', - 'SonicJS Team', - 'editor', - '\u270D\uFE0F', - 'active', - FALSE, - '[]', - '[]', - '{"theme":"snow","defaultHeight":300,"defaultToolbar":"full","placeholder":"Start writing your content..."}', - unixepoch(), - unixepoch() -); -` - }, - { - id: "025", - name: "Add Easymde Plugin", - filename: "025_add_easymde_plugin.sql", - description: "Migration 025: Add Easymde Plugin", - sql: `-- Add EasyMDE Rich Text Editor Plugin --- Migration: 025_add_easymde_plugin --- Description: Add EasyMDE plugin for markdown-based rich text editing - --- Register the plugin (inactive by default, replacing MDXEditor) -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, dependencies, settings, installed_at, last_updated -) VALUES ( - 'easymde-editor', - 'easymde-editor', - 'EasyMDE Editor', - 'Lightweight markdown editor for content creation. Simple, elegant WYSIWYG markdown editor with live preview, toolbar, and dark mode support for richtext fields.', - '1.0.0', - 'SonicJS Team', - 'editor', - '\u270D\uFE0F', - 'inactive', - TRUE, - '[]', - '[]', - '{"theme":"dark","defaultHeight":300,"toolbar":"full","spellChecker":false,"placeholder":"Start writing your content..."}', - unixepoch(), - unixepoch() -); -` - }, - { - id: "026", - name: "Add Otp Login", - filename: "026_add_otp_login.sql", - description: "Migration 026: Add Otp Login", - sql: `-- Add OTP Login Plugin --- Migration: 021_add_otp_login --- Description: Add OTP login plugin for passwordless authentication via email codes - --- Create table for OTP codes -CREATE TABLE IF NOT EXISTS otp_codes ( - id TEXT PRIMARY KEY, - user_email TEXT NOT NULL, - code TEXT NOT NULL, - expires_at INTEGER NOT NULL, - used INTEGER DEFAULT 0, - used_at INTEGER, - ip_address TEXT, - user_agent TEXT, - attempts INTEGER DEFAULT 0, - created_at INTEGER NOT NULL -); - --- Create indexes for performance -CREATE INDEX IF NOT EXISTS idx_otp_email_code ON otp_codes(user_email, code); -CREATE INDEX IF NOT EXISTS idx_otp_expires ON otp_codes(expires_at); -CREATE INDEX IF NOT EXISTS idx_otp_used ON otp_codes(used); - --- Add plugin record -INSERT OR IGNORE INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, permissions, installed_at, last_updated -) VALUES ( - 'otp-login', - 'otp-login', - 'OTP Login', - 'Passwordless authentication via email one-time codes', - '1.0.0-beta.1', - 'SonicJS Team', - 'security', - '\u{1F522}', - 'inactive', - TRUE, - '["otp:manage", "otp:request", "otp:verify"]', - unixepoch(), - unixepoch() -); -` - }, - { - id: "027", - name: "Fix Slug Field Type", - filename: "027_fix_slug_field_type.sql", - description: "Migration 027: Fix Slug Field Type", - sql: "-- Migration: Fix slug field type\n-- Description: Update slug fields to use 'slug' field type instead of 'text' for proper auto-generation\n-- Created: 2026-01-10\n\n-- Update pages collection slug field to use 'slug' field type\nUPDATE content_fields \nSET field_type = 'slug'\nWHERE field_name = 'slug' AND collection_id = 'pages-collection';\n\n-- Update blog posts slug field if it exists\nUPDATE content_fields \nSET field_type = 'slug'\nWHERE field_name = 'slug' AND collection_id = 'blog-posts-collection';\n\n-- Update news slug field if it exists\nUPDATE content_fields \nSET field_type = 'slug'\nWHERE field_name = 'slug' AND collection_id = 'news-collection';\n" - }, - { - id: "028", - name: "Fix Slug Field Type In Schemas", - filename: "028_fix_slug_field_type_in_schemas.sql", - description: "Migration 028: Fix Slug Field Type In Schemas", - sql: `-- Migration: Fix slug field type in collection schemas --- Description: Update slug fields in collection schemas to use 'slug' type instead of 'string' --- Created: 2026-01-10 - --- Update pages-collection schema -UPDATE collections -SET schema = REPLACE( - schema, - '"slug":{"type":"string"', - '"slug":{"type":"slug"' -) -WHERE id = 'pages-collection' AND schema LIKE '%"slug":{"type":"string"%'; - --- Update blog-posts-collection schema if it exists -UPDATE collections -SET schema = REPLACE( - schema, - '"slug":{"type":"string"', - '"slug":{"type":"slug"' -) -WHERE id = 'blog-posts-collection' AND schema LIKE '%"slug":{"type":"string"%'; - --- Update news-collection schema if it exists -UPDATE collections -SET schema = REPLACE( - schema, - '"slug":{"type":"string"', - '"slug":{"type":"slug"' -) -WHERE id = 'news-collection' AND schema LIKE '%"slug":{"type":"string"%'; -` - }, - { - id: "029", - name: "Add Forms System", - filename: "029_add_forms_system.sql", - description: "Migration 029: Add Forms System", - sql: `-- Migration: 029_add_forms_system.sql --- Description: Add Form.io integration for advanced form building --- Date: January 23, 2026 --- Phase: 1 - Database Schema - --- ===================================================== --- Table: forms --- Description: Stores form definitions and configuration --- ===================================================== - -CREATE TABLE IF NOT EXISTS forms ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL UNIQUE, -- Machine name (e.g., "contact-form") - display_name TEXT NOT NULL, -- Human name (e.g., "Contact Form") - description TEXT, -- Optional description - category TEXT DEFAULT 'general', -- Form category (contact, survey, registration, etc.) - - -- Form.io schema (JSON) - formio_schema TEXT NOT NULL, -- Complete Form.io JSON schema - - -- Settings - settings TEXT, -- JSON: { - -- emailNotifications: true, - -- notifyEmail: "admin@example.com", - -- successMessage: "Thank you!", - -- redirectUrl: "/thank-you", - -- allowAnonymous: true, - -- requireAuth: false, - -- maxSubmissions: null, - -- submitButtonText: "Submit", - -- saveProgress: true, - -- webhookUrl: null - -- } - - -- Status & Management - is_active INTEGER DEFAULT 1, -- Active/inactive flag - is_public INTEGER DEFAULT 1, -- Public (anyone) vs private (auth required) - managed INTEGER DEFAULT 0, -- Code-managed (like collections) - - -- Metadata - icon TEXT, -- Optional icon for admin UI - color TEXT, -- Optional color (hex) for admin UI - tags TEXT, -- JSON array of tags - - -- Stats - submission_count INTEGER DEFAULT 0, -- Total submissions received - view_count INTEGER DEFAULT 0, -- Form views (optional tracking) - - -- Ownership - created_by TEXT REFERENCES users(id), -- User who created the form - updated_by TEXT REFERENCES users(id), -- User who last updated - - -- Timestamps - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL -); - --- Indexes for forms -CREATE INDEX IF NOT EXISTS idx_forms_name ON forms(name); -CREATE INDEX IF NOT EXISTS idx_forms_category ON forms(category); -CREATE INDEX IF NOT EXISTS idx_forms_active ON forms(is_active); -CREATE INDEX IF NOT EXISTS idx_forms_public ON forms(is_public); -CREATE INDEX IF NOT EXISTS idx_forms_created_by ON forms(created_by); - --- ===================================================== --- Table: form_submissions --- Description: Stores submitted form data --- ===================================================== - -CREATE TABLE IF NOT EXISTS form_submissions ( - id TEXT PRIMARY KEY, - form_id TEXT NOT NULL REFERENCES forms(id) ON DELETE CASCADE, - - -- Submission data - submission_data TEXT NOT NULL, -- JSON: The actual form data submitted - - -- Submission metadata - status TEXT DEFAULT 'pending', -- pending, reviewed, approved, rejected, spam - submission_number INTEGER, -- Sequential number per form - - -- User information (if authenticated) - user_id TEXT REFERENCES users(id), -- Submitter user ID (if logged in) - user_email TEXT, -- Email from form (or user account) - - -- Tracking information - ip_address TEXT, -- IP address of submitter - user_agent TEXT, -- Browser user agent - referrer TEXT, -- Page that referred to form - utm_source TEXT, -- UTM tracking params - utm_medium TEXT, - utm_campaign TEXT, - - -- Review/Processing - reviewed_by TEXT REFERENCES users(id), -- Admin who reviewed - reviewed_at INTEGER, -- Review timestamp - review_notes TEXT, -- Admin notes - - -- Flags - is_spam INTEGER DEFAULT 0, -- Spam flag - is_archived INTEGER DEFAULT 0, -- Archived flag - - -- Timestamps - submitted_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL -); - --- Indexes for submissions -CREATE INDEX IF NOT EXISTS idx_form_submissions_form_id ON form_submissions(form_id); -CREATE INDEX IF NOT EXISTS idx_form_submissions_status ON form_submissions(status); -CREATE INDEX IF NOT EXISTS idx_form_submissions_user_id ON form_submissions(user_id); -CREATE INDEX IF NOT EXISTS idx_form_submissions_email ON form_submissions(user_email); -CREATE INDEX IF NOT EXISTS idx_form_submissions_submitted_at ON form_submissions(submitted_at); -CREATE INDEX IF NOT EXISTS idx_form_submissions_spam ON form_submissions(is_spam); - --- Trigger to auto-increment submission_number per form -CREATE TRIGGER IF NOT EXISTS set_submission_number -AFTER INSERT ON form_submissions -BEGIN - UPDATE form_submissions - SET submission_number = ( - SELECT COUNT(*) - FROM form_submissions - WHERE form_id = NEW.form_id - AND id <= NEW.id - ) - WHERE id = NEW.id; -END; - --- Trigger to update form submission_count -CREATE TRIGGER IF NOT EXISTS increment_form_submission_count -AFTER INSERT ON form_submissions -BEGIN - UPDATE forms - SET submission_count = submission_count + 1, - updated_at = unixepoch() * 1000 - WHERE id = NEW.form_id; -END; - --- ===================================================== --- Table: form_files (Optional) --- Description: Link form submissions to uploaded files --- ===================================================== - -CREATE TABLE IF NOT EXISTS form_files ( - id TEXT PRIMARY KEY, - submission_id TEXT NOT NULL REFERENCES form_submissions(id) ON DELETE CASCADE, - media_id TEXT NOT NULL REFERENCES media(id) ON DELETE CASCADE, - field_name TEXT NOT NULL, -- Form field that uploaded this file - uploaded_at INTEGER NOT NULL -); - --- Indexes for form files -CREATE INDEX IF NOT EXISTS idx_form_files_submission ON form_files(submission_id); -CREATE INDEX IF NOT EXISTS idx_form_files_media ON form_files(media_id); - --- ===================================================== --- Sample Data: Create a default contact form --- ===================================================== - -INSERT OR IGNORE INTO forms ( - id, - name, - display_name, - description, - category, - formio_schema, - settings, - is_active, - is_public, - created_at, - updated_at -) VALUES ( - 'default-contact-form', - 'contact', - 'Contact Form', - 'A simple contact form for getting in touch', - 'contact', - '{"components":[]}', - '{"emailNotifications":false,"successMessage":"Thank you for your submission!","submitButtonText":"Submit","requireAuth":false}', - 1, - 1, - unixepoch() * 1000, - unixepoch() * 1000 -); -` - }, - { - id: "030", - name: "Add Turnstile To Forms", - filename: "030_add_turnstile_to_forms.sql", - description: "Migration 030: Add Turnstile To Forms", - sql: `-- Add Turnstile configuration to forms table --- This allows per-form Turnstile settings with global fallback - --- Add columns (D1 may not support CHECK constraints in ALTER TABLE) -ALTER TABLE forms ADD COLUMN turnstile_enabled INTEGER DEFAULT 0; -ALTER TABLE forms ADD COLUMN turnstile_settings TEXT; - --- Set default to inherit global settings for existing forms -UPDATE forms -SET turnstile_settings = '{"inherit":true}' -WHERE turnstile_settings IS NULL; - --- Add index for faster lookups -CREATE INDEX IF NOT EXISTS idx_forms_turnstile ON forms(turnstile_enabled); -` - }, - { - id: "031", - name: "Ai Search Plugin", - filename: "031_ai_search_plugin.sql", - description: "Migration 031: Ai Search Plugin", - sql: "-- AI Search plugin settings\nCREATE TABLE IF NOT EXISTS ai_search_settings (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n enabled BOOLEAN DEFAULT 0,\n ai_mode_enabled BOOLEAN DEFAULT 1,\n selected_collections TEXT, -- JSON array of collection IDs to index\n dismissed_collections TEXT, -- JSON array of collection IDs user chose not to index\n autocomplete_enabled BOOLEAN DEFAULT 1,\n cache_duration INTEGER DEFAULT 1, -- hours\n results_limit INTEGER DEFAULT 20,\n index_media BOOLEAN DEFAULT 0,\n index_status TEXT, -- JSON object with status per collection\n last_indexed_at INTEGER,\n created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),\n updated_at INTEGER DEFAULT (strftime('%s', 'now') * 1000)\n);\n\n-- Search history/analytics\nCREATE TABLE IF NOT EXISTS ai_search_history (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n query TEXT NOT NULL,\n mode TEXT, -- 'ai' or 'keyword'\n results_count INTEGER,\n user_id INTEGER,\n created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000)\n);\n\n-- Index metadata tracking (per collection)\nCREATE TABLE IF NOT EXISTS ai_search_index_meta (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n collection_id INTEGER NOT NULL,\n collection_name TEXT NOT NULL, -- Cache collection name for display\n total_items INTEGER DEFAULT 0,\n indexed_items INTEGER DEFAULT 0,\n last_sync_at INTEGER,\n status TEXT DEFAULT 'pending', -- 'pending', 'indexing', 'completed', 'error'\n error_message TEXT,\n UNIQUE(collection_id)\n);\n\n-- Indexes for performance\nCREATE INDEX IF NOT EXISTS idx_ai_search_history_created_at ON ai_search_history(created_at);\nCREATE INDEX IF NOT EXISTS idx_ai_search_history_mode ON ai_search_history(mode);\nCREATE INDEX IF NOT EXISTS idx_ai_search_index_meta_collection_id ON ai_search_index_meta(collection_id);\nCREATE INDEX IF NOT EXISTS idx_ai_search_index_meta_status ON ai_search_index_meta(status);\n" - } -]; -var migrationsByIdMap = new Map( - bundledMigrations.map((m) => [m.id, m]) -); -function getMigrationSQLById(id) { - return migrationsByIdMap.get(id)?.sql ?? null; -} - -// src/services/migrations.ts -var MigrationService = class { - constructor(db) { - this.db = db; - } - /** - * Initialize the migrations tracking table - */ - async initializeMigrationsTable() { - const createTableQuery = ` - CREATE TABLE IF NOT EXISTS migrations ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - filename TEXT NOT NULL, - applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - checksum TEXT - ) - `; - await this.db.prepare(createTableQuery).run(); - } - /** - * Get all available migrations from the bundled migrations - */ - async getAvailableMigrations() { - const migrations = []; - const appliedResult = await this.db.prepare( - "SELECT id, name, filename, applied_at FROM migrations ORDER BY applied_at ASC" - ).all(); - const appliedMigrations = new Map( - appliedResult.results?.map((row) => [row.id, row]) || [] - ); - await this.autoDetectAppliedMigrations(appliedMigrations); - for (const bundled of bundledMigrations) { - const applied = appliedMigrations.has(bundled.id); - const appliedData = appliedMigrations.get(bundled.id); - migrations.push({ - id: bundled.id, - name: bundled.name, - filename: bundled.filename, - description: bundled.description, - applied, - appliedAt: applied ? appliedData?.applied_at : void 0, - size: bundled.sql.length - }); - } - return migrations; - } - /** - * Auto-detect applied migrations by checking if their tables exist - */ - async autoDetectAppliedMigrations(appliedMigrations) { - if (!appliedMigrations.has("001")) { - const hasBasicTables = await this.checkTablesExist(["users", "content", "collections", "media"]); - if (hasBasicTables) { - appliedMigrations.set("001", { - id: "001", - applied_at: (/* @__PURE__ */ new Date()).toISOString(), - name: "Initial Schema", - filename: "001_initial_schema.sql" - }); - await this.markMigrationApplied("001", "Initial Schema", "001_initial_schema.sql"); - } - } - if (!appliedMigrations.has("002")) { - const hasFaqTables = await this.checkTablesExist(["faqs"]); - if (hasFaqTables) { - appliedMigrations.set("002", { - id: "002", - applied_at: (/* @__PURE__ */ new Date()).toISOString(), - name: "Faq Plugin", - filename: "002_faq_plugin.sql" - }); - await this.markMigrationApplied("002", "Faq Plugin", "002_faq_plugin.sql"); - } - } - if (!appliedMigrations.has("003")) { - const hasStage5Tables = await this.checkTablesExist(["content_fields", "content_relationships", "workflow_templates"]); - if (hasStage5Tables) { - appliedMigrations.set("003", { - id: "003", - applied_at: (/* @__PURE__ */ new Date()).toISOString(), - name: "Stage 5 Enhancements", - filename: "003_stage5_enhancements.sql" - }); - await this.markMigrationApplied("003", "Stage 5 Enhancements", "003_stage5_enhancements.sql"); - } - } - if (!appliedMigrations.has("012")) { - const hasTestimonialsTables = await this.checkTablesExist(["testimonials"]); - if (hasTestimonialsTables) { - appliedMigrations.set("012", { - id: "012", - applied_at: (/* @__PURE__ */ new Date()).toISOString(), - name: "Testimonials Plugin", - filename: "012_testimonials_plugin.sql" - }); - await this.markMigrationApplied("012", "Testimonials Plugin", "012_testimonials_plugin.sql"); - } - } - if (!appliedMigrations.has("013")) { - const hasCodeExamplesTables = await this.checkTablesExist(["code_examples"]); - if (hasCodeExamplesTables) { - appliedMigrations.set("013", { - id: "013", - applied_at: (/* @__PURE__ */ new Date()).toISOString(), - name: "Code Examples Plugin", - filename: "013_code_examples_plugin.sql" - }); - await this.markMigrationApplied("013", "Code Examples Plugin", "013_code_examples_plugin.sql"); - } - } - if (!appliedMigrations.has("004")) { - const hasUserTables = await this.checkTablesExist(["api_tokens", "workflow_history"]); - if (hasUserTables) { - appliedMigrations.set("004", { - id: "004", - applied_at: (/* @__PURE__ */ new Date()).toISOString(), - name: "User Management", - filename: "004_stage6_user_management.sql" - }); - await this.markMigrationApplied("004", "User Management", "004_stage6_user_management.sql"); - } - } - if (!appliedMigrations.has("006")) { - const hasPluginTables = await this.checkTablesExist(["plugins", "plugin_hooks"]); - if (hasPluginTables) { - appliedMigrations.set("006", { - id: "006", - applied_at: (/* @__PURE__ */ new Date()).toISOString(), - name: "Plugin System", - filename: "006_plugin_system.sql" - }); - await this.markMigrationApplied("006", "Plugin System", "006_plugin_system.sql"); - } - } - const hasManagedColumn = await this.checkColumnExists("collections", "managed"); - if (!appliedMigrations.has("011") && hasManagedColumn) { - appliedMigrations.set("011", { - id: "011", - applied_at: (/* @__PURE__ */ new Date()).toISOString(), - name: "Config Managed Collections", - filename: "011_config_managed_collections.sql" - }); - await this.markMigrationApplied("011", "Config Managed Collections", "011_config_managed_collections.sql"); - } else if (appliedMigrations.has("011") && !hasManagedColumn) { - console.log("[Migration] Migration 011 marked as applied but managed column missing - will re-run"); - appliedMigrations.delete("011"); - await this.removeMigrationApplied("011"); - } - if (!appliedMigrations.has("009")) { - const hasLoggingTables = await this.checkTablesExist(["system_logs", "log_config"]); - if (hasLoggingTables) { - appliedMigrations.set("009", { - id: "009", - applied_at: (/* @__PURE__ */ new Date()).toISOString(), - name: "System Logging", - filename: "009_system_logging.sql" - }); - await this.markMigrationApplied("009", "System Logging", "009_system_logging.sql"); - } - } - if (!appliedMigrations.has("018")) { - const hasSettingsTable = await this.checkTablesExist(["settings"]); - if (hasSettingsTable) { - appliedMigrations.set("018", { - id: "018", - applied_at: (/* @__PURE__ */ new Date()).toISOString(), - name: "Settings Table", - filename: "018_settings_table.sql" - }); - await this.markMigrationApplied("018", "Settings Table", "018_settings_table.sql"); - } - } - } - /** - * Check if specific tables exist in the database - */ - async checkTablesExist(tableNames) { - try { - for (const tableName of tableNames) { - const result = await this.db.prepare( - `SELECT name FROM sqlite_master WHERE type='table' AND name=?` - ).bind(tableName).first(); - if (!result) { - return false; - } - } - return true; - } catch (error) { - return false; - } - } - /** - * Check if a specific column exists in a table - */ - async checkColumnExists(tableName, columnName) { - try { - const result = await this.db.prepare( - `SELECT * FROM pragma_table_info(?) WHERE name = ?` - ).bind(tableName, columnName).first(); - return !!result; - } catch (error) { - return false; - } - } - /** - * Get migration status summary - */ - async getMigrationStatus() { - await this.initializeMigrationsTable(); - const migrations = await this.getAvailableMigrations(); - const appliedMigrations = migrations.filter((m) => m.applied); - const pendingMigrations = migrations.filter((m) => !m.applied); - const lastApplied = appliedMigrations.length > 0 ? appliedMigrations[appliedMigrations.length - 1]?.appliedAt : void 0; - return { - totalMigrations: migrations.length, - appliedMigrations: appliedMigrations.length, - pendingMigrations: pendingMigrations.length, - lastApplied, - migrations - }; - } - /** - * Mark a migration as applied - */ - async markMigrationApplied(migrationId, name, filename) { - await this.initializeMigrationsTable(); - await this.db.prepare( - "INSERT OR REPLACE INTO migrations (id, name, filename, applied_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)" - ).bind(migrationId, name, filename).run(); - } - /** - * Remove a migration from the applied list (so it can be re-run) - */ - async removeMigrationApplied(migrationId) { - await this.initializeMigrationsTable(); - await this.db.prepare( - "DELETE FROM migrations WHERE id = ?" - ).bind(migrationId).run(); - } - /** - * Check if a specific migration has been applied - */ - async isMigrationApplied(migrationId) { - await this.initializeMigrationsTable(); - const result = await this.db.prepare( - "SELECT COUNT(*) as count FROM migrations WHERE id = ?" - ).bind(migrationId).first(); - return result?.count > 0; - } - /** - * Get the last applied migration - */ - async getLastAppliedMigration() { - await this.initializeMigrationsTable(); - const result = await this.db.prepare( - "SELECT id, name, filename, applied_at FROM migrations ORDER BY applied_at DESC LIMIT 1" - ).first(); - if (!result) return null; - return { - id: result.id, - name: result.name, - filename: result.filename, - applied: true, - appliedAt: result.applied_at - }; - } - /** - * Run pending migrations - */ - async runPendingMigrations() { - await this.initializeMigrationsTable(); - const status = await this.getMigrationStatus(); - const pendingMigrations = status.migrations.filter((m) => !m.applied); - if (pendingMigrations.length === 0) { - return { - success: true, - message: "All migrations are up to date", - applied: [] - }; - } - const applied = []; - const errors = []; - for (const migration of pendingMigrations) { - try { - console.log(`[Migration] Applying ${migration.id}: ${migration.name}`); - await this.applyMigration(migration); - await this.markMigrationApplied(migration.id, migration.name, migration.filename); - applied.push(migration.id); - console.log(`[Migration] Successfully applied ${migration.id}`); - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - console.error(`[Migration] Failed to apply migration ${migration.id}:`, errorMessage); - errors.push(`${migration.id}: ${errorMessage}`); - } - } - if (errors.length > 0 && applied.length === 0) { - return { - success: false, - message: `Failed to apply migrations: ${errors.join("; ")}`, - applied - }; - } - return { - success: true, - message: applied.length > 0 ? `Applied ${applied.length} migration(s)${errors.length > 0 ? ` (${errors.length} failed)` : ""}` : "No migrations applied", - applied - }; - } - /** - * Apply a specific migration - */ - async applyMigration(migration) { - const migrationSQL = getMigrationSQLById(migration.id); - if (migrationSQL === null) { - throw new Error(`Migration SQL not found for ${migration.id}`); - } - if (migrationSQL.trim() === "") { - console.log(`[Migration] Skipping empty migration ${migration.id}`); - return; - } - const statements = this.splitSQLStatements(migrationSQL); - for (const statement of statements) { - if (statement.trim()) { - try { - await this.db.prepare(statement).run(); - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - if (errorMessage.includes("already exists") || errorMessage.includes("duplicate column name") || errorMessage.includes("UNIQUE constraint failed")) { - console.log(`[Migration] Skipping (already exists): ${statement.substring(0, 50)}...`); - continue; - } - console.error(`[Migration] Error executing statement: ${statement.substring(0, 100)}...`); - throw error; - } - } - } - } - /** - * Split SQL into statements, handling CREATE TRIGGER properly - */ - splitSQLStatements(sql) { - const statements = []; - let current = ""; - let inTrigger = false; - const lines = sql.split("\n"); - for (const line of lines) { - const trimmed = line.trim(); - if (trimmed.startsWith("--") || trimmed.length === 0) { - continue; - } - if (trimmed.toUpperCase().includes("CREATE TRIGGER")) { - inTrigger = true; - } - current += line + "\n"; - if (inTrigger && trimmed.toUpperCase() === "END;") { - statements.push(current.trim()); - current = ""; - inTrigger = false; - } else if (!inTrigger && trimmed.endsWith(";")) { - statements.push(current.trim()); - current = ""; - } - } - if (current.trim()) { - statements.push(current.trim()); - } - return statements.filter((s) => s.length > 0); - } - /** - * Validate database schema - */ - async validateSchema() { - const issues = []; - const requiredTables = [ - "users", - "content", - "collections", - "media" - ]; - for (const table of requiredTables) { - try { - await this.db.prepare(`SELECT COUNT(*) FROM ${table} LIMIT 1`).first(); - } catch (error) { - issues.push(`Missing table: ${table}`); - } - } - const hasManagedColumn = await this.checkColumnExists("collections", "managed"); - if (!hasManagedColumn) { - issues.push("Missing column: collections.managed"); - } - return { - valid: issues.length === 0, - issues - }; - } -}; - -exports.MigrationService = MigrationService; -//# sourceMappingURL=chunk-FQSMNIY2.cjs.map -//# sourceMappingURL=chunk-FQSMNIY2.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-IGJUBJBW.cjs b/packages/core/dist/chunk-IGJUBJBW.cjs deleted file mode 100644 index 7ad22cc5d..000000000 --- a/packages/core/dist/chunk-IGJUBJBW.cjs +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -exports.__commonJS = __commonJS; -exports.__esm = __esm; -exports.__export = __export; -exports.__toCommonJS = __toCommonJS; -exports.__toESM = __toESM; -//# sourceMappingURL=chunk-IGJUBJBW.cjs.map -//# sourceMappingURL=chunk-IGJUBJBW.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-KYGRJCZM.cjs b/packages/core/dist/chunk-KYGRJCZM.cjs deleted file mode 100644 index 9aea9cb5b..000000000 --- a/packages/core/dist/chunk-KYGRJCZM.cjs +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -// src/types/plugin.ts -var HOOKS = { - // Application lifecycle - APP_INIT: "app:init", - APP_READY: "app:ready", - APP_SHUTDOWN: "app:shutdown", - // Request lifecycle - REQUEST_START: "request:start", - REQUEST_END: "request:end", - REQUEST_ERROR: "request:error", - // Authentication - AUTH_LOGIN: "auth:login", - AUTH_LOGOUT: "auth:logout", - AUTH_REGISTER: "auth:register", - USER_LOGIN: "user:login", - USER_LOGOUT: "user:logout", - // Content lifecycle - CONTENT_CREATE: "content:create", - CONTENT_UPDATE: "content:update", - CONTENT_DELETE: "content:delete", - CONTENT_PUBLISH: "content:publish", - CONTENT_SAVE: "content:save", - // Media lifecycle - MEDIA_UPLOAD: "media:upload", - MEDIA_DELETE: "media:delete", - MEDIA_TRANSFORM: "media:transform", - // Plugin lifecycle - PLUGIN_INSTALL: "plugin:install", - PLUGIN_UNINSTALL: "plugin:uninstall", - PLUGIN_ACTIVATE: "plugin:activate", - PLUGIN_DEACTIVATE: "plugin:deactivate", - // Admin interface - ADMIN_MENU_RENDER: "admin:menu:render", - ADMIN_PAGE_RENDER: "admin:page:render", - // Database - DB_MIGRATE: "db:migrate", - DB_SEED: "db:seed" -}; - -exports.HOOKS = HOOKS; -//# sourceMappingURL=chunk-KYGRJCZM.cjs.map -//# sourceMappingURL=chunk-KYGRJCZM.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-MNFY6DWY.cjs b/packages/core/dist/chunk-MNFY6DWY.cjs deleted file mode 100644 index 4a2c3fc0e..000000000 --- a/packages/core/dist/chunk-MNFY6DWY.cjs +++ /dev/null @@ -1,3184 +0,0 @@ -'use strict'; - -var chunk6FHNRRJ3_cjs = require('./chunk-6FHNRRJ3.cjs'); -var chunkKYGRJCZM_cjs = require('./chunk-KYGRJCZM.cjs'); -var chunkIGJUBJBW_cjs = require('./chunk-IGJUBJBW.cjs'); -var zod = require('zod'); -var hono = require('hono'); - -// ../../node_modules/semver/internal/constants.js -var require_constants = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/internal/constants.js"(exports, module) { - var SEMVER_SPEC_VERSION = "2.0.0"; - var MAX_LENGTH = 256; - var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ - 9007199254740991; - var MAX_SAFE_COMPONENT_LENGTH = 16; - var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; - var RELEASE_TYPES = [ - "major", - "premajor", - "minor", - "preminor", - "patch", - "prepatch", - "prerelease" - ]; - module.exports = { - MAX_LENGTH, - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_SAFE_INTEGER, - RELEASE_TYPES, - SEMVER_SPEC_VERSION, - FLAG_INCLUDE_PRERELEASE: 1, - FLAG_LOOSE: 2 - }; - } -}); - -// ../../node_modules/semver/internal/debug.js -var require_debug = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/internal/debug.js"(exports, module) { - var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { - }; - module.exports = debug; - } -}); - -// ../../node_modules/semver/internal/re.js -var require_re = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/internal/re.js"(exports, module) { - var { - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_LENGTH - } = require_constants(); - var debug = require_debug(); - exports = module.exports = {}; - var re = exports.re = []; - var safeRe = exports.safeRe = []; - var src = exports.src = []; - var safeSrc = exports.safeSrc = []; - var t = exports.t = {}; - var R = 0; - var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; - var safeRegexReplacements = [ - ["\\s", 1], - ["\\d", MAX_LENGTH], - [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] - ]; - var makeSafeRegex = (value) => { - for (const [token, max] of safeRegexReplacements) { - value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`); - } - return value; - }; - var createToken = (name, value, isGlobal) => { - const safe = makeSafeRegex(value); - const index = R++; - debug(name, index, value); - t[name] = index; - src[index] = value; - safeSrc[index] = safe; - re[index] = new RegExp(value, isGlobal ? "g" : void 0); - safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0); - }; - createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); - createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); - createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); - createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`); - createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`); - createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`); - createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`); - createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); - createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); - createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); - createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); - createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); - createToken("FULL", `^${src[t.FULLPLAIN]}$`); - createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); - createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`); - createToken("GTLT", "((?:<|>)?=?)"); - createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); - createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`); - createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`); - createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); - createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); - createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`); - createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`); - createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`); - createToken("COERCERTL", src[t.COERCE], true); - createToken("COERCERTLFULL", src[t.COERCEFULL], true); - createToken("LONETILDE", "(?:~>?)"); - createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = "$1~"; - createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); - createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); - createToken("LONECARET", "(?:\\^)"); - createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true); - exports.caretTrimReplace = "$1^"; - createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); - createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); - createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); - createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); - createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = "$1$2$3"; - createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`); - createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`); - createToken("STAR", "(<|>)?=?\\s*\\*"); - createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); - createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); - } -}); - -// ../../node_modules/semver/internal/parse-options.js -var require_parse_options = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/internal/parse-options.js"(exports, module) { - var looseOption = Object.freeze({ loose: true }); - var emptyOpts = Object.freeze({}); - var parseOptions = (options) => { - if (!options) { - return emptyOpts; - } - if (typeof options !== "object") { - return looseOption; - } - return options; - }; - module.exports = parseOptions; - } -}); - -// ../../node_modules/semver/internal/identifiers.js -var require_identifiers = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/internal/identifiers.js"(exports, module) { - var numeric = /^[0-9]+$/; - var compareIdentifiers = (a, b) => { - if (typeof a === "number" && typeof b === "number") { - return a === b ? 0 : a < b ? -1 : 1; - } - const anum = numeric.test(a); - const bnum = numeric.test(b); - if (anum && bnum) { - a = +a; - b = +b; - } - return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; - }; - var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a); - module.exports = { - compareIdentifiers, - rcompareIdentifiers - }; - } -}); - -// ../../node_modules/semver/classes/semver.js -var require_semver = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/classes/semver.js"(exports, module) { - var debug = require_debug(); - var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants(); - var { safeRe: re, t } = require_re(); - var parseOptions = require_parse_options(); - var { compareIdentifiers } = require_identifiers(); - var SemVer = class _SemVer { - constructor(version, options) { - options = parseOptions(options); - if (version instanceof _SemVer) { - if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { - return version; - } else { - version = version.version; - } - } else if (typeof version !== "string") { - throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`); - } - if (version.length > MAX_LENGTH) { - throw new TypeError( - `version is longer than ${MAX_LENGTH} characters` - ); - } - debug("SemVer", version, options); - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); - if (!m) { - throw new TypeError(`Invalid Version: ${version}`); - } - this.raw = version; - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError("Invalid major version"); - } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError("Invalid minor version"); - } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError("Invalid patch version"); - } - if (!m[4]) { - this.prerelease = []; - } else { - this.prerelease = m[4].split(".").map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num; - } - } - return id; - }); - } - this.build = m[5] ? m[5].split(".") : []; - this.format(); - } - format() { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join(".")}`; - } - return this.version; - } - toString() { - return this.version; - } - compare(other) { - debug("SemVer.compare", this.version, this.options, other); - if (!(other instanceof _SemVer)) { - if (typeof other === "string" && other === this.version) { - return 0; - } - other = new _SemVer(other, this.options); - } - if (other.version === this.version) { - return 0; - } - return this.compareMain(other) || this.comparePre(other); - } - compareMain(other) { - if (!(other instanceof _SemVer)) { - other = new _SemVer(other, this.options); - } - if (this.major < other.major) { - return -1; - } - if (this.major > other.major) { - return 1; - } - if (this.minor < other.minor) { - return -1; - } - if (this.minor > other.minor) { - return 1; - } - if (this.patch < other.patch) { - return -1; - } - if (this.patch > other.patch) { - return 1; - } - return 0; - } - comparePre(other) { - if (!(other instanceof _SemVer)) { - other = new _SemVer(other, this.options); - } - if (this.prerelease.length && !other.prerelease.length) { - return -1; - } else if (!this.prerelease.length && other.prerelease.length) { - return 1; - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0; - } - let i = 0; - do { - const a = this.prerelease[i]; - const b = other.prerelease[i]; - debug("prerelease compare", i, a, b); - if (a === void 0 && b === void 0) { - return 0; - } else if (b === void 0) { - return 1; - } else if (a === void 0) { - return -1; - } else if (a === b) { - continue; - } else { - return compareIdentifiers(a, b); - } - } while (++i); - } - compareBuild(other) { - if (!(other instanceof _SemVer)) { - other = new _SemVer(other, this.options); - } - let i = 0; - do { - const a = this.build[i]; - const b = other.build[i]; - debug("build compare", i, a, b); - if (a === void 0 && b === void 0) { - return 0; - } else if (b === void 0) { - return 1; - } else if (a === void 0) { - return -1; - } else if (a === b) { - continue; - } else { - return compareIdentifiers(a, b); - } - } while (++i); - } - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc(release, identifier, identifierBase) { - if (release.startsWith("pre")) { - if (!identifier && identifierBase === false) { - throw new Error("invalid increment argument: identifier is empty"); - } - if (identifier) { - const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]); - if (!match || match[1] !== identifier) { - throw new Error(`invalid identifier: ${identifier}`); - } - } - } - switch (release) { - case "premajor": - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc("pre", identifier, identifierBase); - break; - case "preminor": - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc("pre", identifier, identifierBase); - break; - case "prepatch": - this.prerelease.length = 0; - this.inc("patch", identifier, identifierBase); - this.inc("pre", identifier, identifierBase); - break; - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case "prerelease": - if (this.prerelease.length === 0) { - this.inc("patch", identifier, identifierBase); - } - this.inc("pre", identifier, identifierBase); - break; - case "release": - if (this.prerelease.length === 0) { - throw new Error(`version ${this.raw} is not a prerelease`); - } - this.prerelease.length = 0; - break; - case "major": - if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break; - case "minor": - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break; - case "patch": - if (this.prerelease.length === 0) { - this.patch++; - } - this.prerelease = []; - break; - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case "pre": { - const base = Number(identifierBase) ? 1 : 0; - if (this.prerelease.length === 0) { - this.prerelease = [base]; - } else { - let i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === "number") { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) { - if (identifier === this.prerelease.join(".") && identifierBase === false) { - throw new Error("invalid increment argument: identifier already exists"); - } - this.prerelease.push(base); - } - } - if (identifier) { - let prerelease = [identifier, base]; - if (identifierBase === false) { - prerelease = [identifier]; - } - if (compareIdentifiers(this.prerelease[0], identifier) === 0) { - if (isNaN(this.prerelease[1])) { - this.prerelease = prerelease; - } - } else { - this.prerelease = prerelease; - } - } - break; - } - default: - throw new Error(`invalid increment argument: ${release}`); - } - this.raw = this.format(); - if (this.build.length) { - this.raw += `+${this.build.join(".")}`; - } - return this; - } - }; - module.exports = SemVer; - } -}); - -// ../../node_modules/semver/functions/parse.js -var require_parse = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/parse.js"(exports, module) { - var SemVer = require_semver(); - var parse = (version, options, throwErrors = false) => { - if (version instanceof SemVer) { - return version; - } - try { - return new SemVer(version, options); - } catch (er) { - if (!throwErrors) { - return null; - } - throw er; - } - }; - module.exports = parse; - } -}); - -// ../../node_modules/semver/functions/valid.js -var require_valid = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/valid.js"(exports, module) { - var parse = require_parse(); - var valid = (version, options) => { - const v = parse(version, options); - return v ? v.version : null; - }; - module.exports = valid; - } -}); - -// ../../node_modules/semver/functions/clean.js -var require_clean = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/clean.js"(exports, module) { - var parse = require_parse(); - var clean = (version, options) => { - const s = parse(version.trim().replace(/^[=v]+/, ""), options); - return s ? s.version : null; - }; - module.exports = clean; - } -}); - -// ../../node_modules/semver/functions/inc.js -var require_inc = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/inc.js"(exports, module) { - var SemVer = require_semver(); - var inc = (version, release, options, identifier, identifierBase) => { - if (typeof options === "string") { - identifierBase = identifier; - identifier = options; - options = void 0; - } - try { - return new SemVer( - version instanceof SemVer ? version.version : version, - options - ).inc(release, identifier, identifierBase).version; - } catch (er) { - return null; - } - }; - module.exports = inc; - } -}); - -// ../../node_modules/semver/functions/diff.js -var require_diff = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/diff.js"(exports, module) { - var parse = require_parse(); - var diff = (version1, version2) => { - const v1 = parse(version1, null, true); - const v2 = parse(version2, null, true); - const comparison = v1.compare(v2); - if (comparison === 0) { - return null; - } - const v1Higher = comparison > 0; - const highVersion = v1Higher ? v1 : v2; - const lowVersion = v1Higher ? v2 : v1; - const highHasPre = !!highVersion.prerelease.length; - const lowHasPre = !!lowVersion.prerelease.length; - if (lowHasPre && !highHasPre) { - if (!lowVersion.patch && !lowVersion.minor) { - return "major"; - } - if (lowVersion.compareMain(highVersion) === 0) { - if (lowVersion.minor && !lowVersion.patch) { - return "minor"; - } - return "patch"; - } - } - const prefix = highHasPre ? "pre" : ""; - if (v1.major !== v2.major) { - return prefix + "major"; - } - if (v1.minor !== v2.minor) { - return prefix + "minor"; - } - if (v1.patch !== v2.patch) { - return prefix + "patch"; - } - return "prerelease"; - }; - module.exports = diff; - } -}); - -// ../../node_modules/semver/functions/major.js -var require_major = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/major.js"(exports, module) { - var SemVer = require_semver(); - var major = (a, loose) => new SemVer(a, loose).major; - module.exports = major; - } -}); - -// ../../node_modules/semver/functions/minor.js -var require_minor = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/minor.js"(exports, module) { - var SemVer = require_semver(); - var minor = (a, loose) => new SemVer(a, loose).minor; - module.exports = minor; - } -}); - -// ../../node_modules/semver/functions/patch.js -var require_patch = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/patch.js"(exports, module) { - var SemVer = require_semver(); - var patch = (a, loose) => new SemVer(a, loose).patch; - module.exports = patch; - } -}); - -// ../../node_modules/semver/functions/prerelease.js -var require_prerelease = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/prerelease.js"(exports, module) { - var parse = require_parse(); - var prerelease = (version, options) => { - const parsed = parse(version, options); - return parsed && parsed.prerelease.length ? parsed.prerelease : null; - }; - module.exports = prerelease; - } -}); - -// ../../node_modules/semver/functions/compare.js -var require_compare = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/compare.js"(exports, module) { - var SemVer = require_semver(); - var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)); - module.exports = compare; - } -}); - -// ../../node_modules/semver/functions/rcompare.js -var require_rcompare = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/rcompare.js"(exports, module) { - var compare = require_compare(); - var rcompare = (a, b, loose) => compare(b, a, loose); - module.exports = rcompare; - } -}); - -// ../../node_modules/semver/functions/compare-loose.js -var require_compare_loose = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/compare-loose.js"(exports, module) { - var compare = require_compare(); - var compareLoose = (a, b) => compare(a, b, true); - module.exports = compareLoose; - } -}); - -// ../../node_modules/semver/functions/compare-build.js -var require_compare_build = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/compare-build.js"(exports, module) { - var SemVer = require_semver(); - var compareBuild = (a, b, loose) => { - const versionA = new SemVer(a, loose); - const versionB = new SemVer(b, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB); - }; - module.exports = compareBuild; - } -}); - -// ../../node_modules/semver/functions/sort.js -var require_sort = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/sort.js"(exports, module) { - var compareBuild = require_compare_build(); - var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)); - module.exports = sort; - } -}); - -// ../../node_modules/semver/functions/rsort.js -var require_rsort = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/rsort.js"(exports, module) { - var compareBuild = require_compare_build(); - var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); - module.exports = rsort; - } -}); - -// ../../node_modules/semver/functions/gt.js -var require_gt = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/gt.js"(exports, module) { - var compare = require_compare(); - var gt = (a, b, loose) => compare(a, b, loose) > 0; - module.exports = gt; - } -}); - -// ../../node_modules/semver/functions/lt.js -var require_lt = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/lt.js"(exports, module) { - var compare = require_compare(); - var lt = (a, b, loose) => compare(a, b, loose) < 0; - module.exports = lt; - } -}); - -// ../../node_modules/semver/functions/eq.js -var require_eq = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/eq.js"(exports, module) { - var compare = require_compare(); - var eq = (a, b, loose) => compare(a, b, loose) === 0; - module.exports = eq; - } -}); - -// ../../node_modules/semver/functions/neq.js -var require_neq = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/neq.js"(exports, module) { - var compare = require_compare(); - var neq = (a, b, loose) => compare(a, b, loose) !== 0; - module.exports = neq; - } -}); - -// ../../node_modules/semver/functions/gte.js -var require_gte = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/gte.js"(exports, module) { - var compare = require_compare(); - var gte = (a, b, loose) => compare(a, b, loose) >= 0; - module.exports = gte; - } -}); - -// ../../node_modules/semver/functions/lte.js -var require_lte = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/lte.js"(exports, module) { - var compare = require_compare(); - var lte = (a, b, loose) => compare(a, b, loose) <= 0; - module.exports = lte; - } -}); - -// ../../node_modules/semver/functions/cmp.js -var require_cmp = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/cmp.js"(exports, module) { - var eq = require_eq(); - var neq = require_neq(); - var gt = require_gt(); - var gte = require_gte(); - var lt = require_lt(); - var lte = require_lte(); - var cmp = (a, op, b, loose) => { - switch (op) { - case "===": - if (typeof a === "object") { - a = a.version; - } - if (typeof b === "object") { - b = b.version; - } - return a === b; - case "!==": - if (typeof a === "object") { - a = a.version; - } - if (typeof b === "object") { - b = b.version; - } - return a !== b; - case "": - case "=": - case "==": - return eq(a, b, loose); - case "!=": - return neq(a, b, loose); - case ">": - return gt(a, b, loose); - case ">=": - return gte(a, b, loose); - case "<": - return lt(a, b, loose); - case "<=": - return lte(a, b, loose); - default: - throw new TypeError(`Invalid operator: ${op}`); - } - }; - module.exports = cmp; - } -}); - -// ../../node_modules/semver/functions/coerce.js -var require_coerce = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/coerce.js"(exports, module) { - var SemVer = require_semver(); - var parse = require_parse(); - var { safeRe: re, t } = require_re(); - var coerce = (version, options) => { - if (version instanceof SemVer) { - return version; - } - if (typeof version === "number") { - version = String(version); - } - if (typeof version !== "string") { - return null; - } - options = options || {}; - let match = null; - if (!options.rtl) { - match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]); - } else { - const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]; - let next; - while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length)) { - if (!match || next.index + next[0].length !== match.index + match[0].length) { - match = next; - } - coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length; - } - coerceRtlRegex.lastIndex = -1; - } - if (match === null) { - return null; - } - const major = match[2]; - const minor = match[3] || "0"; - const patch = match[4] || "0"; - const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ""; - const build = options.includePrerelease && match[6] ? `+${match[6]}` : ""; - return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options); - }; - module.exports = coerce; - } -}); - -// ../../node_modules/semver/internal/lrucache.js -var require_lrucache = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/internal/lrucache.js"(exports, module) { - var LRUCache = class { - constructor() { - this.max = 1e3; - this.map = /* @__PURE__ */ new Map(); - } - get(key) { - const value = this.map.get(key); - if (value === void 0) { - return void 0; - } else { - this.map.delete(key); - this.map.set(key, value); - return value; - } - } - delete(key) { - return this.map.delete(key); - } - set(key, value) { - const deleted = this.delete(key); - if (!deleted && value !== void 0) { - if (this.map.size >= this.max) { - const firstKey = this.map.keys().next().value; - this.delete(firstKey); - } - this.map.set(key, value); - } - return this; - } - }; - module.exports = LRUCache; - } -}); - -// ../../node_modules/semver/classes/range.js -var require_range = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/classes/range.js"(exports, module) { - var SPACE_CHARACTERS = /\s+/g; - var Range = class _Range { - constructor(range, options) { - options = parseOptions(options); - if (range instanceof _Range) { - if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { - return range; - } else { - return new _Range(range.raw, options); - } - } - if (range instanceof Comparator) { - this.raw = range.value; - this.set = [[range]]; - this.formatted = void 0; - return this; - } - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - this.raw = range.trim().replace(SPACE_CHARACTERS, " "); - this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length); - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${this.raw}`); - } - if (this.set.length > 1) { - const first = this.set[0]; - this.set = this.set.filter((c) => !isNullSet(c[0])); - if (this.set.length === 0) { - this.set = [first]; - } else if (this.set.length > 1) { - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c]; - break; - } - } - } - } - this.formatted = void 0; - } - get range() { - if (this.formatted === void 0) { - this.formatted = ""; - for (let i = 0; i < this.set.length; i++) { - if (i > 0) { - this.formatted += "||"; - } - const comps = this.set[i]; - for (let k = 0; k < comps.length; k++) { - if (k > 0) { - this.formatted += " "; - } - this.formatted += comps[k].toString().trim(); - } - } - } - return this.formatted; - } - format() { - return this.range; - } - toString() { - return this.range; - } - parseRange(range) { - const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE); - const memoKey = memoOpts + ":" + range; - const cached = cache.get(memoKey); - if (cached) { - return cached; - } - const loose = this.options.loose; - const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug("hyphen replace", range); - range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace); - debug("comparator trim", range); - range = range.replace(re[t.TILDETRIM], tildeTrimReplace); - debug("tilde trim", range); - range = range.replace(re[t.CARETTRIM], caretTrimReplace); - debug("caret trim", range); - let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)); - if (loose) { - rangeList = rangeList.filter((comp) => { - debug("loose invalid filter", comp, this.options); - return !!comp.match(re[t.COMPARATORLOOSE]); - }); - } - debug("range list", rangeList); - const rangeMap = /* @__PURE__ */ new Map(); - const comparators = rangeList.map((comp) => new Comparator(comp, this.options)); - for (const comp of comparators) { - if (isNullSet(comp)) { - return [comp]; - } - rangeMap.set(comp.value, comp); - } - if (rangeMap.size > 1 && rangeMap.has("")) { - rangeMap.delete(""); - } - const result = [...rangeMap.values()]; - cache.set(memoKey, result); - return result; - } - intersects(range, options) { - if (!(range instanceof _Range)) { - throw new TypeError("a Range is required"); - } - return this.set.some((thisComparators) => { - return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { - return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options); - }); - }); - }); - }); - } - // if ANY of the sets match ALL of its comparators, then pass - test(version) { - if (!version) { - return false; - } - if (typeof version === "string") { - try { - version = new SemVer(version, this.options); - } catch (er) { - return false; - } - } - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true; - } - } - return false; - } - }; - module.exports = Range; - var LRU = require_lrucache(); - var cache = new LRU(); - var parseOptions = require_parse_options(); - var Comparator = require_comparator(); - var debug = require_debug(); - var SemVer = require_semver(); - var { - safeRe: re, - t, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = require_re(); - var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants(); - var isNullSet = (c) => c.value === "<0.0.0-0"; - var isAny = (c) => c.value === ""; - var isSatisfiable = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options); - }); - testComparator = remainingComparators.pop(); - } - return result; - }; - var parseComparator = (comp, options) => { - comp = comp.replace(re[t.BUILD], ""); - debug("comp", comp, options); - comp = replaceCarets(comp, options); - debug("caret", comp); - comp = replaceTildes(comp, options); - debug("tildes", comp); - comp = replaceXRanges(comp, options); - debug("xrange", comp); - comp = replaceStars(comp, options); - debug("stars", comp); - return comp; - }; - var isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; - var replaceTildes = (comp, options) => { - return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" "); - }; - var replaceTilde = (comp, options) => { - const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; - return comp.replace(r, (_, M, m, p, pr) => { - debug("tilde", comp, _, M, m, p, pr); - let ret; - if (isX(M)) { - ret = ""; - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p)) { - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; - } else if (pr) { - debug("replaceTilde pr", pr); - ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; - } - debug("tilde return", ret); - return ret; - }); - }; - var replaceCarets = (comp, options) => { - return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" "); - }; - var replaceCaret = (comp, options) => { - debug("caret", comp, options); - const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]; - const z2 = options.includePrerelease ? "-0" : ""; - return comp.replace(r, (_, M, m, p, pr) => { - debug("caret", comp, _, M, m, p, pr); - let ret; - if (isX(M)) { - ret = ""; - } else if (isX(m)) { - ret = `>=${M}.0.0${z2} <${+M + 1}.0.0-0`; - } else if (isX(p)) { - if (M === "0") { - ret = `>=${M}.${m}.0${z2} <${M}.${+m + 1}.0-0`; - } else { - ret = `>=${M}.${m}.0${z2} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug("replaceCaret pr", pr); - if (M === "0") { - if (m === "0") { - ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; - } - } else { - debug("no pr"); - if (M === "0") { - if (m === "0") { - ret = `>=${M}.${m}.${p}${z2} <${M}.${m}.${+p + 1}-0`; - } else { - ret = `>=${M}.${m}.${p}${z2} <${M}.${+m + 1}.0-0`; - } - } else { - ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; - } - } - debug("caret return", ret); - return ret; - }); - }; - var replaceXRanges = (comp, options) => { - debug("replaceXRanges", comp, options); - return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" "); - }; - var replaceXRange = (comp, options) => { - comp = comp.trim(); - const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug("xRange", comp, ret, gtlt, M, m, p, pr); - const xM = isX(M); - const xm = xM || isX(m); - const xp = xm || isX(p); - const anyX = xp; - if (gtlt === "=" && anyX) { - gtlt = ""; - } - pr = options.includePrerelease ? "-0" : ""; - if (xM) { - if (gtlt === ">" || gtlt === "<") { - ret = "<0.0.0-0"; - } else { - ret = "*"; - } - } else if (gtlt && anyX) { - if (xm) { - m = 0; - } - p = 0; - if (gtlt === ">") { - gtlt = ">="; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else { - m = +m + 1; - p = 0; - } - } else if (gtlt === "<=") { - gtlt = "<"; - if (xm) { - M = +M + 1; - } else { - m = +m + 1; - } - } - if (gtlt === "<") { - pr = "-0"; - } - ret = `${gtlt + M}.${m}.${p}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; - } - debug("xRange return", ret); - return ret; - }); - }; - var replaceStars = (comp, options) => { - debug("replaceStars", comp, options); - return comp.trim().replace(re[t.STAR], ""); - }; - var replaceGTE0 = (comp, options) => { - debug("replaceGTE0", comp, options); - return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], ""); - }; - var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { - if (isX(fM)) { - from = ""; - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? "-0" : ""}`; - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? "-0" : ""}`; - } - if (isX(tM)) { - to = ""; - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; - } - return `${from} ${to}`.trim(); - }; - var testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false; - } - } - if (version.prerelease.length && !options.includePrerelease) { - for (let i = 0; i < set.length; i++) { - debug(set[i].semver); - if (set[i].semver === Comparator.ANY) { - continue; - } - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver; - if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { - return true; - } - } - } - return false; - } - return true; - }; - } -}); - -// ../../node_modules/semver/classes/comparator.js -var require_comparator = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/classes/comparator.js"(exports, module) { - var ANY = Symbol("SemVer ANY"); - var Comparator = class _Comparator { - static get ANY() { - return ANY; - } - constructor(comp, options) { - options = parseOptions(options); - if (comp instanceof _Comparator) { - if (comp.loose === !!options.loose) { - return comp; - } else { - comp = comp.value; - } - } - comp = comp.trim().split(/\s+/).join(" "); - debug("comparator", comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - if (this.semver === ANY) { - this.value = ""; - } else { - this.value = this.operator + this.semver.version; - } - debug("comp", this); - } - parse(comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; - const m = comp.match(r); - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`); - } - this.operator = m[1] !== void 0 ? m[1] : ""; - if (this.operator === "=") { - this.operator = ""; - } - if (!m[2]) { - this.semver = ANY; - } else { - this.semver = new SemVer(m[2], this.options.loose); - } - } - toString() { - return this.value; - } - test(version) { - debug("Comparator.test", version, this.options.loose); - if (this.semver === ANY || version === ANY) { - return true; - } - if (typeof version === "string") { - try { - version = new SemVer(version, this.options); - } catch (er) { - return false; - } - } - return cmp(version, this.operator, this.semver, this.options); - } - intersects(comp, options) { - if (!(comp instanceof _Comparator)) { - throw new TypeError("a Comparator is required"); - } - if (this.operator === "") { - if (this.value === "") { - return true; - } - return new Range(comp.value, options).test(this.value); - } else if (comp.operator === "") { - if (comp.value === "") { - return true; - } - return new Range(this.value, options).test(comp.semver); - } - options = parseOptions(options); - if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) { - return false; - } - if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) { - return false; - } - if (this.operator.startsWith(">") && comp.operator.startsWith(">")) { - return true; - } - if (this.operator.startsWith("<") && comp.operator.startsWith("<")) { - return true; - } - if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) { - return true; - } - if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) { - return true; - } - if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) { - return true; - } - return false; - } - }; - module.exports = Comparator; - var parseOptions = require_parse_options(); - var { safeRe: re, t } = require_re(); - var cmp = require_cmp(); - var debug = require_debug(); - var SemVer = require_semver(); - var Range = require_range(); - } -}); - -// ../../node_modules/semver/functions/satisfies.js -var require_satisfies = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/functions/satisfies.js"(exports, module) { - var Range = require_range(); - var satisfies = (version, range, options) => { - try { - range = new Range(range, options); - } catch (er) { - return false; - } - return range.test(version); - }; - module.exports = satisfies; - } -}); - -// ../../node_modules/semver/ranges/to-comparators.js -var require_to_comparators = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/ranges/to-comparators.js"(exports, module) { - var Range = require_range(); - var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" ")); - module.exports = toComparators; - } -}); - -// ../../node_modules/semver/ranges/max-satisfying.js -var require_max_satisfying = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/ranges/max-satisfying.js"(exports, module) { - var SemVer = require_semver(); - var Range = require_range(); - var maxSatisfying = (versions, range, options) => { - let max = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range(range, options); - } catch (er) { - return null; - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - if (!max || maxSV.compare(v) === -1) { - max = v; - maxSV = new SemVer(max, options); - } - } - }); - return max; - }; - module.exports = maxSatisfying; - } -}); - -// ../../node_modules/semver/ranges/min-satisfying.js -var require_min_satisfying = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/ranges/min-satisfying.js"(exports, module) { - var SemVer = require_semver(); - var Range = require_range(); - var minSatisfying = (versions, range, options) => { - let min = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range(range, options); - } catch (er) { - return null; - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - if (!min || minSV.compare(v) === 1) { - min = v; - minSV = new SemVer(min, options); - } - } - }); - return min; - }; - module.exports = minSatisfying; - } -}); - -// ../../node_modules/semver/ranges/min-version.js -var require_min_version = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/ranges/min-version.js"(exports, module) { - var SemVer = require_semver(); - var Range = require_range(); - var gt = require_gt(); - var minVersion = (range, loose) => { - range = new Range(range, loose); - let minver = new SemVer("0.0.0"); - if (range.test(minver)) { - return minver; - } - minver = new SemVer("0.0.0-0"); - if (range.test(minver)) { - return minver; - } - minver = null; - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - let setMin = null; - comparators.forEach((comparator) => { - const compver = new SemVer(comparator.semver.version); - switch (comparator.operator) { - case ">": - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - /* fallthrough */ - case "": - case ">=": - if (!setMin || gt(compver, setMin)) { - setMin = compver; - } - break; - case "<": - case "<=": - break; - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`); - } - }); - if (setMin && (!minver || gt(minver, setMin))) { - minver = setMin; - } - } - if (minver && range.test(minver)) { - return minver; - } - return null; - }; - module.exports = minVersion; - } -}); - -// ../../node_modules/semver/ranges/valid.js -var require_valid2 = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/ranges/valid.js"(exports, module) { - var Range = require_range(); - var validRange = (range, options) => { - try { - return new Range(range, options).range || "*"; - } catch (er) { - return null; - } - }; - module.exports = validRange; - } -}); - -// ../../node_modules/semver/ranges/outside.js -var require_outside = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/ranges/outside.js"(exports, module) { - var SemVer = require_semver(); - var Comparator = require_comparator(); - var { ANY } = Comparator; - var Range = require_range(); - var satisfies = require_satisfies(); - var gt = require_gt(); - var lt = require_lt(); - var lte = require_lte(); - var gte = require_gte(); - var outside = (version, range, hilo, options) => { - version = new SemVer(version, options); - range = new Range(range, options); - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case ">": - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = ">"; - ecomp = ">="; - break; - case "<": - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = "<"; - ecomp = "<="; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); - } - if (satisfies(version, range, options)) { - return false; - } - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i]; - let high = null; - let low = null; - comparators.forEach((comparator) => { - if (comparator.semver === ANY) { - comparator = new Comparator(">=0.0.0"); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } - }); - if (high.operator === comp || high.operator === ecomp) { - return false; - } - if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; - } - } - return true; - }; - module.exports = outside; - } -}); - -// ../../node_modules/semver/ranges/gtr.js -var require_gtr = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/ranges/gtr.js"(exports, module) { - var outside = require_outside(); - var gtr = (version, range, options) => outside(version, range, ">", options); - module.exports = gtr; - } -}); - -// ../../node_modules/semver/ranges/ltr.js -var require_ltr = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/ranges/ltr.js"(exports, module) { - var outside = require_outside(); - var ltr = (version, range, options) => outside(version, range, "<", options); - module.exports = ltr; - } -}); - -// ../../node_modules/semver/ranges/intersects.js -var require_intersects = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/ranges/intersects.js"(exports, module) { - var Range = require_range(); - var intersects = (r1, r2, options) => { - r1 = new Range(r1, options); - r2 = new Range(r2, options); - return r1.intersects(r2, options); - }; - module.exports = intersects; - } -}); - -// ../../node_modules/semver/ranges/simplify.js -var require_simplify = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/ranges/simplify.js"(exports, module) { - var satisfies = require_satisfies(); - var compare = require_compare(); - module.exports = (versions, range, options) => { - const set = []; - let first = null; - let prev = null; - const v = versions.sort((a, b) => compare(a, b, options)); - for (const version of v) { - const included = satisfies(version, range, options); - if (included) { - prev = version; - if (!first) { - first = version; - } - } else { - if (prev) { - set.push([first, prev]); - } - prev = null; - first = null; - } - } - if (first) { - set.push([first, null]); - } - const ranges = []; - for (const [min, max] of set) { - if (min === max) { - ranges.push(min); - } else if (!max && min === v[0]) { - ranges.push("*"); - } else if (!max) { - ranges.push(`>=${min}`); - } else if (min === v[0]) { - ranges.push(`<=${max}`); - } else { - ranges.push(`${min} - ${max}`); - } - } - const simplified = ranges.join(" || "); - const original = typeof range.raw === "string" ? range.raw : String(range); - return simplified.length < original.length ? simplified : range; - }; - } -}); - -// ../../node_modules/semver/ranges/subset.js -var require_subset = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/ranges/subset.js"(exports, module) { - var Range = require_range(); - var Comparator = require_comparator(); - var { ANY } = Comparator; - var satisfies = require_satisfies(); - var compare = require_compare(); - var subset = (sub, dom, options = {}) => { - if (sub === dom) { - return true; - } - sub = new Range(sub, options); - dom = new Range(dom, options); - let sawNonNull = false; - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) { - continue OUTER; - } - } - if (sawNonNull) { - return false; - } - } - return true; - }; - var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")]; - var minimumVersion = [new Comparator(">=0.0.0")]; - var simpleSubset = (sub, dom, options) => { - if (sub === dom) { - return true; - } - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) { - return true; - } else if (options.includePrerelease) { - sub = minimumVersionWithPreRelease; - } else { - sub = minimumVersion; - } - } - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) { - return true; - } else { - dom = minimumVersion; - } - } - const eqSet = /* @__PURE__ */ new Set(); - let gt, lt; - for (const c of sub) { - if (c.operator === ">" || c.operator === ">=") { - gt = higherGT(gt, c, options); - } else if (c.operator === "<" || c.operator === "<=") { - lt = lowerLT(lt, c, options); - } else { - eqSet.add(c.semver); - } - } - if (eqSet.size > 1) { - return null; - } - let gtltComp; - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options); - if (gtltComp > 0) { - return null; - } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) { - return null; - } - } - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) { - return null; - } - if (lt && !satisfies(eq, String(lt), options)) { - return null; - } - for (const c of dom) { - if (!satisfies(eq, String(c), options)) { - return false; - } - } - return true; - } - let higher, lower; - let hasDomLT, hasDomGT; - let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">="; - hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<="; - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; - } - } - if (c.operator === ">" || c.operator === ">=") { - higher = higherGT(gt, c, options); - if (higher === c && higher !== gt) { - return false; - } - } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c), options)) { - return false; - } - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; - } - } - if (c.operator === "<" || c.operator === "<=") { - lower = lowerLT(lt, c, options); - if (lower === c && lower !== lt) { - return false; - } - } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c), options)) { - return false; - } - } - if (!c.operator && (lt || gt) && gtltComp !== 0) { - return false; - } - } - if (gt && hasDomLT && !lt && gtltComp !== 0) { - return false; - } - if (lt && hasDomGT && !gt && gtltComp !== 0) { - return false; - } - if (needDomGTPre || needDomLTPre) { - return false; - } - return true; - }; - var higherGT = (a, b, options) => { - if (!a) { - return b; - } - const comp = compare(a.semver, b.semver, options); - return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a; - }; - var lowerLT = (a, b, options) => { - if (!a) { - return b; - } - const comp = compare(a.semver, b.semver, options); - return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a; - }; - module.exports = subset; - } -}); - -// ../../node_modules/semver/index.js -var require_semver2 = chunkIGJUBJBW_cjs.__commonJS({ - "../../node_modules/semver/index.js"(exports, module) { - var internalRe = require_re(); - var constants = require_constants(); - var SemVer = require_semver(); - var identifiers = require_identifiers(); - var parse = require_parse(); - var valid = require_valid(); - var clean = require_clean(); - var inc = require_inc(); - var diff = require_diff(); - var major = require_major(); - var minor = require_minor(); - var patch = require_patch(); - var prerelease = require_prerelease(); - var compare = require_compare(); - var rcompare = require_rcompare(); - var compareLoose = require_compare_loose(); - var compareBuild = require_compare_build(); - var sort = require_sort(); - var rsort = require_rsort(); - var gt = require_gt(); - var lt = require_lt(); - var eq = require_eq(); - var neq = require_neq(); - var gte = require_gte(); - var lte = require_lte(); - var cmp = require_cmp(); - var coerce = require_coerce(); - var Comparator = require_comparator(); - var Range = require_range(); - var satisfies = require_satisfies(); - var toComparators = require_to_comparators(); - var maxSatisfying = require_max_satisfying(); - var minSatisfying = require_min_satisfying(); - var minVersion = require_min_version(); - var validRange = require_valid2(); - var outside = require_outside(); - var gtr = require_gtr(); - var ltr = require_ltr(); - var intersects = require_intersects(); - var simplifyRange = require_simplify(); - var subset = require_subset(); - module.exports = { - parse, - valid, - clean, - inc, - diff, - major, - minor, - patch, - prerelease, - compare, - rcompare, - compareLoose, - compareBuild, - sort, - rsort, - gt, - lt, - eq, - neq, - gte, - lte, - cmp, - coerce, - Comparator, - Range, - satisfies, - toComparators, - maxSatisfying, - minSatisfying, - minVersion, - validRange, - outside, - gtr, - ltr, - intersects, - simplifyRange, - subset, - SemVer, - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - RELEASE_TYPES: constants.RELEASE_TYPES, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers - }; - } -}); - -// src/plugins/hook-system.ts -var HookSystemImpl = class { - hooks = /* @__PURE__ */ new Map(); - executing = /* @__PURE__ */ new Set(); - /** - * Register a hook handler - */ - register(hookName, handler, priority = 10) { - if (!this.hooks.has(hookName)) { - this.hooks.set(hookName, []); - } - const hooks = this.hooks.get(hookName); - const hook = { - name: hookName, - handler, - priority - }; - const insertIndex = hooks.findIndex((h) => h.priority > priority); - if (insertIndex === -1) { - hooks.push(hook); - } else { - hooks.splice(insertIndex, 0, hook); - } - console.debug(`Hook registered: ${hookName} (priority: ${priority})`); - } - /** - * Execute all handlers for a hook - */ - async execute(hookName, data, context) { - const hooks = this.hooks.get(hookName); - if (!hooks || hooks.length === 0) { - return data; - } - if (this.executing.has(hookName)) { - console.warn(`Hook recursion detected for: ${hookName}`); - return data; - } - this.executing.add(hookName); - try { - let result = data; - let cancelled = false; - const hookContext = { - plugin: "", - // Will be set by the plugin manager - context: context || {}, - cancel: () => { - cancelled = true; - } - }; - for (const hook of hooks) { - if (cancelled) { - console.debug(`Hook execution cancelled: ${hookName}`); - break; - } - try { - console.debug(`Executing hook: ${hookName} (priority: ${hook.priority})`); - result = await hook.handler(result, hookContext); - } catch (error) { - console.error(`Hook execution failed: ${hookName}`, error); - if (error instanceof Error && error.message.includes("CRITICAL")) { - throw error; - } - } - } - return result; - } finally { - this.executing.delete(hookName); - } - } - /** - * Remove a hook handler - */ - unregister(hookName, handler) { - const hooks = this.hooks.get(hookName); - if (!hooks) return; - const index = hooks.findIndex((h) => h.handler === handler); - if (index !== -1) { - hooks.splice(index, 1); - console.debug(`Hook unregistered: ${hookName}`); - } - if (hooks.length === 0) { - this.hooks.delete(hookName); - } - } - /** - * Get all registered hooks for a name - */ - getHooks(hookName) { - return this.hooks.get(hookName) || []; - } - /** - * Get all registered hook names - */ - getHookNames() { - return Array.from(this.hooks.keys()); - } - /** - * Get hook statistics - */ - getStats() { - return Array.from(this.hooks.entries()).map(([hookName, handlers]) => ({ - hookName, - handlerCount: handlers.length - })); - } - /** - * Clear all hooks (useful for testing) - */ - clear() { - this.hooks.clear(); - this.executing.clear(); - } - /** - * Create a scoped hook system for a plugin - */ - createScope(_pluginName) { - return new ScopedHookSystem(this); - } -}; -var ScopedHookSystem = class { - constructor(parent) { - this.parent = parent; - } - registeredHooks = []; - /** - * Register a hook (scoped to this plugin) - */ - register(hookName, handler, priority) { - this.parent.register(hookName, handler, priority); - this.registeredHooks.push({ hookName, handler }); - } - /** - * Execute a hook - */ - async execute(hookName, data, context) { - return this.parent.execute(hookName, data, context); - } - /** - * Unregister a specific hook - */ - unregister(hookName, handler) { - this.parent.unregister(hookName, handler); - const index = this.registeredHooks.findIndex( - (h) => h.hookName === hookName && h.handler === handler - ); - if (index !== -1) { - this.registeredHooks.splice(index, 1); - } - } - /** - * Unregister all hooks for this plugin - */ - unregisterAll() { - for (const { hookName, handler } of this.registeredHooks) { - this.parent.unregister(hookName, handler); - } - this.registeredHooks.length = 0; - } - /** - * Get hooks registered by this plugin - */ - getRegisteredHooks() { - return [...this.registeredHooks]; - } -}; -var HookUtils = class { - /** - * Create a hook name with namespace - */ - static createHookName(namespace, event) { - return `${namespace}:${event}`; - } - /** - * Parse a hook name to extract namespace and event - */ - static parseHookName(hookName) { - const parts = hookName.split(":"); - return { - namespace: parts[0] || "", - event: parts.slice(1).join(":") || "" - }; - } - /** - * Create a middleware that executes hooks - */ - static createHookMiddleware(hookSystem, beforeHook, afterHook) { - return async (c, next) => { - if (beforeHook) { - const beforeData = { request: c.req, context: c }; - await hookSystem.execute(beforeHook, beforeData); - } - await next(); - if (afterHook) { - const afterData = { request: c.req, response: c.res, context: c }; - await hookSystem.execute(afterHook, afterData); - } - }; - } - /** - * Create a debounced hook handler - */ - static debounce(handler, delay) { - let timeoutId; - return async (data, context) => { - if (timeoutId) { - clearTimeout(timeoutId); - } - return new Promise((resolve, reject) => { - timeoutId = setTimeout(async () => { - try { - const result = await handler(data, context); - resolve(result); - } catch (error) { - reject(error); - } - }, delay); - }); - }; - } - /** - * Create a throttled hook handler - */ - static throttle(handler, limit) { - let lastExecution = 0; - return async (data, context) => { - const now = Date.now(); - if (now - lastExecution >= limit) { - lastExecution = now; - return handler(data, context); - } - return data; - }; - } -}; - -// src/plugins/plugin-validator.ts -var import_semver = chunkIGJUBJBW_cjs.__toESM(require_semver2(), 1); -var PluginAuthorSchema = zod.z.object({ - name: zod.z.string().min(1), - email: zod.z.string().email().optional(), - url: zod.z.string().url().optional() -}); -var PluginRoutesSchema = zod.z.object({ - path: zod.z.string().min(1), - handler: zod.z.any(), - // Hono instance - description: zod.z.string().optional(), - requiresAuth: zod.z.boolean().optional(), - roles: zod.z.array(zod.z.string()).optional(), - priority: zod.z.number().optional() -}); -var PluginMiddlewareSchema = zod.z.object({ - name: zod.z.string().min(1), - handler: zod.z.function(), - description: zod.z.string().optional(), - priority: zod.z.number().optional(), - routes: zod.z.array(zod.z.string()).optional(), - global: zod.z.boolean().optional() -}); -var PluginModelSchema = zod.z.object({ - name: zod.z.string().min(1), - tableName: zod.z.string().min(1), - schema: zod.z.any(), - // Zod schema - migrations: zod.z.array(zod.z.string()), - relationships: zod.z.array(zod.z.object({ - type: zod.z.enum(["oneToOne", "oneToMany", "manyToMany"]), - target: zod.z.string(), - foreignKey: zod.z.string().optional(), - joinTable: zod.z.string().optional() - })).optional(), - extendsContent: zod.z.boolean().optional() -}); -var PluginServiceSchema = zod.z.object({ - name: zod.z.string().min(1), - implementation: zod.z.any(), - description: zod.z.string().optional(), - dependencies: zod.z.array(zod.z.string()).optional(), - singleton: zod.z.boolean().optional() -}); -var PluginAdminPageSchema = zod.z.object({ - path: zod.z.string().min(1), - title: zod.z.string().min(1), - component: zod.z.string().min(1), - description: zod.z.string().optional(), - permissions: zod.z.array(zod.z.string()).optional(), - menuItem: zod.z.object({ - label: zod.z.string(), - path: zod.z.string(), - icon: zod.z.string().optional(), - order: zod.z.number().optional(), - parent: zod.z.string().optional(), - permissions: zod.z.array(zod.z.string()).optional(), - active: zod.z.boolean().optional() - }).optional(), - icon: zod.z.string().optional() -}); -var PluginComponentSchema = zod.z.object({ - name: zod.z.string().min(1), - template: zod.z.function(), - description: zod.z.string().optional(), - propsSchema: zod.z.any().optional() - // Zod schema -}); -var PluginHookSchema = zod.z.object({ - name: zod.z.string().min(1), - handler: zod.z.function(), - priority: zod.z.number().optional(), - description: zod.z.string().optional() -}); -var PluginSchema = zod.z.object({ - name: zod.z.string().min(1).regex(/^[a-z0-9-]+$/, "Plugin name must be lowercase with hyphens"), - version: zod.z.string().refine((v) => import_semver.default.valid(v), "Version must be valid semver"), - description: zod.z.string().optional(), - author: PluginAuthorSchema.optional(), - dependencies: zod.z.array(zod.z.string()).optional(), - compatibility: zod.z.string().optional(), - license: zod.z.string().optional(), - // Extension points - routes: zod.z.array(PluginRoutesSchema).optional(), - middleware: zod.z.array(PluginMiddlewareSchema).optional(), - models: zod.z.array(PluginModelSchema).optional(), - services: zod.z.array(PluginServiceSchema).optional(), - adminPages: zod.z.array(PluginAdminPageSchema).optional(), - adminComponents: zod.z.array(PluginComponentSchema).optional(), - menuItems: zod.z.array(zod.z.object({ - label: zod.z.string(), - path: zod.z.string(), - icon: zod.z.string().optional(), - order: zod.z.number().optional(), - parent: zod.z.string().optional(), - permissions: zod.z.array(zod.z.string()).optional(), - active: zod.z.boolean().optional() - })).optional(), - hooks: zod.z.array(PluginHookSchema).optional(), - // Lifecycle hooks - install: zod.z.function().optional(), - uninstall: zod.z.function().optional(), - activate: zod.z.function().optional(), - deactivate: zod.z.function().optional(), - configure: zod.z.function().optional() -}); -var PluginValidator = class _PluginValidator { - static RESERVED_NAMES = [ - "core", - "system", - "admin", - "api", - "auth", - "content", - "media", - "users", - "collections" - ]; - static RESERVED_PATHS = [ - "/admin", - "/api", - "/auth", - "/docs", - "/media", - "/_assets" - ]; - /** - * Validate plugin definition - */ - validate(plugin) { - const errors = []; - const warnings = []; - try { - const result = PluginSchema.safeParse(plugin); - if (!result.success) { - result.error.issues.forEach((err) => { - errors.push(`${err.path.join(".")}: ${err.message}`); - }); - } - if (_PluginValidator.RESERVED_NAMES.includes(plugin.name)) { - errors.push(`Plugin name "${plugin.name}" is reserved`); - } - if (plugin.routes) { - for (const route of plugin.routes) { - if (_PluginValidator.RESERVED_PATHS.some((path) => route.path.startsWith(path))) { - errors.push(`Route path "${route.path}" conflicts with reserved system path`); - } - if (!route.path.startsWith("/")) { - errors.push(`Route path "${route.path}" must start with /`); - } - } - } - if (plugin.models) { - const modelNames = /* @__PURE__ */ new Set(); - const tableNames = /* @__PURE__ */ new Set(); - for (const model of plugin.models) { - if (modelNames.has(model.name)) { - errors.push(`Duplicate model name: ${model.name}`); - } - modelNames.add(model.name); - if (tableNames.has(model.tableName)) { - errors.push(`Duplicate table name: ${model.tableName}`); - } - tableNames.add(model.tableName); - if (!/^[a-z][a-z0-9_]*$/.test(model.tableName)) { - errors.push(`Invalid table name format: ${model.tableName}`); - } - const systemTables = ["users", "collections", "content", "content_versions", "media", "api_tokens"]; - if (systemTables.includes(model.tableName)) { - errors.push(`Table name "${model.tableName}" conflicts with system table`); - } - } - } - if (plugin.services) { - const serviceNames = /* @__PURE__ */ new Set(); - for (const service of plugin.services) { - if (serviceNames.has(service.name)) { - errors.push(`Duplicate service name: ${service.name}`); - } - serviceNames.add(service.name); - const systemServices = ["auth", "content", "media", "cdn"]; - if (systemServices.includes(service.name)) { - warnings.push(`Service name "${service.name}" conflicts with system service`); - } - } - } - if (plugin.adminPages) { - const pagePaths = /* @__PURE__ */ new Set(); - for (const page of plugin.adminPages) { - if (pagePaths.has(page.path)) { - errors.push(`Duplicate admin page path: ${page.path}`); - } - pagePaths.add(page.path); - if (!page.path.startsWith("/")) { - errors.push(`Admin page path "${page.path}" must start with /`); - } - const systemPaths = ["/", "/collections", "/content", "/media", "/users", "/settings"]; - if (systemPaths.includes(page.path)) { - errors.push(`Admin page path "${page.path}" conflicts with system page`); - } - } - } - if (plugin.adminComponents) { - const componentNames = /* @__PURE__ */ new Set(); - for (const component of plugin.adminComponents) { - if (componentNames.has(component.name)) { - errors.push(`Duplicate component name: ${component.name}`); - } - componentNames.add(component.name); - const systemComponents = ["table", "form", "alert", "media-grid", "pagination"]; - if (systemComponents.includes(component.name)) { - warnings.push(`Component name "${component.name}" conflicts with system component`); - } - } - } - if (plugin.hooks) { - for (const hook of plugin.hooks) { - if (!hook.name.includes(":")) { - warnings.push(`Hook name "${hook.name}" should include namespace (e.g., "plugin:event")`); - } - } - } - if (plugin.dependencies?.includes(plugin.name)) { - errors.push(`Plugin cannot depend on itself`); - } - if (plugin.license) { - const validLicenses = ["MIT", "Apache-2.0", "GPL-3.0", "BSD-3-Clause", "ISC"]; - if (!validLicenses.includes(plugin.license)) { - warnings.push(`License "${plugin.license}" is not a common SPDX identifier`); - } - } - if (plugin.middleware && plugin.middleware.length > 5) { - warnings.push(`Plugin defines ${plugin.middleware.length} middleware functions, consider consolidating`); - } - if (plugin.hooks && plugin.hooks.length > 10) { - warnings.push(`Plugin defines ${plugin.hooks.length} hooks, ensure they are necessary`); - } - } catch (error) { - errors.push(`Validation error: ${error instanceof Error ? error.message : String(error)}`); - } - return { - valid: errors.length === 0, - errors, - warnings - }; - } - /** - * Validate plugin dependencies - */ - validateDependencies(plugin, registry) { - const errors = []; - const warnings = []; - if (!plugin.dependencies || plugin.dependencies.length === 0) { - return { valid: true, errors, warnings }; - } - for (const depName of plugin.dependencies) { - if (!registry.has(depName)) { - errors.push(`Dependency "${depName}" is not registered`); - continue; - } - const dependency = registry.get(depName); - if (dependency.compatibility && plugin.compatibility) { - if (!this.isCompatible(dependency.compatibility, plugin.compatibility)) { - warnings.push(`Potential compatibility issue with dependency "${depName}"`); - } - } - } - const visited = /* @__PURE__ */ new Set(); - const visiting = /* @__PURE__ */ new Set(); - const checkCircular = (name) => { - if (visiting.has(name)) return true; - if (visited.has(name)) return false; - visiting.add(name); - const current = registry.get(name); - if (current?.dependencies) { - for (const depName of current.dependencies) { - if (checkCircular(depName)) { - errors.push(`Circular dependency detected: ${name} -> ${depName}`); - return true; - } - } - } - visiting.delete(name); - visited.add(name); - return false; - }; - checkCircular(plugin.name); - return { - valid: errors.length === 0, - errors, - warnings - }; - } - /** - * Validate plugin compatibility with SonicJS version - */ - validateCompatibility(plugin, sonicVersion) { - const errors = []; - const warnings = []; - if (!plugin.compatibility) { - warnings.push("Plugin does not specify compatibility version"); - return { valid: true, errors, warnings }; - } - try { - if (!import_semver.default.satisfies(sonicVersion, plugin.compatibility)) { - errors.push(`Plugin requires SonicJS ${plugin.compatibility}, but current version is ${sonicVersion}`); - } - } catch (error) { - errors.push(`Invalid compatibility version format: ${plugin.compatibility}`); - } - return { - valid: errors.length === 0, - errors, - warnings - }; - } - /** - * Check if two version ranges are compatible - */ - isCompatible(version1, version2) { - try { - return import_semver.default.intersects(version1, version2); - } catch { - return false; - } - } - /** - * Validate plugin security constraints - */ - validateSecurity(plugin) { - const errors = []; - const warnings = []; - const pluginCode = JSON.stringify(plugin); - if (pluginCode.includes("eval(") || pluginCode.includes("Function(")) { - errors.push("Plugin contains potentially dangerous code execution patterns"); - } - if (pluginCode.includes("fs.") || pluginCode.includes("require(")) { - warnings.push("Plugin may attempt file system access (not available in Cloudflare Workers)"); - } - if (pluginCode.includes("fetch(") || pluginCode.includes("XMLHttpRequest")) { - warnings.push("Plugin contains network access code - ensure it follows security guidelines"); - } - const sensitivePatterns = ["password", "secret", "key", "token", "credential"]; - for (const pattern of sensitivePatterns) { - if (pluginCode.toLowerCase().includes(pattern)) { - warnings.push(`Plugin code contains "${pattern}" - ensure sensitive data is properly handled`); - } - } - return { - valid: errors.length === 0, - errors, - warnings - }; - } -}; - -// src/plugins/plugin-registry.ts -var PluginRegistryImpl = class { - plugins = /* @__PURE__ */ new Map(); - configs = /* @__PURE__ */ new Map(); - statuses = /* @__PURE__ */ new Map(); - validator; - constructor(validator) { - this.validator = validator || new PluginValidator(); - } - /** - * Get plugin by name - */ - get(name) { - return this.plugins.get(name); - } - /** - * Get all registered plugins - */ - getAll() { - return Array.from(this.plugins.values()); - } - /** - * Get active plugins - */ - getActive() { - return this.getAll().filter((plugin) => { - const status = this.statuses.get(plugin.name); - return status?.active === true; - }); - } - /** - * Register a plugin - */ - async register(plugin) { - console.info(`Registering plugin: ${plugin.name} v${plugin.version}`); - const validation = this.validator.validate(plugin); - if (!validation.valid) { - throw new Error(`Plugin validation failed for ${plugin.name}: ${validation.errors.join(", ")}`); - } - if (this.plugins.has(plugin.name)) { - const existingPlugin = this.plugins.get(plugin.name); - if (existingPlugin.version !== plugin.version) { - console.warn(`Plugin ${plugin.name} is already registered with version ${existingPlugin.version}, replacing with ${plugin.version}`); - } - } - const depValidation = this.validator.validateDependencies(plugin, this); - if (!depValidation.valid) { - throw new Error(`Plugin dependency validation failed for ${plugin.name}: ${depValidation.errors.join(", ")}`); - } - this.plugins.set(plugin.name, plugin); - this.statuses.set(plugin.name, { - name: plugin.name, - version: plugin.version, - active: false, - installed: true, - hasErrors: false, - errors: [] - }); - console.info(`Plugin registered successfully: ${plugin.name}`); - } - /** - * Unregister a plugin - */ - async unregister(name) { - console.info(`Unregistering plugin: ${name}`); - if (!this.plugins.has(name)) { - throw new Error(`Plugin not found: ${name}`); - } - const dependents = this.getDependents(name); - if (dependents.length > 0) { - throw new Error(`Cannot unregister ${name}: plugins ${dependents.join(", ")} depend on it`); - } - this.plugins.delete(name); - this.configs.delete(name); - this.statuses.delete(name); - console.info(`Plugin unregistered: ${name}`); - } - /** - * Check if plugin is registered - */ - has(name) { - return this.plugins.has(name); - } - /** - * Activate a plugin - */ - async activate(name) { - console.info(`Activating plugin: ${name}`); - const plugin = this.plugins.get(name); - if (!plugin) { - throw new Error(`Plugin not found: ${name}`); - } - const status = this.statuses.get(name); - if (status?.active) { - console.warn(`Plugin ${name} is already active`); - return; - } - try { - if (plugin.dependencies) { - for (const depName of plugin.dependencies) { - const depStatus = this.statuses.get(depName); - if (!depStatus?.active) { - await this.activate(depName); - } - } - } - this.updateStatus(name, { - active: true, - hasErrors: false, - errors: [] - }); - console.info(`Plugin activated: ${name}`); - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - this.updateStatus(name, { - active: false, - hasErrors: true, - errors: [errorMessage], - lastError: errorMessage - }); - throw new Error(`Failed to activate plugin ${name}: ${errorMessage}`); - } - } - /** - * Deactivate a plugin - */ - async deactivate(name) { - console.info(`Deactivating plugin: ${name}`); - const plugin = this.plugins.get(name); - if (!plugin) { - throw new Error(`Plugin not found: ${name}`); - } - const status = this.statuses.get(name); - if (!status?.active) { - console.warn(`Plugin ${name} is not active`); - return; - } - try { - const dependents = this.getDependents(name); - for (const depName of dependents) { - const depStatus = this.statuses.get(depName); - if (depStatus?.active) { - await this.deactivate(depName); - } - } - this.updateStatus(name, { - active: false, - hasErrors: false, - errors: [] - }); - console.info(`Plugin deactivated: ${name}`); - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - this.updateStatus(name, { - hasErrors: true, - errors: [errorMessage], - lastError: errorMessage - }); - throw new Error(`Failed to deactivate plugin ${name}: ${errorMessage}`); - } - } - /** - * Get plugin configuration - */ - getConfig(name) { - return this.configs.get(name); - } - /** - * Set plugin configuration - */ - setConfig(name, config) { - this.configs.set(name, { - ...config, - updatedAt: Date.now() - }); - } - /** - * Get plugin status - */ - getStatus(name) { - return this.statuses.get(name); - } - /** - * Get all plugin statuses - */ - getAllStatuses() { - return new Map(this.statuses); - } - /** - * Update plugin status - */ - updateStatus(name, updates) { - const current = this.statuses.get(name); - if (current) { - this.statuses.set(name, { ...current, ...updates }); - } - } - /** - * Get plugins that depend on the specified plugin - */ - getDependents(name) { - const dependents = []; - for (const [pluginName, plugin] of this.plugins) { - if (plugin.dependencies?.includes(name)) { - dependents.push(pluginName); - } - } - return dependents; - } - /** - * Get dependency graph - */ - getDependencyGraph() { - const graph = /* @__PURE__ */ new Map(); - for (const [name, plugin] of this.plugins) { - graph.set(name, plugin.dependencies || []); - } - return graph; - } - /** - * Resolve plugin load order based on dependencies - */ - resolveLoadOrder() { - const graph = this.getDependencyGraph(); - const visited = /* @__PURE__ */ new Set(); - const visiting = /* @__PURE__ */ new Set(); - const result = []; - const visit = (name) => { - if (visited.has(name)) return; - if (visiting.has(name)) { - throw new Error(`Circular dependency detected involving plugin: ${name}`); - } - visiting.add(name); - const dependencies = graph.get(name) || []; - for (const dep of dependencies) { - if (!graph.has(dep)) { - throw new Error(`Plugin ${name} depends on ${dep}, but ${dep} is not registered`); - } - visit(dep); - } - visiting.delete(name); - visited.add(name); - result.push(name); - }; - for (const name of graph.keys()) { - visit(name); - } - return result; - } - /** - * Export plugin configuration - */ - exportConfig() { - const plugins = []; - for (const [name, config] of this.configs) { - plugins.push({ - ...config, - name - }); - } - return { plugins }; - } - /** - * Import plugin configuration - */ - importConfig(config) { - for (const pluginConfig of config.plugins) { - if ("name" in pluginConfig) { - const { name, ...rest } = pluginConfig; - this.setConfig(name, rest); - } - } - } - /** - * Clear all plugins (useful for testing) - */ - clear() { - this.plugins.clear(); - this.configs.clear(); - this.statuses.clear(); - } - /** - * Get registry statistics - */ - getStats() { - const statuses = Array.from(this.statuses.values()); - return { - total: statuses.length, - active: statuses.filter((s) => s.active).length, - inactive: statuses.filter((s) => !s.active).length, - withErrors: statuses.filter((s) => s.hasErrors).length - }; - } -}; -var PluginManager = class { - registry; - hooks; - validator; - context; - scopedHooks = /* @__PURE__ */ new Map(); - pluginRoutes = /* @__PURE__ */ new Map(); - constructor() { - this.validator = new PluginValidator(); - this.registry = new PluginRegistryImpl(this.validator); - this.hooks = new HookSystemImpl(); - } - /** - * Initialize plugin system - */ - async initialize(context) { - console.info("Initializing plugin system..."); - this.context = context; - await this.hooks.execute(chunkKYGRJCZM_cjs.HOOKS.APP_INIT, { - pluginManager: this, - context - }); - console.info("Plugin system initialized"); - } - /** - * Load plugins from configuration - */ - async loadPlugins(configs) { - console.info(`Loading ${configs.length} plugins...`); - const enabledConfigs = configs.filter((config) => config.enabled); - if (enabledConfigs.length === 0) { - console.info("No enabled plugins to load"); - return; - } - for (const config of enabledConfigs) { - try { - console.info(`Loading plugin configuration: ${JSON.stringify(config)}`); - if ("name" in config) { - this.registry.setConfig(config.name, config); - } - } catch (error) { - console.error(`Failed to load plugin configuration:`, error); - } - } - try { - const loadOrder = this.registry.resolveLoadOrder(); - console.info(`Plugin load order: ${loadOrder.join(" -> ")}`); - for (const pluginName of loadOrder) { - const config = this.registry.getConfig(pluginName); - if (config?.enabled) { - await this.registry.activate(pluginName); - } - } - } catch (error) { - console.error("Failed to resolve plugin load order:", error); - } - console.info("Plugin loading completed"); - } - /** - * Install a plugin - */ - async install(plugin, config) { - console.info(`Installing plugin: ${plugin.name}`); - if (!this.context) { - throw new Error("Plugin manager not initialized"); - } - try { - const validation = this.validator.validate(plugin); - if (!validation.valid) { - throw new Error(`Plugin validation failed: ${validation.errors.join(", ")}`); - } - await this.registry.register(plugin); - const pluginConfig = { - enabled: true, - installedAt: Date.now(), - ...config - }; - this.registry.setConfig(plugin.name, pluginConfig); - const scopedHooks = this.hooks.createScope ? this.hooks.createScope(plugin.name) : this.hooks; - this.scopedHooks.set(plugin.name, scopedHooks); - const pluginContext = { - ...this.context, - config: pluginConfig, - hooks: scopedHooks, - logger: this.createLogger(plugin.name) - }; - await this.registerPluginExtensions(plugin, pluginContext); - if (plugin.install) { - await plugin.install(pluginContext); - } - await this.hooks.execute(chunkKYGRJCZM_cjs.HOOKS.PLUGIN_INSTALL, { - plugin: plugin.name, - version: plugin.version, - context: pluginContext - }); - console.info(`Plugin installed successfully: ${plugin.name}`); - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - console.error(`Failed to install plugin ${plugin.name}:`, errorMessage); - const status = this.registry.getStatus(plugin.name); - if (status) { - this.updatePluginStatus(plugin.name, { - hasErrors: true, - errors: [...status.errors || [], errorMessage], - lastError: errorMessage - }); - } - throw error; - } - } - /** - * Uninstall a plugin - */ - async uninstall(name) { - console.info(`Uninstalling plugin: ${name}`); - const plugin = this.registry.get(name); - if (!plugin) { - throw new Error(`Plugin not found: ${name}`); - } - if (!this.context) { - throw new Error("Plugin manager not initialized"); - } - try { - const status = this.registry.getStatus(name); - if (status?.active) { - await this.registry.deactivate(name); - } - const config = this.registry.getConfig(name) || { enabled: false }; - const pluginContext = { - ...this.context, - config, - hooks: this.scopedHooks.get(name) || this.hooks, - logger: this.createLogger(name) - }; - if (plugin.uninstall) { - await plugin.uninstall(pluginContext); - } - await this.unregisterPluginExtensions(plugin); - const scopedHooks = this.scopedHooks.get(name); - if (scopedHooks && "unregisterAll" in scopedHooks) { - scopedHooks.unregisterAll(); - } - this.scopedHooks.delete(name); - this.pluginRoutes.delete(name); - await this.hooks.execute(chunkKYGRJCZM_cjs.HOOKS.PLUGIN_UNINSTALL, { - plugin: name, - context: pluginContext - }); - await this.registry.unregister(name); - console.info(`Plugin uninstalled successfully: ${name}`); - } catch (error) { - const errorMessage = error instanceof Error ? error.message : String(error); - console.error(`Failed to uninstall plugin ${name}:`, errorMessage); - throw error; - } - } - /** - * Get plugin status - */ - getStatus(name) { - const status = this.registry.getStatus(name); - if (!status) { - return { - name, - version: "unknown", - active: false, - installed: false, - hasErrors: false - }; - } - return status; - } - /** - * Get all plugin statuses - */ - getAllStatuses() { - return Array.from(this.registry.getAllStatuses().values()); - } - /** - * Register plugin extensions (routes, middleware, etc.) - */ - async registerPluginExtensions(plugin, _context) { - if (plugin.routes) { - const pluginApp = new hono.Hono(); - for (const route of plugin.routes) { - console.debug(`Registering plugin route: ${route.path}`); - pluginApp.route(route.path, route.handler); - } - this.pluginRoutes.set(plugin.name, pluginApp); - } - if (plugin.middleware) { - for (const middleware of plugin.middleware) { - console.debug(`Registering plugin middleware: ${middleware.name}`); - } - } - if (plugin.hooks) { - const scopedHooks = this.scopedHooks.get(plugin.name); - for (const hook of plugin.hooks) { - console.debug(`Registering plugin hook: ${hook.name}`); - if (scopedHooks) { - scopedHooks.register(hook.name, hook.handler, hook.priority); - } else { - this.hooks.register(hook.name, hook.handler, hook.priority); - } - } - } - if (plugin.services) { - for (const service of plugin.services) { - console.debug(`Registering plugin service: ${service.name}`); - } - } - if (plugin.models) { - for (const model of plugin.models) { - console.debug(`Registering plugin model: ${model.name}`); - } - } - } - /** - * Unregister plugin extensions - */ - async unregisterPluginExtensions(plugin) { - console.debug(`Unregistering extensions for plugin: ${plugin.name}`); - } - /** - * Update plugin status - */ - updatePluginStatus(name, updates) { - const current = this.registry.getStatus(name); - if (current && "updateStatus" in this.registry) { - console.debug(`Updating status for plugin: ${name}`, updates); - } - } - /** - * Create a logger for a plugin - */ - createLogger(pluginName) { - return { - debug: (message, data) => { - console.debug(`[Plugin:${pluginName}] ${message}`, data || ""); - }, - info: (message, data) => { - console.info(`[Plugin:${pluginName}] ${message}`, data || ""); - }, - warn: (message, data) => { - console.warn(`[Plugin:${pluginName}] ${message}`, data || ""); - }, - error: (message, error, data) => { - console.error(`[Plugin:${pluginName}] ${message}`, error || "", data || ""); - } - }; - } - /** - * Get plugin routes for mounting in main app - */ - getPluginRoutes() { - return new Map(this.pluginRoutes); - } - /** - * Get plugin middleware for main app - */ - getPluginMiddleware() { - const middleware = []; - for (const plugin of this.registry.getActive()) { - if (plugin.middleware) { - for (const mw of plugin.middleware) { - middleware.push({ - name: `${plugin.name}:${mw.name}`, - handler: mw.handler, - priority: mw.priority || 10, - global: mw.global || false - }); - } - } - } - return middleware.sort((a, b) => a.priority - b.priority); - } - /** - * Execute shutdown procedures - */ - async shutdown() { - console.info("Shutting down plugin system..."); - await this.hooks.execute(chunkKYGRJCZM_cjs.HOOKS.APP_SHUTDOWN, { - pluginManager: this - }); - const activePlugins = this.registry.getActive(); - for (const plugin of activePlugins.reverse()) { - try { - await this.registry.deactivate(plugin.name); - } catch (error) { - console.error(`Error deactivating plugin ${plugin.name}:`, error); - } - } - console.info("Plugin system shutdown completed"); - } - /** - * Get plugin system statistics - */ - getStats() { - return { - registry: this.registry.getStats(), - hooks: this.hooks.getStats(), - routes: this.pluginRoutes.size, - middleware: this.getPluginMiddleware().length - }; - } -}; - -// src/plugins/core-plugins/turnstile-plugin/middleware/verify.ts -async function verifyTurnstile(c, next) { - const db = c.get("db") || c.env?.DB; - if (!db) { - console.error("Turnstile middleware: Database not available"); - return c.json({ error: "Database not available" }, 500); - } - const turnstileService = new chunk6FHNRRJ3_cjs.TurnstileService(db); - const isEnabled = await turnstileService.isEnabled(); - if (!isEnabled) { - return next(); - } - let token; - let body; - if (c.req.method === "POST") { - const contentType = c.req.header("content-type") || ""; - if (contentType.includes("application/json")) { - body = await c.req.json(); - token = body["cf-turnstile-response"] || body["turnstile-token"]; - c.set("requestBody", body); - } else if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) { - const formData = await c.req.formData(); - token = formData.get("cf-turnstile-response")?.toString() || formData.get("turnstile-token")?.toString(); - } - } - if (!token) { - return c.json({ - error: "Turnstile token missing", - message: "Please complete the verification challenge" - }, 400); - } - const remoteIp = c.req.header("cf-connecting-ip") || c.req.header("x-forwarded-for"); - const result = await turnstileService.verifyToken(token, remoteIp); - if (!result.success) { - return c.json({ - error: "Turnstile verification failed", - message: result.error || "Verification failed. Please try again." - }, 403); - } - return next(); -} -function createTurnstileMiddleware(options) { - return async (c, next) => { - const db = c.get("db") || c.env?.DB; - if (!db) { - return options?.onError?.(c, "Database not available") || c.json({ error: "Database not available" }, 500); - } - const turnstileService = new chunk6FHNRRJ3_cjs.TurnstileService(db); - const isEnabled = await turnstileService.isEnabled(); - if (!isEnabled) { - return next(); - } - let token; - const contentType = c.req.header("content-type") || ""; - if (contentType.includes("application/json")) { - const body = await c.req.json(); - token = body["cf-turnstile-response"] || body["turnstile-token"]; - c.set("requestBody", body); - } else if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) { - const formData = await c.req.formData(); - token = formData.get("cf-turnstile-response")?.toString() || formData.get("turnstile-token")?.toString(); - } - if (!token) { - return options?.onMissing?.(c) || c.json({ error: "Turnstile token missing" }, 400); - } - const remoteIp = c.req.header("cf-connecting-ip") || c.req.header("x-forwarded-for"); - const result = await turnstileService.verifyToken(token, remoteIp); - if (!result.success) { - return options?.onError?.(c, result.error || "Verification failed") || c.json({ error: "Turnstile verification failed", message: result.error }, 403); - } - return next(); - }; -} - -// src/plugins/core-plugins/turnstile-plugin/index.ts -new chunk6FHNRRJ3_cjs.PluginBuilder({ - name: chunk6FHNRRJ3_cjs.manifest_default.name, - version: chunk6FHNRRJ3_cjs.manifest_default.version, - description: chunk6FHNRRJ3_cjs.manifest_default.description, - author: { name: chunk6FHNRRJ3_cjs.manifest_default.author } -}).metadata({ - description: chunk6FHNRRJ3_cjs.manifest_default.description, - author: { name: chunk6FHNRRJ3_cjs.manifest_default.author } -}).addService("turnstile", chunk6FHNRRJ3_cjs.TurnstileService).addSingleMiddleware("verifyTurnstile", verifyTurnstile, { - description: "Verify Cloudflare Turnstile token", - global: false -}).build(); - -exports.HookSystemImpl = HookSystemImpl; -exports.HookUtils = HookUtils; -exports.PluginManager = PluginManager; -exports.PluginRegistryImpl = PluginRegistryImpl; -exports.PluginValidator = PluginValidator; -exports.ScopedHookSystem = ScopedHookSystem; -exports.createTurnstileMiddleware = createTurnstileMiddleware; -exports.verifyTurnstile = verifyTurnstile; -//# sourceMappingURL=chunk-MNFY6DWY.cjs.map -//# sourceMappingURL=chunk-MNFY6DWY.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-MPT5PA6U.cjs b/packages/core/dist/chunk-MPT5PA6U.cjs deleted file mode 100644 index 7178b252b..000000000 --- a/packages/core/dist/chunk-MPT5PA6U.cjs +++ /dev/null @@ -1,833 +0,0 @@ -'use strict'; - -// src/services/collection-loader.ts -var registeredCollections = []; -function registerCollections(collections) { - for (const config of collections) { - if (!config.name || !config.displayName || !config.schema) { - console.error(`Invalid collection config: missing required fields`, config); - continue; - } - const normalizedConfig = { - ...config, - managed: config.managed !== void 0 ? config.managed : true, - isActive: config.isActive !== void 0 ? config.isActive : true - }; - registeredCollections.push(normalizedConfig); - console.log(`\u2713 Registered collection: ${config.name}`); - } -} -async function loadCollectionConfigs() { - const collections = [...registeredCollections]; - if (registeredCollections.length > 0) { - console.log(`\u{1F4E6} Found ${registeredCollections.length} registered collection(s) from application`); - } else { - console.log(`\u26A0\uFE0F No collections registered. Make sure to call registerCollections() in your app's index.ts`); - console.log(` Example: import myCollection from './collections/my-collection.collection'`); - console.log(` registerCollections([myCollection])`); - } - try { - const modules = undefined?.("../collections/*.collection.ts", { eager: true }) || {}; - let coreCollectionCount = 0; - for (const [path, module] of Object.entries(modules)) { - try { - const configModule = module; - if (!configModule.default) { - console.warn(`Collection file ${path} does not export a default config`); - continue; - } - const config = configModule.default; - if (!config.name || !config.displayName || !config.schema) { - console.error(`Invalid collection config in ${path}: missing required fields`); - continue; - } - const normalizedConfig = { - ...config, - managed: config.managed !== void 0 ? config.managed : true, - isActive: config.isActive !== void 0 ? config.isActive : true - }; - collections.push(normalizedConfig); - coreCollectionCount++; - console.log(`\u2713 Loaded core collection: ${config.name}`); - } catch (error) { - console.error(`Error loading collection from ${path}:`, error); - } - } - console.log(`\u{1F4CA} Collection summary: ${collections.length} total (${registeredCollections.length} from app, ${coreCollectionCount} from core)`); - return collections; - } catch (error) { - console.error("Error loading collection configurations:", error); - return collections; - } -} -async function loadCollectionConfig(name) { - try { - console.warn("loadCollectionConfig requires implementation in consuming application"); - return null; - } catch (error) { - console.error(`Error loading collection ${name}:`, error); - return null; - } -} -async function getAvailableCollectionNames() { - try { - const modules = undefined?.("../collections/*.collection.ts") || {}; - const names = []; - for (const path of Object.keys(modules)) { - const match = path.match(/\/([^/]+)\.collection\.ts$/); - if (match && match[1]) { - names.push(match[1]); - } - } - return names; - } catch (error) { - console.error("Error getting collection names:", error); - return []; - } -} -function validateCollectionConfig(config) { - const errors = []; - if (!config.name) { - errors.push("Collection name is required"); - } else if (!/^[a-z0-9_-]+$/.test(config.name)) { - errors.push("Collection name must contain only lowercase letters, numbers, underscores, and hyphens"); - } - if (!config.displayName) { - errors.push("Display name is required"); - } - if (!config.schema) { - errors.push("Schema is required"); - } else { - if (config.schema.type !== "object") { - errors.push('Schema type must be "object"'); - } - if (!config.schema.properties || typeof config.schema.properties !== "object") { - errors.push("Schema must have properties"); - } - for (const [fieldName, fieldConfig] of Object.entries(config.schema.properties || {})) { - if (!fieldConfig.type) { - errors.push(`Field "${fieldName}" is missing type`); - } - if (fieldConfig.type === "reference" && !fieldConfig.collection) { - errors.push(`Reference field "${fieldName}" is missing collection property`); - } - if (["select", "multiselect", "radio"].includes(fieldConfig.type) && !fieldConfig.enum) { - errors.push(`Select field "${fieldName}" is missing enum options`); - } - } - } - return { - valid: errors.length === 0, - errors - }; -} - -// src/services/collection-sync.ts -async function syncCollections(db) { - console.log("\u{1F504} Starting collection sync..."); - const results = []; - const configs = await loadCollectionConfigs(); - if (configs.length === 0) { - console.log("\u26A0\uFE0F No collection configurations found"); - return results; - } - for (const config of configs) { - const result = await syncCollection(db, config); - results.push(result); - } - const created = results.filter((r) => r.status === "created").length; - const updated = results.filter((r) => r.status === "updated").length; - const unchanged = results.filter((r) => r.status === "unchanged").length; - const errors = results.filter((r) => r.status === "error").length; - console.log(`\u2705 Collection sync complete: ${created} created, ${updated} updated, ${unchanged} unchanged, ${errors} errors`); - return results; -} -async function syncCollection(db, config) { - try { - const validation = validateCollectionConfig(config); - if (!validation.valid) { - return { - name: config.name, - status: "error", - error: `Validation failed: ${validation.errors.join(", ")}` - }; - } - const existingStmt = db.prepare("SELECT * FROM collections WHERE name = ?"); - const existing = await existingStmt.bind(config.name).first(); - const now = Date.now(); - const collectionId = existing?.id || `col-${config.name}-${crypto.randomUUID().slice(0, 8)}`; - const schemaJson = JSON.stringify(config.schema); - const isActive = config.isActive !== false ? 1 : 0; - const managed = config.managed !== false ? 1 : 0; - if (!existing) { - const insertStmt = db.prepare(` - INSERT INTO collections (id, name, display_name, description, schema, is_active, managed, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await insertStmt.bind( - collectionId, - config.name, - config.displayName, - config.description || null, - schemaJson, - isActive, - managed, - now, - now - ).run(); - console.log(` \u2713 Created collection: ${config.name}`); - return { - name: config.name, - status: "created", - message: `Created collection "${config.displayName}"` - }; - } else { - const existingSchema = existing.schema ? JSON.stringify(existing.schema) : "{}"; - const existingDisplayName = existing.display_name; - const existingDescription = existing.description; - const existingIsActive = existing.is_active; - const existingManaged = existing.managed; - const needsUpdate = schemaJson !== existingSchema || config.displayName !== existingDisplayName || (config.description || null) !== existingDescription || isActive !== existingIsActive || managed !== existingManaged; - if (!needsUpdate) { - return { - name: config.name, - status: "unchanged", - message: `Collection "${config.displayName}" is up to date` - }; - } - const updateStmt = db.prepare(` - UPDATE collections - SET display_name = ?, description = ?, schema = ?, is_active = ?, managed = ?, updated_at = ? - WHERE name = ? - `); - await updateStmt.bind( - config.displayName, - config.description || null, - schemaJson, - isActive, - managed, - now, - config.name - ).run(); - console.log(` \u2713 Updated collection: ${config.name}`); - return { - name: config.name, - status: "updated", - message: `Updated collection "${config.displayName}"` - }; - } - } catch (error) { - console.error(` \u2717 Error syncing collection ${config.name}:`, error); - return { - name: config.name, - status: "error", - error: error instanceof Error ? error.message : "Unknown error" - }; - } -} -async function isCollectionManaged(db, collectionName) { - try { - const stmt = db.prepare("SELECT managed FROM collections WHERE name = ?"); - const result = await stmt.bind(collectionName).first(); - return result?.managed === 1; - } catch (error) { - console.error(`Error checking if collection is managed:`, error); - return false; - } -} -async function getManagedCollections(db) { - try { - const stmt = db.prepare("SELECT name FROM collections WHERE managed = 1"); - const { results } = await stmt.all(); - return (results || []).map((row) => row.name); - } catch (error) { - console.error("Error getting managed collections:", error); - return []; - } -} -async function cleanupRemovedCollections(db) { - try { - const configs = await loadCollectionConfigs(); - const configNames = new Set(configs.map((c) => c.name)); - const managedCollections = await getManagedCollections(db); - const removed = []; - for (const managedName of managedCollections) { - if (!configNames.has(managedName)) { - const updateStmt = db.prepare(` - UPDATE collections - SET is_active = 0, updated_at = ? - WHERE name = ? AND managed = 1 - `); - await updateStmt.bind(Date.now(), managedName).run(); - removed.push(managedName); - console.log(` \u26A0\uFE0F Deactivated removed collection: ${managedName}`); - } - } - return removed; - } catch (error) { - console.error("Error cleaning up removed collections:", error); - return []; - } -} -async function fullCollectionSync(db) { - const results = await syncCollections(db); - const removed = await cleanupRemovedCollections(db); - return { results, removed }; -} - -// src/services/plugin-service.ts -var PluginService = class { - constructor(db) { - this.db = db; - } - async getAllPlugins() { - await this.ensureAllPluginsExist(); - const stmt = this.db.prepare(` - SELECT * FROM plugins - ORDER BY is_core DESC, display_name ASC - `); - const { results } = await stmt.all(); - return (results || []).map(this.mapPluginFromDb); - } - /** - * Ensure all plugins from the registry exist in the database - * Auto-installs any newly detected plugins with inactive status - * - * Note: This method should be overridden or configured with a plugin registry - * in the consuming application - */ - async ensureAllPluginsExist() { - console.log("[PluginService] ensureAllPluginsExist - requires PLUGIN_REGISTRY configuration"); - } - async getPlugin(pluginId) { - const stmt = this.db.prepare("SELECT * FROM plugins WHERE id = ?"); - const plugin = await stmt.bind(pluginId).first(); - if (!plugin) return null; - return this.mapPluginFromDb(plugin); - } - async getPluginByName(name) { - const stmt = this.db.prepare("SELECT * FROM plugins WHERE name = ?"); - const plugin = await stmt.bind(name).first(); - if (!plugin) return null; - return this.mapPluginFromDb(plugin); - } - async getPluginStats() { - const stmt = this.db.prepare(` - SELECT - COUNT(*) as total, - COUNT(CASE WHEN status = 'active' THEN 1 END) as active, - COUNT(CASE WHEN status = 'inactive' THEN 1 END) as inactive, - COUNT(CASE WHEN status = 'error' THEN 1 END) as errors - FROM plugins - `); - const stats = await stmt.first(); - return { - total: stats.total || 0, - active: stats.active || 0, - inactive: stats.inactive || 0, - errors: stats.errors || 0, - uninstalled: 0 - }; - } - async installPlugin(pluginData) { - const id = pluginData.id || `plugin-${Date.now()}`; - const now = Math.floor(Date.now() / 1e3); - const stmt = this.db.prepare(` - INSERT INTO plugins ( - id, name, display_name, description, version, author, category, icon, - status, is_core, settings, permissions, dependencies, download_count, - rating, installed_at, last_updated - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await stmt.bind( - id, - pluginData.name || id, - pluginData.display_name || "Unnamed Plugin", - pluginData.description || "", - pluginData.version || "1.0.0", - pluginData.author || "Unknown", - pluginData.category || "utilities", - pluginData.icon || "\u{1F50C}", - "inactive", - pluginData.is_core || false, - JSON.stringify(pluginData.settings || {}), - JSON.stringify(pluginData.permissions || []), - JSON.stringify(pluginData.dependencies || []), - pluginData.download_count || 0, - pluginData.rating || 0, - now, - now - ).run(); - await this.logActivity(id, "installed", null, { version: pluginData.version }); - const installed = await this.getPlugin(id); - if (!installed) throw new Error("Failed to install plugin"); - return installed; - } - async uninstallPlugin(pluginId) { - const plugin = await this.getPlugin(pluginId); - if (!plugin) throw new Error("Plugin not found"); - if (plugin.is_core) throw new Error("Cannot uninstall core plugins"); - if (plugin.status === "active") { - await this.deactivatePlugin(pluginId); - } - const stmt = this.db.prepare("DELETE FROM plugins WHERE id = ?"); - await stmt.bind(pluginId).run(); - await this.logActivity(pluginId, "uninstalled", null, { name: plugin.name }); - } - async activatePlugin(pluginId) { - const plugin = await this.getPlugin(pluginId); - if (!plugin) throw new Error("Plugin not found"); - if (plugin.dependencies && plugin.dependencies.length > 0) { - await this.checkDependencies(plugin.dependencies); - } - const now = Math.floor(Date.now() / 1e3); - const stmt = this.db.prepare(` - UPDATE plugins - SET status = 'active', activated_at = ?, error_message = NULL - WHERE id = ? - `); - await stmt.bind(now, pluginId).run(); - await this.logActivity(pluginId, "activated", null); - } - async deactivatePlugin(pluginId) { - const plugin = await this.getPlugin(pluginId); - if (!plugin) throw new Error("Plugin not found"); - await this.checkDependents(plugin.name); - const stmt = this.db.prepare(` - UPDATE plugins - SET status = 'inactive', activated_at = NULL - WHERE id = ? - `); - await stmt.bind(pluginId).run(); - await this.logActivity(pluginId, "deactivated", null); - } - async updatePluginSettings(pluginId, settings) { - const plugin = await this.getPlugin(pluginId); - if (!plugin) throw new Error("Plugin not found"); - const stmt = this.db.prepare(` - UPDATE plugins - SET settings = ?, updated_at = unixepoch() - WHERE id = ? - `); - await stmt.bind(JSON.stringify(settings), pluginId).run(); - await this.logActivity(pluginId, "settings_updated", null); - } - async setPluginError(pluginId, error) { - const stmt = this.db.prepare(` - UPDATE plugins - SET status = 'error', error_message = ? - WHERE id = ? - `); - await stmt.bind(error, pluginId).run(); - await this.logActivity(pluginId, "error", null, { error }); - } - async getPluginActivity(pluginId, limit = 10) { - const stmt = this.db.prepare(` - SELECT * FROM plugin_activity_log - WHERE plugin_id = ? - ORDER BY timestamp DESC - LIMIT ? - `); - const { results } = await stmt.bind(pluginId, limit).all(); - return (results || []).map((row) => ({ - id: row.id, - action: row.action, - userId: row.user_id, - details: row.details ? JSON.parse(row.details) : null, - timestamp: row.timestamp - })); - } - async registerHook(pluginId, hookName, handlerName, priority = 10) { - const id = `hook-${Date.now()}`; - const stmt = this.db.prepare(` - INSERT INTO plugin_hooks (id, plugin_id, hook_name, handler_name, priority) - VALUES (?, ?, ?, ?, ?) - `); - await stmt.bind(id, pluginId, hookName, handlerName, priority).run(); - } - async registerRoute(pluginId, path, method, handlerName, middleware) { - const id = `route-${Date.now()}`; - const stmt = this.db.prepare(` - INSERT INTO plugin_routes (id, plugin_id, path, method, handler_name, middleware) - VALUES (?, ?, ?, ?, ?, ?) - `); - await stmt.bind( - id, - pluginId, - path, - method, - handlerName, - JSON.stringify(middleware || []) - ).run(); - } - async getPluginHooks(pluginId) { - const stmt = this.db.prepare(` - SELECT * FROM plugin_hooks - WHERE plugin_id = ? AND is_active = TRUE - ORDER BY priority ASC - `); - const { results } = await stmt.bind(pluginId).all(); - return results || []; - } - async getPluginRoutes(pluginId) { - const stmt = this.db.prepare(` - SELECT * FROM plugin_routes - WHERE plugin_id = ? AND is_active = TRUE - `); - const { results } = await stmt.bind(pluginId).all(); - return results || []; - } - async checkDependencies(dependencies) { - for (const dep of dependencies) { - const plugin = await this.getPluginByName(dep); - if (!plugin || plugin.status !== "active") { - throw new Error(`Required dependency '${dep}' is not active`); - } - } - } - async checkDependents(pluginName) { - const stmt = this.db.prepare(` - SELECT id, display_name FROM plugins - WHERE status = 'active' - AND dependencies LIKE ? - `); - const { results } = await stmt.bind(`%"${pluginName}"%`).all(); - if (results && results.length > 0) { - const names = results.map((p) => p.display_name).join(", "); - throw new Error(`Cannot deactivate. The following plugins depend on this one: ${names}`); - } - } - async logActivity(pluginId, action, userId, details) { - const id = `activity-${Date.now()}`; - const stmt = this.db.prepare(` - INSERT INTO plugin_activity_log (id, plugin_id, action, user_id, details) - VALUES (?, ?, ?, ?, ?) - `); - await stmt.bind( - id, - pluginId, - action, - userId, - details ? JSON.stringify(details) : null - ).run(); - } - mapPluginFromDb(row) { - return { - id: row.id, - name: row.name, - display_name: row.display_name, - description: row.description, - version: row.version, - author: row.author, - category: row.category, - icon: row.icon, - status: row.status, - is_core: row.is_core === 1, - settings: row.settings ? JSON.parse(row.settings) : void 0, - permissions: row.permissions ? JSON.parse(row.permissions) : void 0, - dependencies: row.dependencies ? JSON.parse(row.dependencies) : void 0, - download_count: row.download_count || 0, - rating: row.rating || 0, - installed_at: row.installed_at, - activated_at: row.activated_at, - last_updated: row.last_updated, - error_message: row.error_message - }; - } -}; - -// src/services/plugin-bootstrap.ts -var PluginBootstrapService = class { - constructor(db) { - this.db = db; - this.pluginService = new PluginService(db); - } - pluginService; - /** - * Core plugins that should always be available in the system - */ - CORE_PLUGINS = [ - { - id: "core-auth", - name: "core-auth", - display_name: "Authentication System", - description: "Core authentication and user management system", - version: "1.0.0", - author: "SonicJS Team", - category: "security", - icon: "\u{1F510}", - permissions: ["manage:users", "manage:roles", "manage:permissions"], - dependencies: [], - settings: { - requiredFields: { - email: { required: true, minLength: 5, label: "Email", type: "email" }, - password: { required: true, minLength: 8, label: "Password", type: "password" }, - username: { required: true, minLength: 3, label: "Username", type: "text" }, - firstName: { required: true, minLength: 1, label: "First Name", type: "text" }, - lastName: { required: true, minLength: 1, label: "Last Name", type: "text" } - }, - validation: { - emailFormat: true, - allowDuplicateUsernames: false, - passwordRequirements: { - requireUppercase: false, - requireLowercase: false, - requireNumbers: false, - requireSpecialChars: false - } - }, - registration: { - enabled: true, - requireEmailVerification: false, - defaultRole: "viewer" - } - } - }, - { - id: "core-media", - name: "core-media", - display_name: "Media Manager", - description: "Core media upload and management system", - version: "1.0.0", - author: "SonicJS Team", - category: "media", - icon: "\u{1F4F8}", - permissions: ["manage:media", "upload:files"], - dependencies: [], - settings: {} - }, - { - id: "database-tools", - name: "database-tools", - display_name: "Database Tools", - description: "Database management tools including truncate, backup, and validation", - version: "1.0.0", - author: "SonicJS Team", - category: "system", - icon: "\u{1F5C4}\uFE0F", - permissions: ["manage:database", "admin"], - dependencies: [], - settings: { - enableTruncate: true, - enableBackup: true, - enableValidation: true, - requireConfirmation: true - } - }, - { - id: "seed-data", - name: "seed-data", - display_name: "Seed Data", - description: "Generate realistic example users and content for testing and development", - version: "1.0.0", - author: "SonicJS Team", - category: "development", - icon: "\u{1F331}", - permissions: ["admin"], - dependencies: [], - settings: { - userCount: 20, - contentCount: 200, - defaultPassword: "password123" - } - }, - { - id: "core-cache", - name: "core-cache", - display_name: "Cache System", - description: "Three-tiered caching system with memory, KV, and database layers", - version: "1.0.0", - author: "SonicJS Team", - category: "performance", - icon: "\u26A1", - permissions: ["manage:cache", "view:stats"], - dependencies: [], - settings: { - enableMemoryCache: true, - enableKVCache: true, - enableDatabaseCache: true, - defaultTTL: 3600 - } - }, - { - id: "workflow-plugin", - name: "workflow-plugin", - display_name: "Workflow Management", - description: "Content workflow management with approval chains, scheduling, and automation", - version: "1.0.0-beta.1", - author: "SonicJS Team", - category: "content", - icon: "\u{1F504}", - permissions: ["manage:workflows", "view:workflows", "transition:content"], - dependencies: ["content-plugin"], - settings: { - enableApprovalChains: true, - enableScheduling: true, - enableAutomation: true, - enableNotifications: true - } - }, - { - id: "easy-mdx", - name: "easy-mdx", - display_name: "EasyMDE Editor", - description: "Lightweight markdown editor with live preview for richtext fields", - version: "1.0.0", - author: "SonicJS Team", - category: "editor", - icon: "\u270D\uFE0F", - permissions: [], - dependencies: [], - settings: { - defaultHeight: 400, - toolbar: "full", - placeholder: "Start writing your content..." - } - }, - { - id: "ai-search", - name: "ai-search-plugin", - display_name: "AI Search", - description: "Advanced search with Cloudflare AI Search. Full-text search, semantic search, and advanced filtering across all content collections.", - version: "1.0.0", - author: "SonicJS Team", - category: "search", - icon: "\u{1F50D}", - permissions: ["settings:write", "admin:access", "content:read"], - dependencies: [], - settings: { - enabled: false, - ai_mode_enabled: true, - selected_collections: [], - dismissed_collections: [], - autocomplete_enabled: true, - cache_duration: 1, - results_limit: 20, - index_media: false - } - } - ]; - /** - * Bootstrap all core plugins - install them if they don't exist - */ - async bootstrapCorePlugins() { - console.log("[PluginBootstrap] Starting core plugin bootstrap process..."); - try { - for (const corePlugin of this.CORE_PLUGINS) { - await this.ensurePluginInstalled(corePlugin); - } - console.log( - "[PluginBootstrap] Core plugin bootstrap completed successfully" - ); - } catch (error) { - console.error("[PluginBootstrap] Error during plugin bootstrap:", error); - throw error; - } - } - /** - * Ensure a specific plugin is installed - */ - async ensurePluginInstalled(plugin) { - try { - const existingPlugin = await this.pluginService.getPlugin(plugin.id); - if (existingPlugin) { - console.log( - `[PluginBootstrap] Plugin already installed: ${plugin.display_name} (status: ${existingPlugin.status})` - ); - if (existingPlugin.version !== plugin.version) { - console.log( - `[PluginBootstrap] Updating plugin version: ${plugin.display_name} from ${existingPlugin.version} to ${plugin.version}` - ); - await this.updatePlugin(plugin); - } - if (plugin.id === "core-auth" && existingPlugin.status !== "active") { - console.log( - `[PluginBootstrap] Core-auth plugin is inactive, activating it now...` - ); - await this.pluginService.activatePlugin(plugin.id); - } - } else { - console.log( - `[PluginBootstrap] Installing plugin: ${plugin.display_name}` - ); - await this.pluginService.installPlugin({ - ...plugin, - is_core: plugin.name.startsWith("core-") - }); - if (plugin.name.startsWith("core-")) { - console.log( - `[PluginBootstrap] Activating newly installed core plugin: ${plugin.display_name}` - ); - await this.pluginService.activatePlugin(plugin.id); - } - } - } catch (error) { - console.error( - `[PluginBootstrap] Error ensuring plugin ${plugin.display_name}:`, - error - ); - } - } - /** - * Update an existing plugin - */ - async updatePlugin(plugin) { - const now = Math.floor(Date.now() / 1e3); - const stmt = this.db.prepare(` - UPDATE plugins - SET - version = ?, - description = ?, - permissions = ?, - settings = ?, - last_updated = ? - WHERE id = ? - `); - await stmt.bind( - plugin.version, - plugin.description, - JSON.stringify(plugin.permissions), - JSON.stringify(plugin.settings || {}), - now, - plugin.id - ).run(); - } - /** - * Check if bootstrap is needed (first run detection) - */ - async isBootstrapNeeded() { - try { - for (const corePlugin of this.CORE_PLUGINS.filter( - (p) => p.name.startsWith("core-") - )) { - const exists = await this.pluginService.getPlugin(corePlugin.id); - if (!exists) { - return true; - } - } - return false; - } catch (error) { - console.error( - "[PluginBootstrap] Error checking bootstrap status:", - error - ); - return true; - } - } -}; - -exports.PluginBootstrapService = PluginBootstrapService; -exports.PluginService = PluginService; -exports.cleanupRemovedCollections = cleanupRemovedCollections; -exports.fullCollectionSync = fullCollectionSync; -exports.getAvailableCollectionNames = getAvailableCollectionNames; -exports.getManagedCollections = getManagedCollections; -exports.isCollectionManaged = isCollectionManaged; -exports.loadCollectionConfig = loadCollectionConfig; -exports.loadCollectionConfigs = loadCollectionConfigs; -exports.registerCollections = registerCollections; -exports.syncCollection = syncCollection; -exports.syncCollections = syncCollections; -exports.validateCollectionConfig = validateCollectionConfig; -//# sourceMappingURL=chunk-MPT5PA6U.cjs.map -//# sourceMappingURL=chunk-MPT5PA6U.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-P3XDZL6Q.cjs b/packages/core/dist/chunk-P3XDZL6Q.cjs deleted file mode 100644 index 5017d9744..000000000 --- a/packages/core/dist/chunk-P3XDZL6Q.cjs +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; - -// src/utils/telemetry-config.ts -function safeGetEnv(key) { - try { - if (typeof process !== "undefined" && process.env) { - return process.env[key]; - } - } catch { - } - return void 0; -} -function getDefaultTelemetryConfig() { - return { - enabled: true, - host: safeGetEnv("SONICJS_TELEMETRY_ENDPOINT") || "https://stats.sonicjs.com", - debug: safeGetEnv("NODE_ENV") === "development" - }; -} -function isTelemetryEnabled() { - const telemetryEnv = safeGetEnv("SONICJS_TELEMETRY"); - if (telemetryEnv === "false" || telemetryEnv === "0" || telemetryEnv === "disabled") { - return false; - } - const doNotTrack = safeGetEnv("DO_NOT_TRACK"); - if (doNotTrack === "1" || doNotTrack === "true") { - return false; - } - return true; -} -function getTelemetryConfig() { - return { - ...getDefaultTelemetryConfig(), - enabled: isTelemetryEnabled() - }; -} -function shouldSkipEvent(eventName, sampleRate = 1) { - if (sampleRate >= 1) return false; - if (sampleRate <= 0) return true; - let hash = 0; - for (let i = 0; i < eventName.length; i++) { - hash = (hash << 5) - hash + eventName.charCodeAt(i); - hash = hash & hash; - } - return Math.abs(hash % 100) / 100 > sampleRate; -} - -// src/utils/telemetry-id.ts -function generateInstallationId() { - return crypto.randomUUID(); -} -function generateProjectId(projectName) { - let hash = 0; - for (let i = 0; i < projectName.length; i++) { - const char = projectName.charCodeAt(i); - hash = (hash << 5) - hash + char; - hash = hash & hash; - } - return `proj_${Math.abs(hash).toString(36)}`; -} -function sanitizeErrorMessage(error) { - const message = typeof error === "string" ? error : error.message; - const [errorTypeRaw] = message.split(":"); - const errorType = (errorTypeRaw || message).trim(); - const sanitized = errorType.replace(/\/Users\/[^/]+/g, "/Users/***").replace(/\/home\/[^/]+/g, "/home/***").replace(/C:\\Users\\[^\\]+/g, "C:\\Users\\***").replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, "***@***.***"); - return sanitized; -} -function sanitizeRoute(route) { - return route.replace(/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/gi, ":id").replace(/\/\d+/g, "/:id").replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, ":email"); -} - -exports.generateInstallationId = generateInstallationId; -exports.generateProjectId = generateProjectId; -exports.getDefaultTelemetryConfig = getDefaultTelemetryConfig; -exports.getTelemetryConfig = getTelemetryConfig; -exports.isTelemetryEnabled = isTelemetryEnabled; -exports.sanitizeErrorMessage = sanitizeErrorMessage; -exports.sanitizeRoute = sanitizeRoute; -exports.shouldSkipEvent = shouldSkipEvent; -//# sourceMappingURL=chunk-P3XDZL6Q.cjs.map -//# sourceMappingURL=chunk-P3XDZL6Q.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-RCQ2HIQD.cjs b/packages/core/dist/chunk-RCQ2HIQD.cjs deleted file mode 100644 index 4c80146ae..000000000 --- a/packages/core/dist/chunk-RCQ2HIQD.cjs +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -// src/utils/metrics.ts -var MetricsTracker = class { - requests = []; - windowSize = 1e4; - // 10 seconds window - /** - * Record a new request - */ - recordRequest() { - const now = Date.now(); - this.requests.push({ timestamp: now }); - this.cleanup(now); - } - /** - * Clean up old requests outside the window - */ - cleanup(now) { - const cutoff = now - this.windowSize; - this.requests = this.requests.filter((req) => req.timestamp > cutoff); - } - /** - * Get current requests per second - */ - getRequestsPerSecond() { - const now = Date.now(); - this.cleanup(now); - if (this.requests.length === 0) { - return 0; - } - const oneSecondAgo = now - 1e3; - const recentRequests = this.requests.filter((req) => req.timestamp > oneSecondAgo); - return recentRequests.length; - } - /** - * Get total requests in the current window - */ - getTotalRequests() { - const now = Date.now(); - this.cleanup(now); - return this.requests.length; - } - /** - * Get average requests per second over the window - */ - getAverageRPS() { - const now = Date.now(); - this.cleanup(now); - if (this.requests.length === 0) { - return 0; - } - const windowSeconds = this.windowSize / 1e3; - return this.requests.length / windowSeconds; - } -}; -var metricsTracker = new MetricsTracker(); - -exports.metricsTracker = metricsTracker; -//# sourceMappingURL=chunk-RCQ2HIQD.cjs.map -//# sourceMappingURL=chunk-RCQ2HIQD.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-S6K2H2TS.cjs b/packages/core/dist/chunk-S6K2H2TS.cjs deleted file mode 100644 index 9129cbdba..000000000 --- a/packages/core/dist/chunk-S6K2H2TS.cjs +++ /dev/null @@ -1,2470 +0,0 @@ -'use strict'; - -var chunkSHCYIZAN_cjs = require('./chunk-SHCYIZAN.cjs'); - -// src/templates/filter-bar.template.ts -function renderFilterBar(data) { - return ` -
-
- ${data.filters.map((filter) => ` -
- - -
- `).join("")} - - ${data.actions && data.actions.length > 0 ? ` -
- ${data.actions.map((action) => ` - - `).join("")} -
- ` : ""} -
- - -
- `; -} - -// src/templates/index.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -chunkSHCYIZAN_cjs.init_logo_template(); - -// src/templates/pages/admin-forms-docs.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderFormsDocsPage(data) { - const pageContent = ` - - -
- -

Forms Quick Reference

-

Comprehensive guide to all Form.io field types and features

-
- -
- - - - -
- - -
-
-

\u{1F4DA} Overview

-

Complete reference for SonicJS Forms powered by Form.io

-
- -
- \u{1F4A1} New to SonicJS Forms? Start with "Getting Started" in the sidebar, then explore the field types you need. -
- -

Key Features

-
-
- \u2713 Visual Builder -

Drag-and-drop interface

-
-
- \u2713 40+ Field Types -

Text, date, file, signature, etc.

-
-
- \u2713 Multi-Page Wizards -

Step-by-step forms

-
-
- \u2713 Headless API -

JSON schema & REST API

-
-
- \u2713 File Uploads -

Cloudflare R2 storage

-
-
- \u2713 100% Open Source -

No vendor lock-in

-
-
- -

Quick Links

- -
- - -
-
-

\u{1F680} Getting Started

-

Create your first form in 3 easy steps

-
- -
-

Step 1: Create a Form

-

Navigate to /admin/forms and click "Create Form"

-
- -
-

Step 2: Build Your Form

-

Drag and drop field types from the sidebar to build your form visually

-
- -
-

Step 3: Publish & Embed

-

Save your form and access it via:

-
    -
  • /forms/your-form-name - Public form page
  • -
  • /forms/your-form-name/schema - JSON schema API
  • -
  • /api/forms/:id/submit - Submission endpoint
  • -
-
-
- - -
-
-

\u{1F4DD} Text Field

-

Single-line text input for short text values

-
- -
-

Basic Usage

-

Most common field type for names, titles, and short text

-
{
-  "type": "textfield",
-  "key": "firstName",
-  "label": "First Name",
-  "placeholder": "Enter your first name",
-  "validate": {
-    "required": true,
-    "minLength": 2,
-    "maxLength": 50
-  }
-}
-
- -
- \u{1F4A1} Pro Tip: Use inputMask for formatted input like SSN or custom patterns. -
-
- - -
-
-

\u{1F4C4} Text Area

-

Multi-line text input for longer text content

-
- -
-

Basic Usage

-

Perfect for comments, descriptions, and multi-line text

-
{
-  "type": "textarea",
-  "key": "comments",
-  "label": "Additional Comments",
-  "placeholder": "Enter your comments here...",
-  "rows": 5,
-  "validate": {
-    "required": false,
-    "maxLength": 1000
-  }
-}
-
-
- - -
-
-

\u{1F522} Number

-

Numeric input with validation

-
- -
-

Basic Usage

-

For ages, quantities, scores, and any numeric value

-
{
-  "type": "number",
-  "key": "age",
-  "label": "Age",
-  "placeholder": "18",
-  "validate": {
-    "required": true,
-    "min": 18,
-    "max": 120
-  }
-}
-
-
- - -
-
-

\u{1F512} Password

-

Masked text input for sensitive data

-
- -
-

Basic Usage

-

Automatically masks input for security

-
{
-  "type": "password",
-  "key": "password",
-  "label": "Password",
-  "placeholder": "Enter password",
-  "validate": {
-    "required": true,
-    "minLength": 8,
-    "pattern": "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"
-  }
-}
-
-
- - -
-
-

\u{1F4E7} Email

-

Email input with automatic validation

-
- -
-

Basic Usage

-

Validates email format automatically

-
{
-  "type": "email",
-  "key": "email",
-  "label": "Email Address",
-  "placeholder": "you@example.com",
-  "validate": {
-    "required": true
-  }
-}
-
-
- - -
-
-

\u{1F310} URL

-

URL input with validation

-
- -
-

Basic Usage

-

Validates URL format (http/https)

-
{
-  "type": "url",
-  "key": "website",
-  "label": "Website",
-  "placeholder": "https://example.com",
-  "validate": {
-    "required": false
-  }
-}
-
-
- - -
-
-

\u{1F4DE} Phone Number

-

Phone number input with formatting

-
- -
-

Basic Usage

-

Automatically formats phone numbers

-
{
-  "type": "phoneNumber",
-  "key": "phone",
-  "label": "Phone Number",
-  "placeholder": "(555) 555-5555",
-  "validate": {
-    "required": true
-  }
-}
-
-
- - -
-
-

\u{1F4C5} Date/Time

-

Date and time picker

-
- -
-

Basic Usage

-

Interactive date/time picker with format control

-
{
-  "type": "datetime",
-  "key": "appointmentDateTime",
-  "label": "Appointment Date & Time",
-  "format": "yyyy-MM-dd hh:mm a",
-  "enableTime": true,
-  "validate": {
-    "required": true
-  }
-}
-
-
- - -
-
-

\u{1F4C6} Day

-

Day/Month/Year selector

-
- -
-

Basic Usage

-

Separate dropdowns for day, month, and year

-
{
-  "type": "day",
-  "key": "birthDate",
-  "label": "Date of Birth",
-  "fields": {
-    "day": { "placeholder": "Day" },
-    "month": { "placeholder": "Month" },
-    "year": { "placeholder": "Year" }
-  },
-  "validate": {
-    "required": true
-  }
-}
-
-
- - -
-
-

\u{1F550} Time

-

Time picker (hours and minutes)

-
- -
-

Basic Usage

-

Select time in HH:MM format

-
{
-  "type": "time",
-  "key": "preferredTime",
-  "label": "Preferred Contact Time",
-  "validate": {
-    "required": false
-  }
-}
-
-
- - -
-
-

\u{1F53D} Select Dropdown

-

Single selection dropdown

-
- -
-

Basic Usage

-

Choose one option from a list

-
{
-  "type": "select",
-  "key": "country",
-  "label": "Country",
-  "placeholder": "Select your country",
-  "data": {
-    "values": [
-      { "label": "United States", "value": "us" },
-      { "label": "Canada", "value": "ca" },
-      { "label": "United Kingdom", "value": "uk" },
-      { "label": "Australia", "value": "au" }
-    ]
-  },
-  "validate": {
-    "required": true
-  }
-}
-
-
- - -
-
-

\u2611\uFE0F Select Boxes

-

Multiple checkbox selections

-
- -
-

Basic Usage

-

Select multiple options with checkboxes

-
{
-  "type": "selectboxes",
-  "key": "interests",
-  "label": "Areas of Interest",
-  "values": [
-    { "label": "Sports", "value": "sports" },
-    { "label": "Music", "value": "music" },
-    { "label": "Technology", "value": "tech" },
-    { "label": "Travel", "value": "travel" }
-  ]
-}
-
-
- - -
-
-

\u{1F518} Radio

-

Single selection with radio buttons

-
- -
-

Basic Usage

-

Choose one option from radio buttons

-
{
-  "type": "radio",
-  "key": "gender",
-  "label": "Gender",
-  "values": [
-    { "label": "Male", "value": "male" },
-    { "label": "Female", "value": "female" },
-    { "label": "Non-binary", "value": "nonbinary" },
-    { "label": "Prefer not to say", "value": "other" }
-  ],
-  "validate": {
-    "required": true
-  }
-}
-
-
- - -
-
-

\u2705 Checkbox

-

Single checkbox for boolean values

-
- -
-

Basic Usage

-

For agreements, subscriptions, and yes/no options

-
{
-  "type": "checkbox",
-  "key": "newsletter",
-  "label": "Subscribe to newsletter",
-  "validate": {
-    "required": false
-  }
-}
-
-// Required checkbox (terms agreement)
-{
-  "type": "checkbox",
-  "key": "terms",
-  "label": "I agree to the terms and conditions",
-  "validate": {
-    "required": true
-  }
-}
-
-
- - -
-
-

\u{1F4B0} Currency

-

Formatted currency input

-
- -
-

Basic Usage

-

Automatically formats with currency symbol

-
{
-  "type": "currency",
-  "key": "salary",
-  "label": "Expected Salary",
-  "currency": "USD",
-  "placeholder": "$50,000",
-  "validate": {
-    "required": true,
-    "min": 0
-  }
-}
-
-
- - -
-
-

\u{1F3F7}\uFE0F Tags

-

Multi-value tag input

-
- -
-

Basic Usage

-

Type and press Enter to add tags

-
{
-  "type": "tags",
-  "key": "skills",
-  "label": "Skills",
-  "placeholder": "Type and press Enter (e.g. JavaScript, Python)",
-  "validate": {
-    "required": false
-  }
-}
-
-
- - -
-
-

\u{1F4CA} Survey

-

Matrix-style rating questions

-
- -
-

Basic Usage

-

Multiple questions with rating scale

-
{
-  "type": "survey",
-  "key": "satisfaction",
-  "label": "Customer Satisfaction Survey",
-  "questions": [
-    { "label": "Product Quality", "value": "quality" },
-    { "label": "Customer Service", "value": "service" },
-    { "label": "Value for Money", "value": "value" }
-  ],
-  "values": [
-    { "label": "Poor", "value": "1" },
-    { "label": "Fair", "value": "2" },
-    { "label": "Good", "value": "3" },
-    { "label": "Excellent", "value": "4" }
-  ]
-}
-
-
- - -
-
-

\u270D\uFE0F Signature

-

Digital signature pad

-
- -
-

Basic Usage

-

Capture signatures with mouse or touch

-
{
-  "type": "signature",
-  "key": "signature",
-  "label": "Signature",
-  "footer": "Sign above",
-  "width": "100%",
-  "height": "150px",
-  "validate": {
-    "required": true
-  }
-}
-
-
- - -
-
-

\u{1F4C1} File Upload

-

File upload with storage options

-
- -
-

Basic Usage

-

Upload files to Cloudflare R2 or base64 encode

-
{
-  "type": "file",
-  "key": "resume",
-  "label": "Upload Resume",
-  "storage": "r2",
-  "filePattern": ".pdf,.doc,.docx",
-  "fileMaxSize": "5MB",
-  "multiple": false,
-  "validate": {
-    "required": true
-  }
-}
-
-// Multiple files
-{
-  "type": "file",
-  "key": "attachments",
-  "label": "Attachments",
-  "storage": "base64",
-  "multiple": true,
-  "fileMaxSize": "10MB"
-}
-
- -
- \u{1F4A1} Storage Options: Use storage: "r2" for Cloudflare R2 (recommended) or storage: "base64" to encode in submission data. -
-
- - -
-
-

\u{1F4CD} Address

-

Address autocomplete with Google Maps

-
- -
-

Basic Usage

-

Google Maps API-powered address autocomplete

-
{
-  "type": "address",
-  "key": "address",
-  "label": "Address",
-  "provider": "google",
-  "map": {
-    "key": "YOUR_GOOGLE_MAPS_API_KEY"
-  },
-  "validate": {
-    "required": true
-  }
-}
-
- -
- \u26A0\uFE0F API Key Required: Enable Google Maps Places API and Maps JavaScript API in Google Cloud Console. -
-
- - -
-
-

\u{1F6E1}\uFE0F Turnstile

-

CAPTCHA-free bot protection by Cloudflare

-
- -
-

Basic Usage

-

Add invisible bot protection to your forms

-
{
-  "type": "turnstile",
-  "key": "turnstile",
-  "label": "Turnstile Verification",
-  "theme": "auto",
-  "size": "normal",
-  "appearance": "always",
-  "persistent": false,
-  "protected": true
-}
-
- -
-

Configuration Options

-
{
-  "type": "turnstile",
-  "key": "turnstile",
-  "label": "Security Check",
-  "theme": "light",          // "light", "dark", "auto"
-  "size": "compact",         // "normal", "compact"
-  "appearance": "always",    // "always", "execute", "interaction-only"
-  "action": "submit-form",   // Optional: action name for analytics
-  "errorMessage": "Please complete the security verification"
-}
-
- -
- \u{1F527} Setup Required: Enable the Turnstile plugin in Settings \u2192 Plugins and configure your site key and secret key from Cloudflare Dashboard. -
- -
- \u{1F4A1} Usage Tips: -
    -
  • Invisible Mode: Use "appearance": "interaction-only" for seamless UX
  • -
  • Dark Mode: Use "theme": "auto" to match user preferences
  • -
  • Compact Size: Use "size": "compact" for mobile forms
  • -
  • Backend Validation: Tokens are automatically validated server-side
  • -
-
-
- - -
-
-

\u{1F4E6} Panel

-

Group fields in collapsible panels

-
- -
-

Basic Usage

-

Used for wizards and grouping related fields

-
{
-  "type": "panel",
-  "key": "personalInfo",
-  "title": "Personal Information",
-  "collapsible": true,
-  "collapsed": false,
-  "components": [
-    { "type": "textfield", "key": "firstName", "label": "First Name" },
-    { "type": "textfield", "key": "lastName", "label": "Last Name" },
-    { "type": "email", "key": "email", "label": "Email" }
-  ]
-}
-
-
- - -
-
-

\u{1F4CA} Columns

-

Multi-column layout

-
- -
-

Basic Usage

-

Create side-by-side fields (responsive)

-
{
-  "type": "columns",
-  "columns": [
-    {
-      "components": [
-        { "type": "textfield", "key": "firstName", "label": "First Name" }
-      ],
-      "width": 6
-    },
-    {
-      "components": [
-        { "type": "textfield", "key": "lastName", "label": "Last Name" }
-      ],
-      "width": 6
-    }
-  ]
-}
-
- -
- \u{1F4A1} Width System: Width is based on 12-column grid. Use 6 for 50%, 4 for 33%, 3 for 25%, etc. -
-
- - -
-
-

\u{1F4D1} Tabs

-

Organize fields in tabs

-
- -
-

Basic Usage

-

Create tabbed interface for complex forms

-
{
-  "type": "tabs",
-  "components": [
-    {
-      "label": "Personal Info",
-      "key": "tab1",
-      "components": [...]
-    },
-    {
-      "label": "Contact Info",
-      "key": "tab2",
-      "components": [...]
-    }
-  ]
-}
-
-
- - -
-
-

\u{1F4CB} Table

-

Table layout for forms

-
- -
-

Basic Usage

-

Create table-based layouts

-
{
-  "type": "table",
-  "numRows": 3,
-  "numCols": 2,
-  "rows": [
-    [
-      { "components": [{ "type": "textfield", "key": "cell1" }] },
-      { "components": [{ "type": "textfield", "key": "cell2" }] }
-    ]
-  ]
-}
-
-
- - -
-
-

\u{1F4E6} Fieldset

-

Group fields with border and legend

-
- -
-

Basic Usage

-

HTML fieldset with legend label

-
{
-  "type": "fieldset",
-  "legend": "Contact Information",
-  "components": [
-    { "type": "email", "key": "email", "label": "Email" },
-    { "type": "phoneNumber", "key": "phone", "label": "Phone" }
-  ]
-}
-
-
- - -
-
-

\u{1F5C3}\uFE0F Data Grid

-

Repeatable row data entry

-
- -
-

Basic Usage

-

Add/remove rows of structured data

-
{
-  "type": "datagrid",
-  "key": "items",
-  "label": "Items",
-  "addAnother": "Add Item",
-  "components": [
-    { "type": "textfield", "key": "name", "label": "Item Name" },
-    { "type": "number", "key": "quantity", "label": "Quantity" },
-    { "type": "currency", "key": "price", "label": "Price" }
-  ]
-}
-
-
- - -
-
-

\u270F\uFE0F Edit Grid

-

Editable table with modal editing

-
- -
-

Basic Usage

-

Similar to Data Grid but with modal editing

-
{
-  "type": "editgrid",
-  "key": "contacts",
-  "label": "Contacts",
-  "components": [
-    { "type": "textfield", "key": "name", "label": "Name" },
-    { "type": "email", "key": "email", "label": "Email" },
-    { "type": "phoneNumber", "key": "phone", "label": "Phone" }
-  ]
-}
-
-
- - -
-
-

\u{1F9D9} Multi-Page Wizards

-

Create step-by-step forms with progress tracking

-
- -
- \u{1F4A1} How It Works: Set display: "wizard" and use Panel components for each step. Form.io automatically adds navigation buttons. -
- -
-

Complete Wizard Example

-
{
-  "display": "wizard",
-  "components": [
-    {
-      "type": "panel",
-      "key": "step1",
-      "title": "Step 1: Personal Info",
-      "components": [
-        { "type": "textfield", "key": "firstName", "label": "First Name" },
-        { "type": "textfield", "key": "lastName", "label": "Last Name" }
-      ]
-    },
-    {
-      "type": "panel",
-      "key": "step2",
-      "title": "Step 2: Contact Info",
-      "components": [
-        { "type": "email", "key": "email", "label": "Email" },
-        { "type": "phoneNumber", "key": "phone", "label": "Phone" }
-      ]
-    },
-    {
-      "type": "panel",
-      "key": "step3",
-      "title": "Step 3: Review",
-      "components": [
-        { "type": "checkbox", "key": "terms", "label": "I agree" }
-      ]
-    }
-  ]
-}
-
-
- - -
-
-

\u{1F310} Embedding Forms

-

Multiple ways to embed forms on your website

-
- -
-

Method 1: JavaScript (Recommended)

-

Load form schema via API and render with Form.io

-
<div id="form"></div>
-<script src="https://cdn.form.io/formiojs/formio.full.min.js"></script>
-<script>
-  fetch('/forms/contact_form/schema')
-    .then(r => r.json())
-    .then(data => {
-      Formio.createForm(
-        document.getElementById('form'),
-        data.schema
-      ).then(form => {
-        // Handle submission
-        form.on('submitDone', (submission) => {
-          console.log('Submitted:', submission);
-        });
-      });
-    });
-</script>
-
- -
-

Method 2: iFrame

-

Simple iframe embed (less flexible)

-
<iframe 
-  src="/forms/contact_form"
-  width="100%"
-  height="600"
-  frameborder="0"
-></iframe>
-
- -
-

Method 3: React Component

-

Use Form.io React library

-
import { Form } from '@formio/react';
-
-function MyForm() {
-  const [schema, setSchema] = useState(null);
-  
-  useEffect(() => {
-    fetch('/forms/contact_form/schema')
-      .then(r => r.json())
-      .then(data => setSchema(data.schema));
-  }, []);
-  
-  const handleSubmit = (submission) => {
-    fetch('/api/forms/123/submit', {
-      method: 'POST',
-      headers: { 'Content-Type': 'application/json' },
-      body: JSON.stringify(submission.data)
-    });
-  };
-  
-  return schema ? (
-    <Form form={schema} onSubmit={handleSubmit} />
-  ) : null;
-}
-
-
- - -
-
-

\u2705 Validation

-

Built-in validation rules

-
- -
-

Common Validation Rules

-
{
-  "validate": {
-    "required": true,           // Field must have value
-    "minLength": 2,            // Minimum characters
-    "maxLength": 50,           // Maximum characters
-    "min": 0,                  // Minimum number value
-    "max": 100,                // Maximum number value
-    "pattern": "^[A-Za-z]+$",  // Regular expression
-    "custom": "valid = (input === 'yes');" // Custom validation
-  }
-}
-
- -
-

Custom Error Messages

-
{
-  "validate": {
-    "required": true,
-    "customMessage": "Please provide your full name"
-  }
-}
-
-
- - -
-
-

\u{1F500} Conditional Logic

-

Show/hide fields based on conditions

-
- -
-

Simple Conditional

-

Show field only when condition is met

-
{
-  "type": "textfield",
-  "key": "companyName",
-  "label": "Company Name",
-  "conditional": {
-    "show": true,
-    "when": "hasCompany",
-    "eq": true
-  }
-}
-
- -
-

Advanced Conditional (JavaScript)

-

Complex conditions using custom JavaScript

-
{
-  "type": "textfield",
-  "key": "discount",
-  "label": "Discount Code",
-  "customConditional": "show = (data.total > 100 && data.memberType === 'premium');"
-}
-
-
- -
-
- - - `; - const layoutData = { - title: "Forms Quick Reference", - pageTitle: "Forms Quick Reference", - content: pageContent, - user: data.user, - version: data.version - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/pages/admin-forms-examples.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderFormsExamplesPage(data) { - const pageContent = ` - - -
- -

Form Examples

-

Interactive examples showcasing Form.io capabilities

-
- -
- - - - -
- - -
-
-

\u{1F373} Kitchen Sink

-

A comprehensive form showcasing all major field types and configurations.

-
- -
-
-
- -
-

Form Schema (JSON)

- -
-
{
-  "display": "form",
-  "components": [
-    // Basic Text Fields
-    { "type": "textfield", "key": "firstName", "label": "First Name" },
-    { "type": "email", "key": "email", "label": "Email" },
-    { "type": "phoneNumber", "key": "phone", "label": "Phone" },
-    { "type": "password", "key": "password", "label": "Password" },
-    { "type": "url", "key": "website", "label": "Website" },
-    { "type": "textarea", "key": "bio", "label": "Biography" },
-    
-    // Date & Time
-    { "type": "datetime", "key": "appointmentDateTime", "label": "Appointment" },
-    { "type": "day", "key": "birthDate", "label": "Birth Date" },
-    { "type": "time", "key": "preferredTime", "label": "Time" },
-    
-    // Selections
-    { "type": "select", "key": "country", "label": "Country", 
-      "data": { "values": [{ "label": "USA", "value": "us" }] }},
-    { "type": "selectboxes", "key": "interests", "label": "Interests",
-      "values": [{ "label": "Sports", "value": "sports" }] },
-    { "type": "radio", "key": "gender", "label": "Gender",
-      "values": [{ "label": "Male", "value": "male" }] },
-    { "type": "checkbox", "key": "newsletter", "label": "Newsletter" },
-    
-    // Advanced
-    { "type": "currency", "key": "salary", "label": "Salary" },
-    { "type": "tags", "key": "skills", "label": "Skills" },
-    { "type": "survey", "key": "satisfaction", "label": "Satisfaction" },
-    { "type": "signature", "key": "signature", "label": "Signature" },
-    { "type": "file", "key": "resume", "label": "Resume", "storage": "base64" }
-  ]
-}
-
- - -
-
-

\u{1F4E7} Simple Contact Form

-

A minimal contact form with validation.

-
- -
-
-
- -
-

Form Schema (JSON)

- -
-
{
-  "display": "form",
-  "components": [
-    {
-      "type": "textfield",
-      "key": "name",
-      "label": "Full Name",
-      "validate": { "required": true }
-    },
-    {
-      "type": "email",
-      "key": "email",
-      "label": "Email Address",
-      "validate": { "required": true }
-    },
-    {
-      "type": "textarea",
-      "key": "message",
-      "label": "Message",
-      "rows": 5,
-      "validate": { "required": true }
-    }
-  ]
-}
-
- - -
-
-

\u{1F389} Thank You Page

-

Handle form submission and redirect to a thank you message.

-
- -
-
- -
- -
-

Form Schema (JSON)

- -
-
{
-  "display": "form",
-  "components": [
-    { "type": "textfield", "key": "firstName", "label": "First Name", 
-      "validate": { "required": true }},
-    { "type": "textfield", "key": "lastName", "label": "Last Name", 
-      "validate": { "required": true }},
-    { "type": "email", "key": "email", "label": "Email Address", 
-      "validate": { "required": true }},
-    { "type": "phoneNumber", "key": "phone", "label": "Phone Number" },
-    { "type": "textarea", "key": "message", "label": "Message", 
-      "validate": { "required": true }},
-    { "type": "button", "action": "submit", "label": "Submit Form" }
-  ]
-}
- -
-

JavaScript Code

- -
-
Formio.createForm(document.getElementById('formio'), formSchema)
-  .then(function(form) {
-    // Handle successful submission
-    form.on('submitDone', function(submission) {
-      console.log('Form submitted:', submission);
-      
-      // Hide form and show thank you message
-      form.element.style.display = 'none';
-      document.getElementById('thank-you-message').style.display = 'block';
-      
-      // Or redirect to another page:
-      // window.location = '/thank-you';
-    });
-  });
-
- - -
-
-

\u{1F9D9} Multi-Page Wizard

-

Step-by-step form with multiple pages and progress indicator.

-
- -
-
-
- -
-

Form Schema (JSON)

- -
-
{
-  "display": "wizard",
-  "components": [
-    {
-      "type": "panel",
-      "key": "step1PersonalInfo",
-      "title": "Step 1: Personal Information",
-      "components": [
-        { "type": "textfield", "key": "firstName", "label": "First Name" },
-        { "type": "textfield", "key": "lastName", "label": "Last Name" },
-        { "type": "datetime", "key": "birthDate", "label": "Date of Birth" },
-        { "type": "select", "key": "gender", "label": "Gender" }
-      ]
-    },
-    {
-      "type": "panel",
-      "key": "step2ContactInfo",
-      "title": "Step 2: Contact Information",
-      "components": [
-        { "type": "email", "key": "email", "label": "Email" },
-        { "type": "phoneNumber", "key": "phone", "label": "Phone" },
-        { "type": "textfield", "key": "address", "label": "Address" },
-        { "type": "select", "key": "country", "label": "Country" }
-      ]
-    },
-    {
-      "type": "panel",
-      "key": "step3Preferences",
-      "title": "Step 3: Preferences & Review",
-      "components": [
-        { "type": "selectboxes", "key": "interests", "label": "Interests" },
-        { "type": "radio", "key": "contactMethod", "label": "Contact Method" },
-        { "type": "textarea", "key": "comments", "label": "Comments" },
-        { "type": "checkbox", "key": "terms", "label": "I agree to terms" }
-      ]
-    }
-  ]
-}
-
- - -
-
-

\u{1F500} Conditional Logic

-

Show/hide fields based on user input.

-
-
-
-
-
- -
-
-

\u{1F4C1} File Upload

-

Upload files to Cloudflare R2 storage.

-
-
-
-
-
- -
-
-

\u{1F4CD} Address with Maps

-

Google Maps autocomplete for address input.

-
-
-
-
-
- -
-
-

\u270D\uFE0F Signature Pad

-

Capture digital signatures.

-
-
-
-
-
- -
-
-

\u{1F4CA} Data Grid

-

Repeatable data entry with add/remove rows.

-
-
-
-
-
- -
-
-

\u{1F6E1}\uFE0F Turnstile Protection

-

CAPTCHA-free bot protection by Cloudflare - drag and drop from the Premium section in the form builder.

-
- -
-

\u2728 Key Features

-
    -
  • No CAPTCHA puzzles - Seamless user experience
  • -
  • Invisible protection - Works in the background
  • -
  • Auto-validated - Server-side token verification
  • -
  • Privacy-first - Cloudflare's secure infrastructure
  • -
-
- -
-
-
- -
- \u{1F527} Setup Instructions: -
    -
  1. Go to Settings \u2192 Plugins and enable Turnstile plugin
  2. -
  3. Get free API keys from Cloudflare Dashboard
  4. -
  5. Configure site key and secret key in plugin settings
  6. -
  7. Drag Turnstile component from Premium section in form builder
  8. -
-
- -
- \u{1F4A1} Pro Tip: Use "appearance": "interaction-only" for invisible mode - the widget only appears when suspicious activity is detected! -
-
- -
-
- - - - - - - - - `; - const layoutData = { - title: "Forms Examples", - pageTitle: "Forms Examples", - content: pageContent, - user: data.user, - version: data.version - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -exports.renderFilterBar = renderFilterBar; -exports.renderFormsDocsPage = renderFormsDocsPage; -exports.renderFormsExamplesPage = renderFormsExamplesPage; -//# sourceMappingURL=chunk-S6K2H2TS.cjs.map -//# sourceMappingURL=chunk-S6K2H2TS.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-SHCYIZAN.cjs b/packages/core/dist/chunk-SHCYIZAN.cjs deleted file mode 100644 index b368ae4e5..000000000 --- a/packages/core/dist/chunk-SHCYIZAN.cjs +++ /dev/null @@ -1,3565 +0,0 @@ -'use strict'; - -var chunkIGJUBJBW_cjs = require('./chunk-IGJUBJBW.cjs'); - -// src/templates/components/logo.template.ts -function renderLogo(data = {}) { - const { - size = "md", - variant = "default", - showText = true, - showVersion = true, - version, - className = "", - href - } = data; - const sizeClass = sizeClasses[size]; - const logoSvg = ` - - `; - const versionBadge = showVersion && version ? ` - - ${version} - - ` : ""; - const logoContent = showText ? ` -
- ${logoSvg} - ${versionBadge} -
- ` : logoSvg; - if (href) { - return `${logoContent}`; - } - return logoContent; -} -var sizeClasses; -var init_logo_template = chunkIGJUBJBW_cjs.__esm({ - "src/templates/components/logo.template.ts"() { - sizeClasses = { - sm: "h-6 w-auto", - md: "h-8 w-auto", - lg: "h-12 w-auto", - xl: "h-16 w-auto" - }; - } -}); - -// src/templates/layouts/admin-layout-catalyst.template.ts -var admin_layout_catalyst_template_exports = {}; -chunkIGJUBJBW_cjs.__export(admin_layout_catalyst_template_exports, { - renderAdminLayoutCatalyst: () => renderAdminLayoutCatalyst, - renderCatalystCheckbox: () => renderCatalystCheckbox -}); -function renderCatalystCheckbox(props) { - const { - id, - name, - checked = false, - disabled = false, - label, - description, - color = "dark/zinc", - className = "" - } = props; - const colorClasses = { - "dark/zinc": "peer-checked:bg-zinc-900 peer-checked:before:bg-zinc-900 dark:peer-checked:bg-zinc-600", - "dark/white": "peer-checked:bg-zinc-900 peer-checked:before:bg-zinc-900 dark:peer-checked:bg-white", - white: "peer-checked:bg-white peer-checked:before:bg-white", - dark: "peer-checked:bg-zinc-900 peer-checked:before:bg-zinc-900", - zinc: "peer-checked:bg-zinc-600 peer-checked:before:bg-zinc-600", - blue: "peer-checked:bg-blue-600 peer-checked:before:bg-blue-600", - green: "peer-checked:bg-green-600 peer-checked:before:bg-green-600", - red: "peer-checked:bg-red-600 peer-checked:before:bg-red-600" - }; - const checkColor = color === "dark/white" ? "dark:text-zinc-900" : "text-white"; - const baseClasses = ` - relative isolate flex w-4 h-4 items-center justify-center rounded-[0.3125rem] - before:absolute before:inset-0 before:-z-10 before:rounded-[calc(0.3125rem-1px)] before:bg-white before:shadow-sm - dark:before:hidden - dark:bg-white/5 - border border-zinc-950/15 peer-checked:border-transparent - dark:border-white/15 dark:peer-checked:border-white/5 - peer-focus:outline peer-focus:outline-2 peer-focus:outline-offset-2 peer-focus:outline-blue-500 - peer-disabled:opacity-50 - peer-disabled:border-zinc-950/25 peer-disabled:bg-zinc-950/5 - dark:peer-disabled:border-white/20 dark:peer-disabled:bg-white/2.5 - `.trim().replace(/\s+/g, " "); - const checkIconClasses = ` - w-4 h-4 opacity-0 peer-checked:opacity-100 pointer-events-none - `.trim().replace(/\s+/g, " "); - if (description) { - return ` -
-
- - -
- ${label ? `` : ""} - ${description ? `

${description}

` : ""} -
- `; - } else { - return ` - - `; - } -} -function renderAdminLayoutCatalyst(data) { - return ` - - - - - ${data.title} - SonicJS AI Admin - - - - - - - - - - - - - - - ${data.styles ? data.styles.map((style) => ``).join("\n ") : ""} - ${data.scripts ? data.scripts.map((script) => ``).join("\n ") : ""} - - -
- -
- ${renderCatalystSidebar( - data.currentPath, - data.user, - data.dynamicMenuItems, - false, - data.version, - data.enableExperimentalFeatures - )} -
- - - -
- ${renderCatalystSidebar( - data.currentPath, - data.user, - data.dynamicMenuItems, - true, - data.version, - data.enableExperimentalFeatures - )} -
- - -
- -
- -
- ${renderLogo({ size: "sm", showText: true, variant: "white", version: data.version, href: "/admin" })} -
-
- - -
- ${data.content} -
-
-
- - -
- - - - - - -`; -} -function renderCatalystSidebar(currentPath = "", user, dynamicMenuItems, isMobile = false, version, enableExperimentalFeatures) { - let baseMenuItems = [ - { - label: "Dashboard", - path: "/admin", - icon: ` - - ` - }, - { - label: "Collections", - path: "/admin/collections", - icon: ` - - ` - }, - { - label: "Forms", - path: "/admin/forms", - icon: ` - - ` - }, - { - label: "Content", - path: "/admin/content", - icon: ` - - ` - }, - { - label: "Media", - path: "/admin/media", - icon: ` - - ` - }, - { - label: "Users", - path: "/admin/users", - icon: ` - - ` - }, - { - label: "Plugins", - path: "/admin/plugins", - icon: ` - - ` - }, - { - label: "Cache", - path: "/admin/cache", - icon: ` - - ` - } - ]; - const settingsMenuItem = { - label: "Settings", - path: "/admin/settings", - icon: ` - - ` - }; - const allMenuItems = [...baseMenuItems]; - if (dynamicMenuItems && dynamicMenuItems.length > 0) { - const usersIndex = allMenuItems.findIndex( - (item) => item.path === "/admin/users" - ); - if (usersIndex !== -1) { - allMenuItems.splice(usersIndex + 1, 0, ...dynamicMenuItems); - } else { - allMenuItems.push(...dynamicMenuItems); - } - } - const closeButton = isMobile ? ` -
- -
- ` : ""; - return ` - - `; -} -var init_admin_layout_catalyst_template = chunkIGJUBJBW_cjs.__esm({ - "src/templates/layouts/admin-layout-catalyst.template.ts"() { - init_logo_template(); - } -}); - -// src/templates/alert.template.ts -function renderAlert(data) { - const typeClasses = { - success: "bg-green-50 dark:bg-green-500/10 border border-green-600/20 dark:border-green-500/20", - error: "bg-error/10 border border-red-600/20 dark:border-red-500/20", - warning: "bg-amber-50 dark:bg-amber-500/10 border border-amber-600/20 dark:border-amber-500/20", - info: "bg-blue-50 dark:bg-blue-500/10 border border-blue-600/20 dark:border-blue-500/20" - }; - const iconClasses = { - success: "text-green-600 dark:text-green-400", - error: "text-red-600 dark:text-red-400", - warning: "text-amber-600 dark:text-amber-400", - info: "text-blue-600 dark:text-blue-400" - }; - const textClasses = { - success: "text-green-900 dark:text-green-300", - error: "text-red-900 dark:text-red-300", - warning: "text-amber-900 dark:text-amber-300", - info: "text-blue-900 dark:text-blue-300" - }; - const messageTextClasses = { - success: "text-green-700 dark:text-green-400", - error: "text-red-700 dark:text-red-400", - warning: "text-amber-700 dark:text-amber-400", - info: "text-blue-700 dark:text-blue-400" - }; - const icons = { - success: ``, - error: ``, - warning: ``, - info: `` - }; - return ` -
-
- ${data.icon !== false ? ` -
- - ${icons[data.type]} - -
- ` : ""} -
- ${data.title ? ` -

- ${data.title} -

- ` : ""} -
-

${data.message}

-
-
- ${data.dismissible ? ` -
-
- -
-
- ` : ""} -
-
- `; -} - -// src/templates/confirmation-dialog.template.ts -function renderConfirmationDialog(options) { - const { - id, - title, - message, - confirmText = "Confirm", - cancelText = "Cancel", - confirmClass = "bg-red-500 hover:bg-red-400", - iconColor = "red", - onConfirm = "" - } = options; - const iconColorClasses = { - red: "bg-red-500/10 text-red-400", - yellow: "bg-yellow-500/10 text-yellow-400", - blue: "bg-blue-500/10 text-blue-400" - }; - return ` - - - - -
- -
-
- -
-
-

${title}

-
-

${message}

-
-
-
-
- - -
-
-
-
-
- `; -} -function getConfirmationDialogScript() { - return ` - - - `; -} - -// src/templates/pagination.template.ts -function renderPagination(data) { - const shouldShowPagination = data.totalPages > 1 || data.showPageSizeSelector !== false && data.totalItems > 0; - if (!shouldShowPagination) { - return ""; - } - const buildUrl = (page, limit) => { - const params = new URLSearchParams(data.queryParams || {}); - params.set("page", page.toString()); - if (data.itemsPerPage !== 20) { - params.set("limit", data.itemsPerPage.toString()); - } - return `${data.baseUrl}?${params.toString()}`; - }; - const buildPageSizeUrl = (limit) => { - const params = new URLSearchParams(data.queryParams || {}); - params.set("page", "1"); - params.set("limit", limit.toString()); - return `${data.baseUrl}?${params.toString()}`; - }; - const generatePageNumbers = () => { - const maxNumbers = data.maxPageNumbers || 5; - const half = Math.floor(maxNumbers / 2); - let start = Math.max(1, data.currentPage - half); - let end = Math.min(data.totalPages, start + maxNumbers - 1); - if (end - start + 1 < maxNumbers) { - start = Math.max(1, end - maxNumbers + 1); - } - const pages = []; - for (let i = start; i <= end; i++) { - pages.push(i); - } - return pages; - }; - return ` -
- ${data.totalPages > 1 ? ` - -
- ${data.currentPage > 1 ? ` - - Previous - - ` : ` - Previous - `} - - ${data.currentPage < data.totalPages ? ` - - Next - - ` : ` - Next - `} -
- ` : ""} - - - -
- `; -} - -// src/templates/table.template.ts -function renderTable(data) { - const tableId = data.tableId || `table-${Math.random().toString(36).substr(2, 9)}`; - if (data.rows.length === 0) { - return ` -
-
- - - -

${data.emptyMessage || "No data available"}

-
-
- `; - } - return ` -
- ${data.title ? ` -
-

${data.title}

-
- ` : ""} -
- - - - ${data.selectable ? ` - - ` : ""} - ${data.columns.map((column, index) => { - const isFirst = index === 0 && !data.selectable; - const isLast = index === data.columns.length - 1; - return ` - - `; - }).join("")} - - - - ${data.rows.map((row) => { - if (!row) return ""; - const clickableClass = data.rowClickable ? "cursor-pointer" : ""; - const clickHandler = data.rowClickable && data.rowClickUrl ? `onclick="window.location.href='${data.rowClickUrl(row)}'"` : ""; - return ` - - ${data.selectable ? ` - - ` : ""} - ${data.columns.map((column, colIndex) => { - const value = row[column.key]; - const displayValue = column.render ? column.render(value, row) : value; - const stopPropagation = column.key === "actions" ? 'onclick="event.stopPropagation()"' : ""; - const isFirst = colIndex === 0 && !data.selectable; - const isLast = colIndex === data.columns.length - 1; - return ` - - `; - }).join("")} - - `; - }).join("")} - -
-
-
- - - - - -
-
-
- ${column.sortable ? ` - - ` : column.label} -
-
-
- - - - - -
-
-
- ${displayValue || ""} -
-
- - -
- `; -} - -// src/templates/layouts/admin-layout-v2.template.ts -init_logo_template(); -function renderAdminLayout(data) { - const { - renderAdminLayoutCatalyst: renderAdminLayoutCatalyst2 - } = (init_admin_layout_catalyst_template(), chunkIGJUBJBW_cjs.__toCommonJS(admin_layout_catalyst_template_exports)); - return renderAdminLayoutCatalyst2(data); -} -function adminLayoutV2(data) { - return ` - - - - - ${data.title} - SonicJS AI Admin - - - - - - - - - - - - - - - ${data.styles ? data.styles.map((style) => ``).join("\n ") : ""} - ${data.scripts ? data.scripts.map((script) => ``).join("\n ") : ""} - - - -
- -
- - ${renderTopBar(data.pageTitle || "Dashboard", data.user)} - - -
-
- -
- ${renderSidebar(data.currentPath || "/", data.user, data.dynamicMenuItems)} -
- - -
- ${data.content} -
-
-
-
- - -
- - - -`; -} -function renderSidebar(currentPath, user, dynamicMenuItems) { - const baseMenuItems = [ - { - label: "Dashboard", - path: "/admin", - icon: ` - - ` - }, - { - label: "Content", - path: "/admin/content", - icon: ` - - ` - }, - { - label: "Collections", - path: "/admin/collections", - icon: ` - - ` - }, - { - label: "Media", - path: "/admin/media", - icon: ` - - ` - }, - { - label: "Users", - path: "/admin/users", - icon: ` - - ` - }, - { - label: "Plugins", - path: "/admin/plugins", - icon: ` - - ` - }, - { - label: "Cache", - path: "/admin/cache", - icon: ` - - ` - }, - { - label: "Design", - path: "/admin/design", - icon: ` - - ` - }, - { - label: "Logs", - path: "/admin/logs", - icon: ` - - ` - }, - { - label: "Settings", - path: "/admin/settings", - icon: ` - - ` - }, - { - label: "API Reference", - path: "/admin/api-reference", - icon: ` - - ` - }, - { - label: "Field Types", - path: "/admin/field-types", - icon: ` - - ` - }, - { - label: "API Spec", - path: "/api", - target: "_blank", - icon: ` - - ` - } - ]; - const allMenuItems = [...baseMenuItems]; - if (dynamicMenuItems && dynamicMenuItems.length > 0) { - const usersIndex = allMenuItems.findIndex( - (item) => item.path === "/admin/users" - ); - if (usersIndex !== -1) { - allMenuItems.splice(usersIndex + 1, 0, ...dynamicMenuItems); - } else { - allMenuItems.push(...dynamicMenuItems); - } - } - return ` - - `; -} -function renderTopBar(pageTitle, user) { - return ` -
-
-
-
- ${renderLogo({ size: "md", showText: true, variant: "white" })} -
- -
- - - - -
- - - - -
- - - ${user ? ` -
- - - - -
- ` : ` - - Sign In - - `} -
-
-
- `; -} - -// src/templates/pages/admin-design.template.ts -init_admin_layout_catalyst_template(); -function renderDesignPage(data) { - const pageContent = ` -
- -
-
-

Catalyst Design System

-

- A comprehensive showcase of all UI components and design patterns -

-
- -
- - -
-
-
-

Component Library

-

Browse all available components

-
- - - - - Quick Nav - -
- -
- - -
-

Modern UI Patterns

- - -
-
-

Gradient Filter Bar

-
-
-
-
-
-
-
- - - -
- -
- -
-
-
-
-
- - -
-

Colored Category Badges

-
-
- - Collection Name - - - 5 fields - - - Interactive - - - Category - -
-
-
- - -
-

Enhanced Table with Gradient Hover

-
- - - - - - - - - - - - - - - - - - - - -
NameTypeStatus
Example Item - - Collection - - - - Active - -
Another Item - - Content - - - - Draft - -
-
-
-
-
- - -
-

Typography

- -
-
-
-

Heading 1

- text-3xl font-semibold -
- -
-

Heading 2

- text-2xl font-semibold -
- -
-

Heading 3

- text-xl font-semibold -
- -
-

Body text - This is the standard body text used throughout the interface for content and descriptions.

- text-base -
- -
-

Small text - Used for secondary information and metadata.

- text-sm text-zinc-500 -
-
-
-
- - -
-

Color Palette

- -
- -
-

Pastel Brand Colors (Currently Used)

-
-
-
- cyan-400 - #22d3ee -
-
-
- pink-400 - #f472b6 -
-
-
- purple-400 - #c084fc -
-
-
- lime-400 - #a3e635 -
-
-
- - -
-

Complete Pastel Color Set

-
-
-
- cyan-400 - #22d3ee -
-
-
- sky-400 - #38bdf8 -
-
-
- blue-400 - #60a5fa -
-
-
- indigo-400 - #818cf8 -
-
-
- purple-400 - #c084fc -
-
-
- fuchsia-400 - #e879f9 -
-
-
- pink-400 - #f472b6 -
-
-
- rose-400 - #fb7185 -
-
-
- red-400 - #f87171 -
-
-
- orange-400 - #fb923c -
-
-
- amber-400 - #fbbf24 -
-
-
- yellow-400 - #facc15 -
-
-
- lime-400 - #a3e635 -
-
-
- green-400 - #4ade80 -
-
-
- emerald-400 - #34d399 -
-
-
- teal-400 - #2dd4bf -
-
-
- - -
- -
-

Zinc (Neutral Scale)

-
-
-
- zinc-50 -
-
-
- zinc-100 -
-
-
- zinc-500 -
-
-
- zinc-900 -
-
-
- zinc-950 -
-
-
- - -
-

Semantic Colors

-
-
-
- Info - blue-500 -
-
-
- Success - green-500 -
-
-
- Warning - amber-500 -
-
-
- Error - red-500 -
-
-
-
-
-
- - -
-

Buttons

- -
-
- -
-

Primary

-
- - -
-
- - -
-

Secondary

-
- - -
-
- - -
-

Danger

-
- -
-
- - -
-

Link Style

-
- -
-
-
-
-
- - -
-

Form Components

- -
-
- -
- - -
- - -
- -
- - -
-
- - -
- - -
- - -
- -
-
- - -
-
- - -
-
-
-
-
-
- - -
-

Checkboxes

- -
-
- -
-

Simple Checkboxes

-
- Simple Checkboxes -
-
-
-
- - - - -
-
-
-
-
-
-
- - - - -
-
-
-
-
-
-
- - - - -
-
-
-
-
-
-
- - - - -
-
-
-
-
-
-
- - -
-

With Descriptions

-
- Notifications -
-
-
-
- - - - -
-
-
- -

Receive email updates about new features and product announcements.

-
-
-
-
-
- - - - -
-
-
- -

Get tips, special offers, and news about our products and services.

-
-
-
-
-
- - - - -
-
-
- -

Important notifications about your account security and privacy.

-
-
-
-
-
-
-
-
- - -
-

Tables

- -
- - - - - - - - - - - - - - - - - - - - - - - -
- Name - - Status - - Created - - Actions -
- Sample Item 1 - - - Published - - - Jan 15, 2025 - - -
- Sample Item 2 - - - Draft - - - Jan 14, 2025 - - -
-
-
- - -
-

Alerts

- -
- -
-
- - - -
-

Success

-

Your changes have been saved successfully.

-
-
-
- - -
-
- - - -
-

Error

-

There was a problem with your request.

-
-
-
- - -
-
- - - -
-

Warning

-

Please review your changes before continuing.

-
-
-
- - -
-
- - - -
-

Information

-

Here's some helpful information about this feature.

-
-
-
-
-
- - -
-

Badges

- -
-
- - Default - - - Info - - - Success - - - Warning - - - Error - -
-
-
- - -
-

Cards

- -
- -
-

Basic Card

-

- A simple card with a title and description. -

-
- - -
-

Interactive Card

-

- This card has hover effects and is clickable. -

-
- - -
-
-
- - - -
-

With Icon

-
-

- Card with an icon in the header. -

-
-
-
- -
- `; - const layoutData = { - title: "Catalyst Design System", - currentPath: "/admin/design", - user: data.user, - version: data.version, - content: pageContent - }; - return renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/pages/admin-checkboxes.template.ts -init_admin_layout_catalyst_template(); -function renderCheckboxPage(data) { - const pageContent = ` -
- -
-
-

Catalyst Checkboxes

-

- Interactive examples using the official Catalyst checkbox component -

-
- -
- - -
-

Discoverability

-

Decide where your events can be found across the web.

- -
- Discoverability -
-
-
-
- - - - - -
-
-
- -

Make this event visible on your profile.

-
-
-
-
-
- - - - - -
-
-
- -

Allow others to embed your event details on their own site.

-
-
-
-
-
- - -
-

Newsletter Preferences

-

Choose which updates you'd like to receive.

- -
- Newsletter Preferences -
-
-
-
- - - - - -
-
-
- -

Get notified about new features and improvements.

-
-
-
-
-
- - - - - -
-
-
- -

Receive a summary of activity every week.

-
-
-
-
-
- - - - - -
-
-
- -

Special offers and promotional content.

-
-
-
-
-
- - -
-

Privacy Settings

-

Control your privacy and data sharing preferences.

- -
- Privacy Settings -
-
-
-
- - - - - -
-
-
- -

Make your profile visible to other users.

-
-
-
-
-
- - - - - -
-
-
- -

Display your recent activity on your profile.

-
-
-
-
-
- - - - - -
-
-
- -

Help us improve by sharing anonymous usage data.

-
-
-
-
-
-
- `; - const layoutData = { - title: "Catalyst Checkboxes", - currentPath: "/admin/checkboxes", - user: data.user, - content: pageContent - }; - return renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/pages/admin-testimonials-list.template.ts -init_admin_layout_catalyst_template(); -function renderTestimonialsList(data) { - const { testimonials, totalCount, currentPage, totalPages, message, messageType } = data; - const pageContent = ` -
- -
-
-

Testimonials

-

Manage customer testimonials and reviews

-
- -
- - ${message ? renderAlert({ type: messageType || "info", message, dismissible: true }) : ""} - - -
- -
- -
-
-
-
-
- -
- - -
-
-
- -
- - -
-
-
- -
-
- - - -
- -
-
-
-
- ${totalCount} ${totalCount === 1 ? "item" : "items"} - -
-
-
-
-
- - -
- ${testimonials.length > 0 ? renderTable({ - tableId: "testimonials-table", - rowClickable: true, - rowClickUrl: (row) => `/admin/testimonials/${row.id}`, - columns: [ - { key: "author", label: "Author", sortable: true, sortType: "string" }, - { key: "testimonial", label: "Testimonial", sortable: false }, - { key: "status", label: "Status", sortable: true, sortType: "boolean" }, - { key: "sortOrder", label: "Order", sortable: true, sortType: "number" }, - { key: "created_at", label: "Created", sortable: true, sortType: "date" } - ], - rows: testimonials.map((testimonial) => { - const rating = testimonial.rating ? "\u2B50".repeat(testimonial.rating) : ""; - const truncated = testimonial.testimonial_text.length > 100 ? testimonial.testimonial_text.substring(0, 100) + "..." : testimonial.testimonial_text; - return { - id: testimonial.id, - author: ` -
-
${testimonial.author_name}
- ${testimonial.author_title || testimonial.author_company ? ` -
- ${[testimonial.author_title, testimonial.author_company].filter(Boolean).join(" \xB7 ")} -
- ` : ""} - ${rating ? `
${rating}
` : ""} -
- `, - testimonial: `
${truncated}
`, - status: testimonial.isPublished ? 'Published' : 'Draft', - sortOrder: testimonial.sortOrder.toString(), - created_at: new Date(testimonial.created_at * 1e3).toLocaleDateString() - }; - }), - selectable: true - }) : ` -
- - - -

No testimonials

-

Get started by creating a new testimonial.

- -
- `} -
- - ${totalPages > 1 ? renderPagination({ - currentPage, - totalPages, - totalItems: totalCount, - itemsPerPage: 20, - startItem: (currentPage - 1) * 20 + 1, - endItem: Math.min(currentPage * 20, totalCount), - baseUrl: "/admin/testimonials" - }) : ""} -
- `; - const layoutData = { - title: "Testimonials", - currentPath: "/admin/testimonials", - user: data.user, - content: pageContent - }; - return renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/pages/admin-code-examples-list.template.ts -init_admin_layout_catalyst_template(); -function renderCodeExamplesList(data) { - const { codeExamples, totalCount, currentPage, totalPages, message, messageType } = data; - const pageContent = ` -
- -
-
-

Code Examples

-

Manage code snippets and examples

-
- -
- - ${message ? renderAlert({ type: messageType || "info", message, dismissible: true }) : ""} - - -
- -
- -
-
-
-
-
- -
- - -
-
-
- -
- - -
-
-
- -
-
- - - -
- -
-
-
-
- ${totalCount} ${totalCount === 1 ? "item" : "items"} - -
-
-
-
-
- - -
- ${codeExamples.length > 0 ? renderTable({ - tableId: "code-examples-table", - rowClickable: true, - rowClickUrl: (row) => `/admin/code-examples/${row.id}`, - columns: [ - { key: "title", label: "Title", sortable: true, sortType: "string" }, - { key: "language", label: "Language", sortable: true, sortType: "string" }, - { key: "description", label: "Description", sortable: false }, - { key: "status", label: "Status", sortable: true, sortType: "boolean" }, - { key: "sortOrder", label: "Order", sortable: true, sortType: "number" }, - { key: "created_at", label: "Created", sortable: true, sortType: "date" } - ], - rows: codeExamples.map((example) => { - const truncatedDesc = example.description ? example.description.length > 80 ? example.description.substring(0, 80) + "..." : example.description : "No description"; - const languageColors = { - javascript: "bg-yellow-100 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 ring-yellow-600/20 dark:ring-yellow-500/20", - typescript: "bg-blue-100 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 ring-blue-600/20 dark:ring-blue-500/20", - python: "bg-green-100 dark:bg-green-500/10 text-green-700 dark:text-green-400 ring-green-600/20 dark:ring-green-500/20", - go: "bg-cyan-100 dark:bg-cyan-500/10 text-cyan-700 dark:text-cyan-400 ring-cyan-600/20 dark:ring-cyan-500/20", - rust: "bg-orange-100 dark:bg-orange-500/10 text-orange-700 dark:text-orange-400 ring-orange-600/20 dark:ring-orange-500/20", - java: "bg-red-100 dark:bg-red-500/10 text-red-700 dark:text-red-400 ring-red-600/20 dark:ring-red-500/20", - php: "bg-indigo-100 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 ring-indigo-600/20 dark:ring-indigo-500/20", - ruby: "bg-pink-100 dark:bg-pink-500/10 text-pink-700 dark:text-pink-400 ring-pink-600/20 dark:ring-pink-500/20", - sql: "bg-purple-100 dark:bg-purple-500/10 text-purple-700 dark:text-purple-400 ring-purple-600/20 dark:ring-purple-500/20" - }; - const langColor = languageColors[example.language.toLowerCase()] || "bg-zinc-100 dark:bg-zinc-500/10 text-zinc-700 dark:text-zinc-400 ring-zinc-600/20 dark:ring-zinc-500/20"; - return { - id: example.id, - title: `
${example.title}
`, - language: `${example.language}`, - description: `
${truncatedDesc}
`, - status: example.isPublished ? 'Published' : 'Draft', - sortOrder: example.sortOrder.toString(), - created_at: new Date(example.created_at * 1e3).toLocaleDateString() - }; - }), - selectable: true - }) : ` -
- - - -

No code examples

-

Get started by creating a new code example.

- -
- `} -
- - ${totalPages > 1 ? renderPagination({ - currentPage, - totalPages, - totalItems: totalCount, - itemsPerPage: 20, - startItem: (currentPage - 1) * 20 + 1, - endItem: Math.min(currentPage * 20, totalCount), - baseUrl: "/admin/code-examples" - }) : ""} -
- `; - const layoutData = { - title: "Code Examples", - currentPath: "/admin/code-examples", - user: data.user, - content: pageContent - }; - return renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/form.template.ts -function renderForm(data) { - return ` -
f.type === "file") ? 'enctype="multipart/form-data"' : ""} - > - ${data.title ? ` -
-

${data.title}

- ${data.description ? `

${data.description}

` : ""} -
- ` : ""} - -
- - ${data.fields.map((field) => renderFormField(field)).join("")} - -
-
- ${data.submitButtons.map((button) => ` - - `).join("")} -
-
-
- `; -} -function renderFormField(field) { - const fieldId = `field-${field.name}`; - const required = field.required ? "required" : ""; - const readonly = field.readonly ? "readonly" : ""; - const placeholder = field.placeholder ? `placeholder="${field.placeholder}"` : ""; - let fieldHTML = ""; - switch (field.type) { - case "text": - case "email": - case "number": - case "date": - fieldHTML = ` - - `; - break; - case "textarea": - fieldHTML = ` - - `; - break; - case "rich_text": - const uniqueId = `${field.name}-${Date.now()}`; - fieldHTML = ` -
- - -
- `; - break; - case "select": - fieldHTML = ` - - `; - break; - case "multi_select": - fieldHTML = ` - - `; - break; - case "checkbox": - fieldHTML = ` - - - `; - break; - default: - fieldHTML = ` - - `; - break; - } - if (field.type === "checkbox") { - return ` -
-
- ${fieldHTML} -
- ${field.helpText ? `

${field.helpText}

` : ""} -
- `; - } - return ` -
- - ${fieldHTML} - ${field.helpText ? `

${field.helpText}

` : ""} -
- `; -} - -exports.adminLayoutV2 = adminLayoutV2; -exports.getConfirmationDialogScript = getConfirmationDialogScript; -exports.init_admin_layout_catalyst_template = init_admin_layout_catalyst_template; -exports.init_logo_template = init_logo_template; -exports.renderAdminLayout = renderAdminLayout; -exports.renderAdminLayoutCatalyst = renderAdminLayoutCatalyst; -exports.renderAlert = renderAlert; -exports.renderCheckboxPage = renderCheckboxPage; -exports.renderCodeExamplesList = renderCodeExamplesList; -exports.renderConfirmationDialog = renderConfirmationDialog; -exports.renderDesignPage = renderDesignPage; -exports.renderForm = renderForm; -exports.renderFormField = renderFormField; -exports.renderLogo = renderLogo; -exports.renderPagination = renderPagination; -exports.renderTable = renderTable; -exports.renderTestimonialsList = renderTestimonialsList; -//# sourceMappingURL=chunk-SHCYIZAN.cjs.map -//# sourceMappingURL=chunk-SHCYIZAN.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-VAPDSKKV.cjs b/packages/core/dist/chunk-VAPDSKKV.cjs deleted file mode 100644 index eb5225af7..000000000 --- a/packages/core/dist/chunk-VAPDSKKV.cjs +++ /dev/null @@ -1,27840 +0,0 @@ -'use strict'; - -var chunkVNLR35GO_cjs = require('./chunk-VNLR35GO.cjs'); -var chunkDVQA5II3_cjs = require('./chunk-DVQA5II3.cjs'); -var chunkMPT5PA6U_cjs = require('./chunk-MPT5PA6U.cjs'); -var chunkFQSMNIY2_cjs = require('./chunk-FQSMNIY2.cjs'); -var chunkSHCYIZAN_cjs = require('./chunk-SHCYIZAN.cjs'); -var chunk6FHNRRJ3_cjs = require('./chunk-6FHNRRJ3.cjs'); -var chunk5HMR2SJW_cjs = require('./chunk-5HMR2SJW.cjs'); -var chunkRCQ2HIQD_cjs = require('./chunk-RCQ2HIQD.cjs'); -var hono = require('hono'); -var cors = require('hono/cors'); -var zod = require('zod'); -var cookie = require('hono/cookie'); -var html = require('hono/html'); - -// src/schemas/index.ts -var schemaDefinitions = []; - -// src/routes/api-content-access-policy.ts -function canReadNonPublicContent(userRole) { - return userRole === "admin" || userRole === "editor"; -} -function isStatusCondition(condition) { - return condition.field === "status"; -} -function stripStatusConditions(group) { - if (!group) { - return void 0; - } - const and = group.and?.filter((condition) => !isStatusCondition(condition)); - const or = group.or?.filter((condition) => !isStatusCondition(condition)); - const normalizedGroup = {}; - if (and && and.length > 0) { - normalizedGroup.and = and; - } - if (or && or.length > 0) { - normalizedGroup.or = or; - } - return normalizedGroup; -} -function normalizePublicContentFilter(filter, userRole) { - if (canReadNonPublicContent(userRole)) { - return filter; - } - const normalizedFilter = { - ...filter, - where: stripStatusConditions(filter.where) - }; - if (!normalizedFilter.where) { - normalizedFilter.where = { and: [] }; - } - if (!normalizedFilter.where.and) { - normalizedFilter.where.and = []; - } - normalizedFilter.where.and.push({ - field: "status", - operator: "equals", - value: "published" - }); - return normalizedFilter; -} -var apiContentCrudRoutes = new hono.Hono(); -apiContentCrudRoutes.get("/check-slug", async (c) => { - try { - const db = c.env.DB; - const collectionId = c.req.query("collectionId"); - const slug = c.req.query("slug"); - const excludeId = c.req.query("excludeId"); - if (!collectionId || !slug) { - return c.json({ error: "collectionId and slug are required" }, 400); - } - let query = "SELECT id FROM content WHERE collection_id = ? AND slug = ?"; - const params = [collectionId, slug]; - if (excludeId) { - query += " AND id != ?"; - params.push(excludeId); - } - const existing = await db.prepare(query).bind(...params).first(); - if (existing) { - return c.json({ - available: false, - message: "This URL slug is already in use in this collection" - }); - } - return c.json({ available: true }); - } catch (error) { - console.error("Error checking slug:", error); - return c.json({ - error: "Failed to check slug availability", - details: error instanceof Error ? error.message : String(error) - }, 500); - } -}); -apiContentCrudRoutes.get("/:id", async (c) => { - try { - const id = c.req.param("id"); - const db = c.env.DB; - const stmt = db.prepare("SELECT * FROM content WHERE id = ?"); - const content = await stmt.bind(id).first(); - if (!content) { - return c.json({ error: "Content not found" }, 404); - } - const transformedContent = { - id: content.id, - title: content.title, - slug: content.slug, - status: content.status, - collectionId: content.collection_id, - data: content.data ? JSON.parse(content.data) : {}, - created_at: content.created_at, - updated_at: content.updated_at - }; - return c.json({ data: transformedContent }); - } catch (error) { - console.error("Error fetching content:", error); - return c.json({ - error: "Failed to fetch content", - details: error instanceof Error ? error.message : String(error) - }, 500); - } -}); -apiContentCrudRoutes.post("/", chunkDVQA5II3_cjs.requireAuth(), async (c) => { - try { - const db = c.env.DB; - const user = c.get("user"); - const body = await c.req.json(); - const { collectionId, title, slug, status, data } = body; - if (!collectionId) { - return c.json({ error: "collectionId is required" }, 400); - } - if (!title) { - return c.json({ error: "title is required" }, 400); - } - let finalSlug = slug || title; - finalSlug = finalSlug.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim(); - const duplicateCheck = db.prepare( - "SELECT id FROM content WHERE collection_id = ? AND slug = ?" - ); - const existing = await duplicateCheck.bind(collectionId, finalSlug).first(); - if (existing) { - return c.json({ error: "A content item with this slug already exists in this collection" }, 409); - } - const contentId = crypto.randomUUID(); - const now = Date.now(); - const insertStmt = db.prepare(` - INSERT INTO content ( - id, collection_id, slug, title, data, status, - author_id, created_at, updated_at - ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await insertStmt.bind( - contentId, - collectionId, - finalSlug, - title, - JSON.stringify(data || {}), - status || "draft", - user?.userId || "system", - now, - now - ).run(); - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.api); - await cache.invalidate(`content:list:${collectionId}:*`); - await cache.invalidate("content-filtered:*"); - const getStmt = db.prepare("SELECT * FROM content WHERE id = ?"); - const createdContent = await getStmt.bind(contentId).first(); - return c.json({ - data: { - id: createdContent.id, - title: createdContent.title, - slug: createdContent.slug, - status: createdContent.status, - collectionId: createdContent.collection_id, - data: createdContent.data ? JSON.parse(createdContent.data) : {}, - created_at: createdContent.created_at, - updated_at: createdContent.updated_at - } - }, 201); - } catch (error) { - console.error("Error creating content:", error); - return c.json({ - error: "Failed to create content", - details: error instanceof Error ? error.message : String(error) - }, 500); - } -}); -apiContentCrudRoutes.put("/:id", chunkDVQA5II3_cjs.requireAuth(), async (c) => { - try { - const id = c.req.param("id"); - const db = c.env.DB; - const body = await c.req.json(); - const existingStmt = db.prepare("SELECT * FROM content WHERE id = ?"); - const existing = await existingStmt.bind(id).first(); - if (!existing) { - return c.json({ error: "Content not found" }, 404); - } - const updates = []; - const params = []; - if (body.title !== void 0) { - updates.push("title = ?"); - params.push(body.title); - } - if (body.slug !== void 0) { - let finalSlug = body.slug.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim(); - updates.push("slug = ?"); - params.push(finalSlug); - } - if (body.status !== void 0) { - updates.push("status = ?"); - params.push(body.status); - } - if (body.data !== void 0) { - updates.push("data = ?"); - params.push(JSON.stringify(body.data)); - } - const now = Date.now(); - updates.push("updated_at = ?"); - params.push(now); - params.push(id); - const updateStmt = db.prepare(` - UPDATE content SET ${updates.join(", ")} - WHERE id = ? - `); - await updateStmt.bind(...params).run(); - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.api); - await cache.delete(cache.generateKey("content", id)); - await cache.invalidate(`content:list:${existing.collection_id}:*`); - await cache.invalidate("content-filtered:*"); - const getStmt = db.prepare("SELECT * FROM content WHERE id = ?"); - const updatedContent = await getStmt.bind(id).first(); - return c.json({ - data: { - id: updatedContent.id, - title: updatedContent.title, - slug: updatedContent.slug, - status: updatedContent.status, - collectionId: updatedContent.collection_id, - data: updatedContent.data ? JSON.parse(updatedContent.data) : {}, - created_at: updatedContent.created_at, - updated_at: updatedContent.updated_at - } - }); - } catch (error) { - console.error("Error updating content:", error); - return c.json({ - error: "Failed to update content", - details: error instanceof Error ? error.message : String(error) - }, 500); - } -}); -apiContentCrudRoutes.delete("/:id", chunkDVQA5II3_cjs.requireAuth(), async (c) => { - try { - const id = c.req.param("id"); - const db = c.env.DB; - const existingStmt = db.prepare("SELECT collection_id FROM content WHERE id = ?"); - const existing = await existingStmt.bind(id).first(); - if (!existing) { - return c.json({ error: "Content not found" }, 404); - } - const deleteStmt = db.prepare("DELETE FROM content WHERE id = ?"); - await deleteStmt.bind(id).run(); - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.api); - await cache.delete(cache.generateKey("content", id)); - await cache.invalidate(`content:list:${existing.collection_id}:*`); - await cache.invalidate("content-filtered:*"); - return c.json({ success: true }); - } catch (error) { - console.error("Error deleting content:", error); - return c.json({ - error: "Failed to delete content", - details: error instanceof Error ? error.message : String(error) - }, 500); - } -}); -var api_content_crud_default = apiContentCrudRoutes; - -// src/routes/api.ts -var apiRoutes = new hono.Hono(); -apiRoutes.use("*", async (c, next) => { - const startTime = Date.now(); - c.set("startTime", startTime); - await next(); - const totalTime = Date.now() - startTime; - c.header("X-Response-Time", `${totalTime}ms`); -}); -apiRoutes.use("*", async (c, next) => { - const cacheEnabled = await chunkDVQA5II3_cjs.isPluginActive(c.env.DB, "core-cache"); - c.set("cacheEnabled", cacheEnabled); - await next(); -}); -apiRoutes.use("*", cors.cors({ - origin: "*", - allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], - allowHeaders: ["Content-Type", "Authorization"] -})); -function addTimingMeta(c, meta = {}, executionStartTime) { - const totalTime = Date.now() - c.get("startTime"); - const executionTime = executionStartTime ? Date.now() - executionStartTime : void 0; - return { - ...meta, - timing: { - total: totalTime, - execution: executionTime, - unit: "ms" - } - }; -} -apiRoutes.get("/", (c) => { - const baseUrl = new URL(c.req.url); - const serverUrl = `${baseUrl.protocol}//${baseUrl.host}`; - return c.json({ - openapi: "3.0.0", - info: { - title: "SonicJS AI API", - version: "0.1.0", - description: "RESTful API for SonicJS headless CMS - a modern, AI-powered content management system built on Cloudflare Workers", - contact: { - name: "SonicJS Support", - url: `${serverUrl}/docs`, - email: "support@sonicjs.com" - }, - license: { - name: "MIT", - url: "https://opensource.org/licenses/MIT" - } - }, - servers: [ - { - url: serverUrl, - description: "Current server" - } - ], - paths: { - "/api/": { - get: { - summary: "API Information", - description: "Returns OpenAPI specification for the SonicJS API", - operationId: "getApiInfo", - tags: ["System"], - responses: { - "200": { - description: "OpenAPI specification", - content: { - "application/json": { - schema: { type: "object" } - } - } - } - } - } - }, - "/api/health": { - get: { - summary: "Health Check", - description: "Returns API health status and available schemas", - operationId: "getHealth", - tags: ["System"], - responses: { - "200": { - description: "Health status", - content: { - "application/json": { - schema: { - type: "object", - properties: { - status: { type: "string", example: "healthy" }, - timestamp: { type: "string", format: "date-time" }, - schemas: { type: "array", items: { type: "string" } } - } - } - } - } - } - } - } - }, - "/api/collections": { - get: { - summary: "List Collections", - description: "Returns all active collections with their schemas", - operationId: "getCollections", - tags: ["Content"], - responses: { - "200": { - description: "List of collections", - content: { - "application/json": { - schema: { - type: "object", - properties: { - data: { - type: "array", - items: { - type: "object", - properties: { - id: { type: "string" }, - name: { type: "string" }, - display_name: { type: "string" }, - schema: { type: "object" }, - is_active: { type: "integer" } - } - } - }, - meta: { type: "object" } - } - } - } - } - } - } - } - }, - "/api/collections/{collection}/content": { - get: { - summary: "Get Collection Content", - description: "Returns content items from a specific collection with filtering support. Anonymous, viewer, and author requests are restricted to published content; admin and editor requests may query other statuses.", - operationId: "getCollectionContent", - tags: ["Content"], - parameters: [ - { - name: "collection", - in: "path", - required: true, - schema: { type: "string" }, - description: "Collection name" - }, - { - name: "limit", - in: "query", - schema: { type: "integer", default: 50, maximum: 1e3 }, - description: "Maximum number of items to return" - }, - { - name: "offset", - in: "query", - schema: { type: "integer", default: 0 }, - description: "Number of items to skip" - }, - { - name: "status", - in: "query", - schema: { type: "string", enum: ["draft", "published", "archived"] }, - description: "Filter by content status. Anonymous, viewer, and author requests are limited to published content." - } - ], - responses: { - "200": { - description: "List of content items", - content: { - "application/json": { - schema: { - type: "object", - properties: { - data: { type: "array", items: { type: "object" } }, - meta: { type: "object" } - } - } - } - } - }, - "404": { - description: "Collection not found" - } - } - } - }, - "/api/content": { - get: { - summary: "List Content", - description: "Returns content items with advanced filtering support. Anonymous, viewer, and author requests are restricted to published content; admin and editor requests may query other statuses.", - operationId: "getContent", - tags: ["Content"], - parameters: [ - { - name: "collection", - in: "query", - schema: { type: "string" }, - description: "Filter by collection name" - }, - { - name: "limit", - in: "query", - schema: { type: "integer", default: 50, maximum: 1e3 }, - description: "Maximum number of items to return" - }, - { - name: "offset", - in: "query", - schema: { type: "integer", default: 0 }, - description: "Number of items to skip" - }, - { - name: "status", - in: "query", - schema: { type: "string", enum: ["draft", "published", "archived"] }, - description: "Filter by content status. Anonymous, viewer, and author requests are limited to published content." - } - ], - responses: { - "200": { - description: "List of content items", - content: { - "application/json": { - schema: { - type: "object", - properties: { - data: { type: "array", items: { type: "object" } }, - meta: { type: "object" } - } - } - } - } - } - } - }, - post: { - summary: "Create Content", - description: "Creates a new content item", - operationId: "createContent", - tags: ["Content"], - security: [{ bearerAuth: [] }], - requestBody: { - required: true, - content: { - "application/json": { - schema: { - type: "object", - required: ["collection_id", "title"], - properties: { - collection_id: { type: "string" }, - title: { type: "string" }, - slug: { type: "string" }, - status: { type: "string", enum: ["draft", "published", "archived"] }, - data: { type: "object" } - } - } - } - } - }, - responses: { - "201": { description: "Content created successfully" }, - "400": { description: "Invalid request body" }, - "401": { description: "Unauthorized" } - } - } - }, - "/api/content/{id}": { - get: { - summary: "Get Content by ID", - description: "Returns a specific content item by ID", - operationId: "getContentById", - tags: ["Content"], - parameters: [ - { - name: "id", - in: "path", - required: true, - schema: { type: "string" }, - description: "Content item ID" - } - ], - responses: { - "200": { description: "Content item" }, - "404": { description: "Content not found" } - } - }, - put: { - summary: "Update Content", - description: "Updates an existing content item", - operationId: "updateContent", - tags: ["Content"], - security: [{ bearerAuth: [] }], - parameters: [ - { - name: "id", - in: "path", - required: true, - schema: { type: "string" }, - description: "Content item ID" - } - ], - responses: { - "200": { description: "Content updated successfully" }, - "401": { description: "Unauthorized" }, - "404": { description: "Content not found" } - } - }, - delete: { - summary: "Delete Content", - description: "Deletes a content item", - operationId: "deleteContent", - tags: ["Content"], - security: [{ bearerAuth: [] }], - parameters: [ - { - name: "id", - in: "path", - required: true, - schema: { type: "string" }, - description: "Content item ID" - } - ], - responses: { - "200": { description: "Content deleted successfully" }, - "401": { description: "Unauthorized" }, - "404": { description: "Content not found" } - } - } - }, - "/api/media": { - get: { - summary: "List Media", - description: "Returns all media files with pagination", - operationId: "getMedia", - tags: ["Media"], - responses: { - "200": { description: "List of media files" } - } - } - }, - "/api/media/upload": { - post: { - summary: "Upload Media", - description: "Uploads a new media file to R2 storage", - operationId: "uploadMedia", - tags: ["Media"], - security: [{ bearerAuth: [] }], - requestBody: { - required: true, - content: { - "multipart/form-data": { - schema: { - type: "object", - properties: { - file: { type: "string", format: "binary" } - } - } - } - } - }, - responses: { - "201": { description: "Media uploaded successfully" }, - "401": { description: "Unauthorized" } - } - } - } - }, - components: { - securitySchemes: { - bearerAuth: { - type: "http", - scheme: "bearer", - bearerFormat: "JWT" - } - }, - schemas: { - Content: { - type: "object", - properties: { - id: { type: "string", format: "uuid" }, - title: { type: "string" }, - slug: { type: "string" }, - status: { type: "string", enum: ["draft", "published", "archived"] }, - collectionId: { type: "string", format: "uuid" }, - data: { type: "object" }, - created_at: { type: "integer" }, - updated_at: { type: "integer" } - } - }, - Collection: { - type: "object", - properties: { - id: { type: "string", format: "uuid" }, - name: { type: "string" }, - display_name: { type: "string" }, - description: { type: "string" }, - schema: { type: "object" }, - is_active: { type: "integer" } - } - }, - Media: { - type: "object", - properties: { - id: { type: "string", format: "uuid" }, - filename: { type: "string" }, - mimetype: { type: "string" }, - size: { type: "integer" }, - url: { type: "string" } - } - }, - Error: { - type: "object", - properties: { - error: { type: "string" }, - details: { type: "string" } - } - } - } - }, - tags: [ - { name: "System", description: "System and health endpoints" }, - { name: "Content", description: "Content management operations" }, - { name: "Media", description: "Media file operations" } - ] - }); -}); -apiRoutes.get("/health", (c) => { - return c.json({ - status: "healthy", - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - schemas: schemaDefinitions.map((s) => s.name) - }); -}); -apiRoutes.get("/collections", async (c) => { - const executionStart = Date.now(); - try { - const db = c.env.DB; - const cacheEnabled = c.get("cacheEnabled"); - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.api); - const cacheKey = cache.generateKey("collections", "all"); - if (cacheEnabled) { - const cacheResult = await cache.getWithSource(cacheKey); - if (cacheResult.hit && cacheResult.data) { - c.header("X-Cache-Status", "HIT"); - c.header("X-Cache-Source", cacheResult.source); - if (cacheResult.ttl) { - c.header("X-Cache-TTL", Math.floor(cacheResult.ttl).toString()); - } - const dataWithMeta = { - ...cacheResult.data, - meta: addTimingMeta(c, { - ...cacheResult.data.meta, - cache: { - hit: true, - source: cacheResult.source, - ttl: cacheResult.ttl ? Math.floor(cacheResult.ttl) : void 0 - } - }, executionStart) - }; - return c.json(dataWithMeta); - } - } - c.header("X-Cache-Status", "MISS"); - c.header("X-Cache-Source", "database"); - const stmt = db.prepare("SELECT * FROM collections WHERE is_active = 1"); - const { results } = await stmt.all(); - const transformedResults = results.map((row) => ({ - ...row, - schema: row.schema ? JSON.parse(row.schema) : {}, - is_active: row.is_active - // Keep as number (1 or 0) - })); - const responseData = { - data: transformedResults, - meta: addTimingMeta(c, { - count: results.length, - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - cache: { - hit: false, - source: "database" - } - }, executionStart) - }; - if (cacheEnabled) { - await cache.set(cacheKey, responseData); - } - return c.json(responseData); - } catch (error) { - console.error("Error fetching collections:", error); - return c.json({ error: "Failed to fetch collections" }, 500); - } -}); -apiRoutes.get("/content", chunkDVQA5II3_cjs.optionalAuth(), async (c) => { - const executionStart = Date.now(); - try { - const db = c.env.DB; - const queryParams = c.req.query(); - if (queryParams.collection) { - const collectionName = queryParams.collection; - const collectionStmt = db.prepare("SELECT id FROM collections WHERE name = ? AND is_active = 1"); - const collectionResult = await collectionStmt.bind(collectionName).first(); - if (collectionResult) { - queryParams.collection_id = collectionResult.id; - delete queryParams.collection; - } else { - return c.json({ - data: [], - meta: addTimingMeta(c, { - count: 0, - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - message: `Collection '${collectionName}' not found` - }, executionStart) - }); - } - } - const filter = chunk5HMR2SJW_cjs.QueryFilterBuilder.parseFromQuery(queryParams); - const normalizedFilter = normalizePublicContentFilter(filter, c.get("user")?.role); - if (!normalizedFilter.limit) { - normalizedFilter.limit = 50; - } - normalizedFilter.limit = Math.min(normalizedFilter.limit, 1e3); - const builder3 = new chunk5HMR2SJW_cjs.QueryFilterBuilder(); - const queryResult = builder3.build("content", normalizedFilter); - if (queryResult.errors.length > 0) { - return c.json({ - error: "Invalid filter parameters", - details: queryResult.errors - }, 400); - } - const cacheEnabled = c.get("cacheEnabled"); - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.api); - const cacheKey = cache.generateKey("content-filtered", JSON.stringify({ filter: normalizedFilter, query: queryResult.sql })); - if (cacheEnabled) { - const cacheResult = await cache.getWithSource(cacheKey); - if (cacheResult.hit && cacheResult.data) { - c.header("X-Cache-Status", "HIT"); - c.header("X-Cache-Source", cacheResult.source); - if (cacheResult.ttl) { - c.header("X-Cache-TTL", Math.floor(cacheResult.ttl).toString()); - } - const dataWithMeta = { - ...cacheResult.data, - meta: addTimingMeta(c, { - ...cacheResult.data.meta, - cache: { - hit: true, - source: cacheResult.source, - ttl: cacheResult.ttl ? Math.floor(cacheResult.ttl) : void 0 - } - }, executionStart) - }; - return c.json(dataWithMeta); - } - } - c.header("X-Cache-Status", "MISS"); - c.header("X-Cache-Source", "database"); - const stmt = db.prepare(queryResult.sql); - const boundStmt = queryResult.params.length > 0 ? stmt.bind(...queryResult.params) : stmt; - const { results } = await boundStmt.all(); - const transformedResults = results.map((row) => ({ - id: row.id, - title: row.title, - slug: row.slug, - status: row.status, - collectionId: row.collection_id, - data: row.data ? JSON.parse(row.data) : {}, - created_at: row.created_at, - updated_at: row.updated_at - })); - const responseData = { - data: transformedResults, - meta: addTimingMeta(c, { - count: results.length, - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - filter: normalizedFilter, - query: { - sql: queryResult.sql, - params: queryResult.params - }, - cache: { - hit: false, - source: "database" - } - }, executionStart) - }; - if (cacheEnabled) { - await cache.set(cacheKey, responseData); - } - return c.json(responseData); - } catch (error) { - console.error("Error fetching content:", error); - return c.json({ - error: "Failed to fetch content", - details: error instanceof Error ? error.message : String(error) - }, 500); - } -}); -apiRoutes.get("/collections/:collection/content", chunkDVQA5II3_cjs.optionalAuth(), async (c) => { - const executionStart = Date.now(); - try { - const collection = c.req.param("collection"); - const db = c.env.DB; - const queryParams = c.req.query(); - const collectionStmt = db.prepare("SELECT * FROM collections WHERE name = ? AND is_active = 1"); - const collectionResult = await collectionStmt.bind(collection).first(); - if (!collectionResult) { - return c.json({ error: "Collection not found" }, 404); - } - const filter = chunk5HMR2SJW_cjs.QueryFilterBuilder.parseFromQuery(queryParams); - const normalizedFilter = normalizePublicContentFilter(filter, c.get("user")?.role); - if (!normalizedFilter.where) { - normalizedFilter.where = { and: [] }; - } - if (!normalizedFilter.where.and) { - normalizedFilter.where.and = []; - } - normalizedFilter.where.and.push({ - field: "collection_id", - operator: "equals", - value: collectionResult.id - }); - if (!normalizedFilter.limit) { - normalizedFilter.limit = 50; - } - normalizedFilter.limit = Math.min(normalizedFilter.limit, 1e3); - const builder3 = new chunk5HMR2SJW_cjs.QueryFilterBuilder(); - const queryResult = builder3.build("content", normalizedFilter); - if (queryResult.errors.length > 0) { - return c.json({ - error: "Invalid filter parameters", - details: queryResult.errors - }, 400); - } - const cacheEnabled = c.get("cacheEnabled"); - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.api); - const cacheKey = cache.generateKey("collection-content-filtered", `${collection}:${JSON.stringify({ filter: normalizedFilter, query: queryResult.sql })}`); - if (cacheEnabled) { - const cacheResult = await cache.getWithSource(cacheKey); - if (cacheResult.hit && cacheResult.data) { - c.header("X-Cache-Status", "HIT"); - c.header("X-Cache-Source", cacheResult.source); - if (cacheResult.ttl) { - c.header("X-Cache-TTL", Math.floor(cacheResult.ttl).toString()); - } - const dataWithMeta = { - ...cacheResult.data, - meta: addTimingMeta(c, { - ...cacheResult.data.meta, - cache: { - hit: true, - source: cacheResult.source, - ttl: cacheResult.ttl ? Math.floor(cacheResult.ttl) : void 0 - } - }, executionStart) - }; - return c.json(dataWithMeta); - } - } - c.header("X-Cache-Status", "MISS"); - c.header("X-Cache-Source", "database"); - const stmt = db.prepare(queryResult.sql); - const boundStmt = queryResult.params.length > 0 ? stmt.bind(...queryResult.params) : stmt; - const { results } = await boundStmt.all(); - const transformedResults = results.map((row) => ({ - id: row.id, - title: row.title, - slug: row.slug, - status: row.status, - collectionId: row.collection_id, - data: row.data ? JSON.parse(row.data) : {}, - created_at: row.created_at, - updated_at: row.updated_at - })); - const responseData = { - data: transformedResults, - meta: addTimingMeta(c, { - collection: { - ...collectionResult, - schema: collectionResult.schema ? JSON.parse(collectionResult.schema) : {} - }, - count: results.length, - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - filter: normalizedFilter, - query: { - sql: queryResult.sql, - params: queryResult.params - }, - cache: { - hit: false, - source: "database" - } - }, executionStart) - }; - if (cacheEnabled) { - await cache.set(cacheKey, responseData); - } - return c.json(responseData); - } catch (error) { - console.error("Error fetching content:", error); - return c.json({ - error: "Failed to fetch content", - details: error instanceof Error ? error.message : String(error) - }, 500); - } -}); -apiRoutes.route("/content", api_content_crud_default); -var api_default = apiRoutes; -function generateId() { - return crypto.randomUUID().replace(/-/g, "").substring(0, 21); -} -async function emitEvent(eventName, data) { - console.log(`[Event] ${eventName}:`, data); -} -var fileValidationSchema = zod.z.object({ - name: zod.z.string().min(1).max(255), - type: zod.z.string().refine( - (type) => { - const allowedTypes = [ - // Images - "image/jpeg", - "image/jpg", - "image/png", - "image/gif", - "image/webp", - "image/svg+xml", - // Documents - "application/pdf", - "text/plain", - "application/msword", - "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - // Videos - "video/mp4", - "video/webm", - "video/ogg", - "video/avi", - "video/mov", - // Audio - "audio/mp3", - "audio/wav", - "audio/ogg", - "audio/m4a" - ]; - return allowedTypes.includes(type); - }, - { message: "Unsupported file type" } - ), - size: zod.z.number().min(1).max(50 * 1024 * 1024) - // 50MB max -}); -var apiMediaRoutes = new hono.Hono(); -apiMediaRoutes.use("*", chunkDVQA5II3_cjs.requireAuth()); -apiMediaRoutes.post("/upload", async (c) => { - try { - const user = c.get("user"); - const formData = await c.req.formData(); - const fileData = formData.get("file"); - if (!fileData || typeof fileData === "string") { - return c.json({ error: "No file provided" }, 400); - } - const file = fileData; - const validation = fileValidationSchema.safeParse({ - name: file.name, - type: file.type, - size: file.size - }); - if (!validation.success) { - return c.json({ - error: "File validation failed", - details: validation.error.issues - }, 400); - } - const fileId = generateId(); - const fileExtension = file.name.split(".").pop() || ""; - const filename = `${fileId}.${fileExtension}`; - const folder = formData.get("folder") || "uploads"; - const r2Key = `${folder}/${filename}`; - const arrayBuffer = await file.arrayBuffer(); - const uploadResult = await c.env.MEDIA_BUCKET.put(r2Key, arrayBuffer, { - httpMetadata: { - contentType: file.type, - contentDisposition: `inline; filename="${file.name}"` - }, - customMetadata: { - originalName: file.name, - uploadedBy: user.userId, - uploadedAt: (/* @__PURE__ */ new Date()).toISOString() - } - }); - if (!uploadResult) { - return c.json({ error: "Failed to upload file to storage" }, 500); - } - const bucketName = c.env.BUCKET_NAME || "sonicjs-media-dev"; - const publicUrl = `https://pub-${bucketName}.r2.dev/${r2Key}`; - let width; - let height; - if (file.type.startsWith("image/") && !file.type.includes("svg")) { - try { - const dimensions = await getImageDimensions(arrayBuffer); - width = dimensions.width; - height = dimensions.height; - } catch (error) { - console.warn("Failed to extract image dimensions:", error); - } - } - let thumbnailUrl; - if (file.type.startsWith("image/") && c.env.IMAGES_ACCOUNT_ID) { - thumbnailUrl = `https://imagedelivery.net/${c.env.IMAGES_ACCOUNT_ID}/${r2Key}/thumbnail`; - } - const mediaRecord = { - id: fileId, - filename, - original_name: file.name, - mime_type: file.type, - size: file.size, - width, - height, - folder, - r2_key: r2Key, - public_url: publicUrl, - thumbnail_url: thumbnailUrl, - uploaded_by: user.userId, - uploaded_at: Math.floor(Date.now() / 1e3), - created_at: Math.floor(Date.now() / 1e3) - }; - const stmt = c.env.DB.prepare(` - INSERT INTO media ( - id, filename, original_name, mime_type, size, width, height, - folder, r2_key, public_url, thumbnail_url, uploaded_by, uploaded_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await stmt.bind( - mediaRecord.id, - mediaRecord.filename, - mediaRecord.original_name, - mediaRecord.mime_type, - mediaRecord.size, - mediaRecord.width ?? null, - mediaRecord.height ?? null, - mediaRecord.folder, - mediaRecord.r2_key, - mediaRecord.public_url, - mediaRecord.thumbnail_url ?? null, - mediaRecord.uploaded_by, - mediaRecord.uploaded_at - ).run(); - await emitEvent("media.upload", { id: mediaRecord.id, filename: mediaRecord.filename }); - return c.json({ - success: true, - file: { - id: mediaRecord.id, - filename: mediaRecord.filename, - originalName: mediaRecord.original_name, - mimeType: mediaRecord.mime_type, - size: mediaRecord.size, - width: mediaRecord.width, - height: mediaRecord.height, - r2_key: mediaRecord.r2_key, - publicUrl: mediaRecord.public_url, - thumbnailUrl: mediaRecord.thumbnail_url, - uploadedAt: new Date(mediaRecord.uploaded_at * 1e3).toISOString() - } - }); - } catch (error) { - console.error("Upload error:", error); - return c.json({ error: "Upload failed" }, 500); - } -}); -apiMediaRoutes.post("/upload-multiple", async (c) => { - try { - const user = c.get("user"); - const formData = await c.req.formData(); - const filesData = formData.getAll("files"); - const files = []; - for (const f of filesData) { - if (typeof f !== "string") { - files.push(f); - } - } - if (!files || files.length === 0) { - return c.json({ error: "No files provided" }, 400); - } - const uploadResults = []; - const errors = []; - for (const file of files) { - try { - const validation = fileValidationSchema.safeParse({ - name: file.name, - type: file.type, - size: file.size - }); - if (!validation.success) { - errors.push({ - filename: file.name, - error: "Validation failed", - details: validation.error.issues - }); - continue; - } - const fileId = generateId(); - const fileExtension = file.name.split(".").pop() || ""; - const filename = `${fileId}.${fileExtension}`; - const folder = formData.get("folder") || "uploads"; - const r2Key = `${folder}/${filename}`; - const arrayBuffer = await file.arrayBuffer(); - const uploadResult = await c.env.MEDIA_BUCKET.put(r2Key, arrayBuffer, { - httpMetadata: { - contentType: file.type, - contentDisposition: `inline; filename="${file.name}"` - }, - customMetadata: { - originalName: file.name, - uploadedBy: user.userId, - uploadedAt: (/* @__PURE__ */ new Date()).toISOString() - } - }); - if (!uploadResult) { - errors.push({ - filename: file.name, - error: "Failed to upload to storage" - }); - continue; - } - const bucketName = c.env.BUCKET_NAME || "sonicjs-media-dev"; - const publicUrl = `https://pub-${bucketName}.r2.dev/${r2Key}`; - let width; - let height; - if (file.type.startsWith("image/") && !file.type.includes("svg")) { - try { - const dimensions = await getImageDimensions(arrayBuffer); - width = dimensions.width; - height = dimensions.height; - } catch (error) { - console.warn("Failed to extract image dimensions:", error); - } - } - let thumbnailUrl; - if (file.type.startsWith("image/") && c.env.IMAGES_ACCOUNT_ID) { - thumbnailUrl = `https://imagedelivery.net/${c.env.IMAGES_ACCOUNT_ID}/${r2Key}/thumbnail`; - } - const mediaRecord = { - id: fileId, - filename, - original_name: file.name, - mime_type: file.type, - size: file.size, - width, - height, - folder, - r2_key: r2Key, - public_url: publicUrl, - thumbnail_url: thumbnailUrl, - uploaded_by: user.userId, - uploaded_at: Math.floor(Date.now() / 1e3) - }; - const stmt = c.env.DB.prepare(` - INSERT INTO media ( - id, filename, original_name, mime_type, size, width, height, - folder, r2_key, public_url, thumbnail_url, uploaded_by, uploaded_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await stmt.bind( - mediaRecord.id, - mediaRecord.filename, - mediaRecord.original_name, - mediaRecord.mime_type, - mediaRecord.size, - mediaRecord.width ?? null, - mediaRecord.height ?? null, - mediaRecord.folder, - mediaRecord.r2_key, - mediaRecord.public_url, - mediaRecord.thumbnail_url ?? null, - mediaRecord.uploaded_by, - mediaRecord.uploaded_at - ).run(); - uploadResults.push({ - id: mediaRecord.id, - filename: mediaRecord.filename, - originalName: mediaRecord.original_name, - mimeType: mediaRecord.mime_type, - size: mediaRecord.size, - width: mediaRecord.width, - height: mediaRecord.height, - r2_key: mediaRecord.r2_key, - publicUrl: mediaRecord.public_url, - thumbnailUrl: mediaRecord.thumbnail_url, - uploadedAt: new Date(mediaRecord.uploaded_at * 1e3).toISOString() - }); - } catch (error) { - errors.push({ - filename: file.name, - error: "Upload failed", - details: error instanceof Error ? error.message : "Unknown error" - }); - } - } - if (uploadResults.length > 0) { - await emitEvent("media.upload", { count: uploadResults.length }); - } - return c.json({ - success: uploadResults.length > 0, - uploaded: uploadResults, - errors, - summary: { - total: files.length, - successful: uploadResults.length, - failed: errors.length - } - }); - } catch (error) { - console.error("Multiple upload error:", error); - return c.json({ error: "Upload failed" }, 500); - } -}); -apiMediaRoutes.post("/bulk-delete", async (c) => { - try { - const user = c.get("user"); - const body = await c.req.json(); - const fileIds = body.fileIds; - if (!fileIds || !Array.isArray(fileIds) || fileIds.length === 0) { - return c.json({ error: "No file IDs provided" }, 400); - } - if (fileIds.length > 50) { - return c.json({ error: "Too many files selected. Maximum 50 files per operation." }, 400); - } - const results = []; - const errors = []; - for (const fileId of fileIds) { - try { - const stmt = c.env.DB.prepare("SELECT * FROM media WHERE id = ?"); - const fileRecord = await stmt.bind(fileId).first(); - if (!fileRecord) { - errors.push({ fileId, error: "File not found" }); - continue; - } - if (fileRecord.deleted_at !== null) { - console.log(`File ${fileId} already deleted, skipping`); - results.push({ - fileId, - filename: fileRecord.original_name, - success: true, - alreadyDeleted: true - }); - continue; - } - if (fileRecord.uploaded_by !== user.userId && user.role !== "admin") { - errors.push({ fileId, error: "Permission denied" }); - continue; - } - try { - await c.env.MEDIA_BUCKET.delete(fileRecord.r2_key); - } catch (error) { - console.warn(`Failed to delete from R2 for file ${fileId}:`, error); - } - const deleteStmt = c.env.DB.prepare("UPDATE media SET deleted_at = ? WHERE id = ?"); - await deleteStmt.bind(Math.floor(Date.now() / 1e3), fileId).run(); - results.push({ - fileId, - filename: fileRecord.original_name, - success: true - }); - } catch (error) { - errors.push({ - fileId, - error: "Delete failed", - details: error instanceof Error ? error.message : "Unknown error" - }); - } - } - if (results.length > 0) { - await emitEvent("media.delete", { count: results.length, ids: fileIds }); - } - return c.json({ - success: results.length > 0, - deleted: results, - errors, - summary: { - total: fileIds.length, - successful: results.length, - failed: errors.length - } - }); - } catch (error) { - console.error("Bulk delete error:", error); - return c.json({ error: "Bulk delete failed" }, 500); - } -}); -apiMediaRoutes.post("/create-folder", async (c) => { - try { - const body = await c.req.json(); - const folderName = body.folderName; - if (!folderName || typeof folderName !== "string") { - return c.json({ success: false, error: "No folder name provided" }, 400); - } - const folderPattern = /^[a-z0-9-_]+$/; - if (!folderPattern.test(folderName)) { - return c.json({ - success: false, - error: "Folder name can only contain lowercase letters, numbers, hyphens, and underscores" - }, 400); - } - const checkStmt = c.env.DB.prepare("SELECT COUNT(*) as count FROM media WHERE folder = ? AND deleted_at IS NULL"); - const existingFolder = await checkStmt.bind(folderName).first(); - if (existingFolder && existingFolder.count > 0) { - return c.json({ - success: false, - error: `Folder "${folderName}" already exists` - }, 400); - } - return c.json({ - success: true, - message: `Folder "${folderName}" is ready. Upload files to this folder to make it appear in the media library.`, - folder: folderName, - note: "Folders appear automatically when you upload files to them" - }); - } catch (error) { - console.error("Create folder error:", error); - return c.json({ success: false, error: "Failed to create folder" }, 500); - } -}); -apiMediaRoutes.post("/bulk-move", async (c) => { - try { - const user = c.get("user"); - const body = await c.req.json(); - const fileIds = body.fileIds; - const targetFolder = body.folder; - if (!fileIds || !Array.isArray(fileIds) || fileIds.length === 0) { - return c.json({ error: "No file IDs provided" }, 400); - } - if (!targetFolder || typeof targetFolder !== "string") { - return c.json({ error: "No target folder provided" }, 400); - } - if (fileIds.length > 50) { - return c.json({ error: "Too many files selected. Maximum 50 files per operation." }, 400); - } - const results = []; - const errors = []; - for (const fileId of fileIds) { - try { - const stmt = c.env.DB.prepare("SELECT * FROM media WHERE id = ? AND deleted_at IS NULL"); - const fileRecord = await stmt.bind(fileId).first(); - if (!fileRecord) { - errors.push({ fileId, error: "File not found" }); - continue; - } - if (fileRecord.uploaded_by !== user.userId && user.role !== "admin") { - errors.push({ fileId, error: "Permission denied" }); - continue; - } - if (fileRecord.folder === targetFolder) { - results.push({ - fileId, - filename: fileRecord.original_name, - success: true, - skipped: true - }); - continue; - } - const oldR2Key = fileRecord.r2_key; - const filename = oldR2Key.split("/").pop() || fileRecord.filename; - const newR2Key = `${targetFolder}/${filename}`; - try { - const object = await c.env.MEDIA_BUCKET.get(oldR2Key); - if (!object) { - errors.push({ fileId, error: "File not found in storage" }); - continue; - } - await c.env.MEDIA_BUCKET.put(newR2Key, object.body, { - httpMetadata: object.httpMetadata, - customMetadata: { - ...object.customMetadata, - movedBy: user.userId, - movedAt: (/* @__PURE__ */ new Date()).toISOString() - } - }); - await c.env.MEDIA_BUCKET.delete(oldR2Key); - } catch (error) { - console.warn(`Failed to move file in R2 for file ${fileId}:`, error); - errors.push({ fileId, error: "Failed to move file in storage" }); - continue; - } - const bucketName = c.env.BUCKET_NAME || "sonicjs-media-dev"; - const newPublicUrl = `https://pub-${bucketName}.r2.dev/${newR2Key}`; - const updateStmt = c.env.DB.prepare(` - UPDATE media - SET folder = ?, r2_key = ?, public_url = ?, updated_at = ? - WHERE id = ? - `); - await updateStmt.bind( - targetFolder, - newR2Key, - newPublicUrl, - Math.floor(Date.now() / 1e3), - fileId - ).run(); - results.push({ - fileId, - filename: fileRecord.original_name, - success: true, - skipped: false - }); - } catch (error) { - errors.push({ - fileId, - error: "Move failed", - details: error instanceof Error ? error.message : "Unknown error" - }); - } - } - if (results.length > 0) { - await emitEvent("media.move", { count: results.length, targetFolder, ids: fileIds }); - } - return c.json({ - success: results.length > 0, - moved: results, - errors, - summary: { - total: fileIds.length, - successful: results.length, - failed: errors.length - } - }); - } catch (error) { - console.error("Bulk move error:", error); - return c.json({ error: "Bulk move failed" }, 500); - } -}); -apiMediaRoutes.delete("/:id", async (c) => { - try { - const user = c.get("user"); - const fileId = c.req.param("id"); - const stmt = c.env.DB.prepare("SELECT * FROM media WHERE id = ? AND deleted_at IS NULL"); - const fileRecord = await stmt.bind(fileId).first(); - if (!fileRecord) { - return c.json({ error: "File not found" }, 404); - } - if (fileRecord.uploaded_by !== user.userId && user.role !== "admin") { - return c.json({ error: "Permission denied" }, 403); - } - try { - await c.env.MEDIA_BUCKET.delete(fileRecord.r2_key); - } catch (error) { - console.warn("Failed to delete from R2:", error); - } - const deleteStmt = c.env.DB.prepare("UPDATE media SET deleted_at = ? WHERE id = ?"); - await deleteStmt.bind(Math.floor(Date.now() / 1e3), fileId).run(); - await emitEvent("media.delete", { id: fileId }); - return c.json({ success: true, message: "File deleted successfully" }); - } catch (error) { - console.error("Delete error:", error); - return c.json({ error: "Delete failed" }, 500); - } -}); -apiMediaRoutes.patch("/:id", async (c) => { - try { - const user = c.get("user"); - const fileId = c.req.param("id"); - const body = await c.req.json(); - const stmt = c.env.DB.prepare("SELECT * FROM media WHERE id = ? AND deleted_at IS NULL"); - const fileRecord = await stmt.bind(fileId).first(); - if (!fileRecord) { - return c.json({ error: "File not found" }, 404); - } - if (fileRecord.uploaded_by !== user.userId && user.role !== "admin") { - return c.json({ error: "Permission denied" }, 403); - } - const allowedFields = ["alt", "caption", "tags", "folder"]; - const updates = []; - const values = []; - for (const [key, value] of Object.entries(body)) { - if (allowedFields.includes(key)) { - updates.push(`${key} = ?`); - values.push(key === "tags" ? JSON.stringify(value) : value); - } - } - if (updates.length === 0) { - return c.json({ error: "No valid fields to update" }, 400); - } - updates.push("updated_at = ?"); - values.push(Math.floor(Date.now() / 1e3)); - values.push(fileId); - const updateStmt = c.env.DB.prepare(` - UPDATE media SET ${updates.join(", ")} WHERE id = ? - `); - await updateStmt.bind(...values).run(); - await emitEvent("media.update", { id: fileId }); - return c.json({ success: true, message: "File updated successfully" }); - } catch (error) { - console.error("Update error:", error); - return c.json({ error: "Update failed" }, 500); - } -}); -async function getImageDimensions(arrayBuffer) { - const uint8Array = new Uint8Array(arrayBuffer); - if (uint8Array[0] === 255 && uint8Array[1] === 216) { - return getJPEGDimensions(uint8Array); - } - if (uint8Array[0] === 137 && uint8Array[1] === 80 && uint8Array[2] === 78 && uint8Array[3] === 71) { - return getPNGDimensions(uint8Array); - } - return { width: 0, height: 0 }; -} -function getJPEGDimensions(uint8Array) { - let i = 2; - while (i < uint8Array.length) { - if (i + 8 >= uint8Array.length) break; - if (uint8Array[i] === 255 && uint8Array[i + 1] === 192) { - if (i + 8 < uint8Array.length) { - return { - height: uint8Array[i + 5] << 8 | uint8Array[i + 6], - width: uint8Array[i + 7] << 8 | uint8Array[i + 8] - }; - } - } - if (i + 3 < uint8Array.length) { - i += 2 + (uint8Array[i + 2] << 8 | uint8Array[i + 3]); - } else { - break; - } - } - return { width: 0, height: 0 }; -} -function getPNGDimensions(uint8Array) { - if (uint8Array.length < 24) { - return { width: 0, height: 0 }; - } - return { - width: uint8Array[16] << 24 | uint8Array[17] << 16 | uint8Array[18] << 8 | uint8Array[19], - height: uint8Array[20] << 24 | uint8Array[21] << 16 | uint8Array[22] << 8 | uint8Array[23] - }; -} -var api_media_default = apiMediaRoutes; -var apiSystemRoutes = new hono.Hono(); -apiSystemRoutes.get("/health", async (c) => { - try { - const startTime = Date.now(); - let dbStatus = "unknown"; - let dbLatency = 0; - try { - const dbStart = Date.now(); - await c.env.DB.prepare("SELECT 1").first(); - dbLatency = Date.now() - dbStart; - dbStatus = "healthy"; - } catch (error) { - console.error("Database health check failed:", error); - dbStatus = "unhealthy"; - } - let kvStatus = "not_configured"; - let kvLatency = 0; - if (c.env.CACHE_KV) { - try { - const kvStart = Date.now(); - await c.env.CACHE_KV.get("__health_check__"); - kvLatency = Date.now() - kvStart; - kvStatus = "healthy"; - } catch (error) { - console.error("KV health check failed:", error); - kvStatus = "unhealthy"; - } - } - let r2Status = "not_configured"; - if (c.env.MEDIA_BUCKET) { - try { - await c.env.MEDIA_BUCKET.head("__health_check__"); - r2Status = "healthy"; - } catch (error) { - r2Status = "healthy"; - } - } - const totalLatency = Date.now() - startTime; - const overall = dbStatus === "healthy" ? "healthy" : "degraded"; - return c.json({ - status: overall, - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - uptime: totalLatency, - checks: { - database: { - status: dbStatus, - latency: dbLatency - }, - cache: { - status: kvStatus, - latency: kvLatency - }, - storage: { - status: r2Status - } - }, - environment: c.env.ENVIRONMENT || "production" - }); - } catch (error) { - console.error("Health check failed:", error); - return c.json({ - status: "unhealthy", - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - error: "Health check failed" - }, 503); - } -}); -apiSystemRoutes.get("/info", (c) => { - const appVersion = c.get("appVersion") || "1.0.0"; - return c.json({ - name: "SonicJS", - version: appVersion, - description: "Modern headless CMS built on Cloudflare Workers", - endpoints: { - api: "/api", - auth: "/auth", - health: "/api/system/health", - docs: "/docs" - }, - features: { - content: true, - media: true, - auth: true, - collections: true, - caching: !!c.env.CACHE_KV, - storage: !!c.env.MEDIA_BUCKET - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -apiSystemRoutes.get("/stats", async (c) => { - try { - const db = c.env.DB; - const contentStats = await db.prepare(` - SELECT COUNT(*) as total_content - FROM content - WHERE deleted_at IS NULL - `).first(); - const mediaStats = await db.prepare(` - SELECT - COUNT(*) as total_files, - SUM(size) as total_size - FROM media - WHERE deleted_at IS NULL - `).first(); - const userStats = await db.prepare(` - SELECT COUNT(*) as total_users - FROM users - `).first(); - return c.json({ - content: { - total: contentStats?.total_content || 0 - }, - media: { - total_files: mediaStats?.total_files || 0, - total_size_bytes: mediaStats?.total_size || 0, - total_size_mb: Math.round((mediaStats?.total_size || 0) / 1024 / 1024 * 100) / 100 - }, - users: { - total: userStats?.total_users || 0 - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } catch (error) { - console.error("Stats query failed:", error); - return c.json({ error: "Failed to fetch system statistics" }, 500); - } -}); -apiSystemRoutes.get("/ping", async (c) => { - try { - const start = Date.now(); - await c.env.DB.prepare("SELECT 1").first(); - const latency = Date.now() - start; - return c.json({ - pong: true, - latency, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } catch (error) { - console.error("Ping failed:", error); - return c.json({ - pong: false, - error: "Database connection failed" - }, 503); - } -}); -apiSystemRoutes.get("/env", (c) => { - return c.json({ - environment: c.env.ENVIRONMENT || "production", - features: { - database: !!c.env.DB, - cache: !!c.env.CACHE_KV, - media_bucket: !!c.env.MEDIA_BUCKET, - email_queue: !!c.env.EMAIL_QUEUE, - sendgrid: !!c.env.SENDGRID_API_KEY, - cloudflare_images: !!(c.env.IMAGES_ACCOUNT_ID && c.env.IMAGES_API_TOKEN) - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -var api_system_default = apiSystemRoutes; -var adminApiRoutes = new hono.Hono(); -adminApiRoutes.use("*", chunkDVQA5II3_cjs.requireAuth()); -adminApiRoutes.use("*", chunkDVQA5II3_cjs.requireRole(["admin", "editor"])); -adminApiRoutes.get("/stats", async (c) => { - try { - const db = c.env.DB; - let collectionsCount = 0; - try { - const collectionsStmt = db.prepare("SELECT COUNT(*) as count FROM collections WHERE is_active = 1"); - const collectionsResult = await collectionsStmt.first(); - collectionsCount = collectionsResult?.count || 0; - } catch (error) { - console.error("Error fetching collections count:", error); - } - let contentCount = 0; - try { - const contentStmt = db.prepare("SELECT COUNT(*) as count FROM content WHERE deleted_at IS NULL"); - const contentResult = await contentStmt.first(); - contentCount = contentResult?.count || 0; - } catch (error) { - console.error("Error fetching content count:", error); - } - let mediaCount = 0; - let mediaSize = 0; - try { - const mediaStmt = db.prepare("SELECT COUNT(*) as count, COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL"); - const mediaResult = await mediaStmt.first(); - mediaCount = mediaResult?.count || 0; - mediaSize = mediaResult?.total_size || 0; - } catch (error) { - console.error("Error fetching media count:", error); - } - let usersCount = 0; - try { - const usersStmt = db.prepare("SELECT COUNT(*) as count FROM users WHERE is_active = 1"); - const usersResult = await usersStmt.first(); - usersCount = usersResult?.count || 0; - } catch (error) { - console.error("Error fetching users count:", error); - } - return c.json({ - collections: collectionsCount, - contentItems: contentCount, - mediaFiles: mediaCount, - mediaSize, - users: usersCount, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } catch (error) { - console.error("Error fetching stats:", error); - return c.json({ error: "Failed to fetch statistics" }, 500); - } -}); -adminApiRoutes.get("/storage", async (c) => { - try { - const db = c.env.DB; - let databaseSize = 0; - try { - const result = await db.prepare("SELECT 1").run(); - databaseSize = result?.meta?.size_after || 0; - } catch (error) { - console.error("Error fetching database size:", error); - } - let mediaSize = 0; - try { - const mediaStmt = db.prepare("SELECT COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL"); - const mediaResult = await mediaStmt.first(); - mediaSize = mediaResult?.total_size || 0; - } catch (error) { - console.error("Error fetching media size:", error); - } - return c.json({ - databaseSize, - mediaSize, - totalSize: databaseSize + mediaSize, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } catch (error) { - console.error("Error fetching storage usage:", error); - return c.json({ error: "Failed to fetch storage usage" }, 500); - } -}); -adminApiRoutes.get("/activity", async (c) => { - try { - const db = c.env.DB; - const limit = parseInt(c.req.query("limit") || "10"); - const activityStmt = db.prepare(` - SELECT - a.id, - a.action, - a.resource_type, - a.resource_id, - a.details, - a.created_at, - u.email, - u.first_name, - u.last_name - FROM activity_logs a - LEFT JOIN users u ON a.user_id = u.id - WHERE a.resource_type IN ('content', 'collections', 'users', 'media') - ORDER BY a.created_at DESC - LIMIT ? - `); - const { results } = await activityStmt.bind(limit).all(); - const recentActivity = (results || []).map((row) => { - const userName = row.first_name && row.last_name ? `${row.first_name} ${row.last_name}` : row.email || "System"; - let details = {}; - try { - details = row.details ? JSON.parse(row.details) : {}; - } catch (e) { - console.error("Error parsing activity details:", e); - } - return { - id: row.id, - type: row.resource_type, - action: row.action, - resource_id: row.resource_id, - details, - timestamp: new Date(Number(row.created_at)).toISOString(), - user: userName - }; - }); - return c.json({ - data: recentActivity, - count: recentActivity.length, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } catch (error) { - console.error("Error fetching recent activity:", error); - return c.json({ error: "Failed to fetch recent activity" }, 500); - } -}); -var createCollectionSchema = zod.z.object({ - name: zod.z.string().min(1).max(255).regex(/^[a-z0-9_]+$/, "Must contain only lowercase letters, numbers, and underscores"), - displayName: zod.z.string().min(1).max(255).optional(), - display_name: zod.z.string().min(1).max(255).optional(), - description: zod.z.string().optional() -}).refine((data) => data.displayName || data.display_name, { - message: "Either displayName or display_name is required", - path: ["displayName"] -}); -var updateCollectionSchema = zod.z.object({ - display_name: zod.z.string().min(1).max(255).optional(), - description: zod.z.string().optional(), - is_active: zod.z.boolean().optional() -}); -adminApiRoutes.get("/collections", async (c) => { - try { - const db = c.env.DB; - const search = c.req.query("search") || ""; - const includeInactive = c.req.query("includeInactive") === "true"; - let stmt; - let results; - if (search) { - stmt = db.prepare(` - SELECT id, name, display_name, description, created_at, updated_at, is_active, managed - FROM collections - WHERE ${includeInactive ? "1=1" : "is_active = 1"} - AND (name LIKE ? OR display_name LIKE ? OR description LIKE ?) - ORDER BY created_at DESC - `); - const searchParam = `%${search}%`; - const queryResults = await stmt.bind(searchParam, searchParam, searchParam).all(); - results = queryResults.results; - } else { - stmt = db.prepare(` - SELECT id, name, display_name, description, created_at, updated_at, is_active, managed - FROM collections - ${includeInactive ? "" : "WHERE is_active = 1"} - ORDER BY created_at DESC - `); - const queryResults = await stmt.all(); - results = queryResults.results; - } - const fieldCountStmt = db.prepare("SELECT collection_id, COUNT(*) as count FROM content_fields GROUP BY collection_id"); - const { results: fieldCountResults } = await fieldCountStmt.all(); - const fieldCounts = new Map((fieldCountResults || []).map((row) => [String(row.collection_id), Number(row.count)])); - const collections = (results || []).map((row) => ({ - id: row.id, - name: row.name, - display_name: row.display_name, - description: row.description, - created_at: Number(row.created_at), - updated_at: Number(row.updated_at), - is_active: row.is_active === 1, - managed: row.managed === 1, - field_count: fieldCounts.get(String(row.id)) || 0 - })); - return c.json({ - data: collections, - count: collections.length, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } catch (error) { - console.error("Error fetching collections:", error); - return c.json({ error: "Failed to fetch collections" }, 500); - } -}); -adminApiRoutes.get("/collections/:id", async (c) => { - try { - const id = c.req.param("id"); - const db = c.env.DB; - const stmt = db.prepare("SELECT * FROM collections WHERE id = ?"); - const collection = await stmt.bind(id).first(); - if (!collection) { - return c.json({ error: "Collection not found" }, 404); - } - const fieldsStmt = db.prepare(` - SELECT * FROM content_fields - WHERE collection_id = ? - ORDER BY field_order ASC - `); - const { results: fieldsResults } = await fieldsStmt.bind(id).all(); - const fields = (fieldsResults || []).map((row) => ({ - id: row.id, - field_name: row.field_name, - field_type: row.field_type, - field_label: row.field_label, - field_options: row.field_options ? JSON.parse(row.field_options) : {}, - field_order: row.field_order, - is_required: row.is_required === 1, - is_searchable: row.is_searchable === 1, - created_at: Number(row.created_at), - updated_at: Number(row.updated_at) - })); - return c.json({ - id: collection.id, - name: collection.name, - display_name: collection.display_name, - description: collection.description, - is_active: collection.is_active === 1, - managed: collection.managed === 1, - schema: collection.schema ? JSON.parse(collection.schema) : null, - created_at: Number(collection.created_at), - updated_at: Number(collection.updated_at), - fields - }); - } catch (error) { - console.error("Error fetching collection:", error); - return c.json({ error: "Failed to fetch collection" }, 500); - } -}); -adminApiRoutes.get("/references", async (c) => { - try { - const db = c.env.DB; - const url = new URL(c.req.url); - const collectionParams = url.searchParams.getAll("collection").flatMap((value) => value.split(",")).map((value) => value.trim()).filter(Boolean); - const search = c.req.query("search") || ""; - const id = c.req.query("id") || ""; - const limit = Math.min(Number.parseInt(c.req.query("limit") || "20", 10) || 20, 100); - if (collectionParams.length === 0) { - return c.json({ error: "Collection is required" }, 400); - } - const placeholders = collectionParams.map(() => "?").join(", "); - const collectionStmt = db.prepare(` - SELECT id, name, display_name - FROM collections - WHERE id IN (${placeholders}) OR name IN (${placeholders}) - `); - const collectionResults = await collectionStmt.bind(...collectionParams, ...collectionParams).all(); - const collections = collectionResults.results || []; - if (collections.length === 0) { - return c.json({ error: "Collection not found" }, 404); - } - const collectionById = Object.fromEntries( - collections.map((entry) => [ - entry.id, - { - id: entry.id, - name: entry.name, - display_name: entry.display_name - } - ]) - ); - const collectionIds = collections.map((entry) => entry.id); - if (id) { - const idPlaceholders = collectionIds.map(() => "?").join(", "); - const itemStmt = db.prepare(` - SELECT id, title, slug, collection_id - FROM content - WHERE id = ? AND collection_id IN (${idPlaceholders}) - LIMIT 1 - `); - const item = await itemStmt.bind(id, ...collectionIds).first(); - if (!item) { - return c.json({ error: "Reference not found" }, 404); - } - return c.json({ - data: { - id: item.id, - title: item.title, - slug: item.slug, - collection: collectionById[item.collection_id] - } - }); - } - let stmt; - let results; - const listPlaceholders = collectionIds.map(() => "?").join(", "); - const statusFilterValues = ["published"]; - const statusClause = ` AND status IN (${statusFilterValues.map(() => "?").join(", ")})`; - if (search) { - const searchParam = `%${search}%`; - stmt = db.prepare(` - SELECT id, title, slug, status, updated_at, collection_id - FROM content - WHERE collection_id IN (${listPlaceholders}) - AND (title LIKE ? OR slug LIKE ?) - ${statusClause} - ORDER BY updated_at DESC - LIMIT ? - `); - const queryResults = await stmt.bind(...collectionIds, searchParam, searchParam, ...statusFilterValues, limit).all(); - results = queryResults.results; - } else { - stmt = db.prepare(` - SELECT id, title, slug, status, updated_at, collection_id - FROM content - WHERE collection_id IN (${listPlaceholders}) - ${statusClause} - ORDER BY updated_at DESC - LIMIT ? - `); - const queryResults = await stmt.bind(...collectionIds, ...statusFilterValues, limit).all(); - results = queryResults.results; - } - const items = (results || []).map((row) => ({ - id: row.id, - title: row.title, - slug: row.slug, - status: row.status, - updated_at: row.updated_at ? Number(row.updated_at) : null, - collection: collectionById[row.collection_id] - })); - return c.json({ - data: items, - count: items.length - }); - } catch (error) { - console.error("Error fetching reference options:", error); - return c.json({ error: "Failed to fetch references" }, 500); - } -}); -adminApiRoutes.post("/collections", async (c) => { - try { - const contentType = c.req.header("Content-Type"); - if (!contentType || !contentType.includes("application/json")) { - return c.json({ error: "Content-Type must be application/json" }, 400); - } - let body; - try { - body = await c.req.json(); - } catch (e) { - return c.json({ error: "Invalid JSON in request body" }, 400); - } - const validation = createCollectionSchema.safeParse(body); - if (!validation.success) { - return c.json({ error: "Validation failed", details: validation.error.issues }, 400); - } - const validatedData = validation.data; - const db = c.env.DB; - const _user = c.get("user"); - const displayName = validatedData.displayName || validatedData.display_name || ""; - const existingStmt = db.prepare("SELECT id FROM collections WHERE name = ?"); - const existing = await existingStmt.bind(validatedData.name).first(); - if (existing) { - return c.json({ error: "A collection with this name already exists" }, 400); - } - const basicSchema = { - type: "object", - properties: { - title: { - type: "string", - title: "Title", - required: true - }, - content: { - type: "string", - title: "Content", - format: "richtext" - }, - status: { - type: "string", - title: "Status", - enum: ["draft", "published", "archived"], - default: "draft" - } - }, - required: ["title"] - }; - const collectionId = crypto.randomUUID(); - const now = Date.now(); - const insertStmt = db.prepare(` - INSERT INTO collections (id, name, display_name, description, schema, is_active, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - `); - await insertStmt.bind( - collectionId, - validatedData.name, - displayName, - validatedData.description || null, - JSON.stringify(basicSchema), - 1, - // is_active - now, - now - ).run(); - try { - await c.env.CACHE_KV.delete("cache:collections:all"); - await c.env.CACHE_KV.delete(`cache:collection:${validatedData.name}`); - } catch (e) { - console.error("Error clearing cache:", e); - } - return c.json({ - id: collectionId, - name: validatedData.name, - displayName, - description: validatedData.description, - created_at: now - }, 201); - } catch (error) { - console.error("Error creating collection:", error); - return c.json({ error: "Failed to create collection" }, 500); - } -}); -adminApiRoutes.patch("/collections/:id", async (c) => { - try { - const id = c.req.param("id"); - const body = await c.req.json(); - const validation = updateCollectionSchema.safeParse(body); - if (!validation.success) { - return c.json({ error: "Validation failed", details: validation.error.issues }, 400); - } - const validatedData = validation.data; - const db = c.env.DB; - const checkStmt = db.prepare("SELECT * FROM collections WHERE id = ?"); - const existing = await checkStmt.bind(id).first(); - if (!existing) { - return c.json({ error: "Collection not found" }, 404); - } - const updateFields = []; - const updateParams = []; - if (validatedData.display_name !== void 0) { - updateFields.push("display_name = ?"); - updateParams.push(validatedData.display_name); - } - if (validatedData.description !== void 0) { - updateFields.push("description = ?"); - updateParams.push(validatedData.description); - } - if (validatedData.is_active !== void 0) { - updateFields.push("is_active = ?"); - updateParams.push(validatedData.is_active ? 1 : 0); - } - if (updateFields.length === 0) { - return c.json({ error: "No fields to update" }, 400); - } - updateFields.push("updated_at = ?"); - updateParams.push(Date.now()); - updateParams.push(id); - const updateStmt = db.prepare(` - UPDATE collections - SET ${updateFields.join(", ")} - WHERE id = ? - `); - await updateStmt.bind(...updateParams).run(); - try { - await c.env.CACHE_KV.delete("cache:collections:all"); - await c.env.CACHE_KV.delete(`cache:collection:${existing.name}`); - } catch (e) { - console.error("Error clearing cache:", e); - } - return c.json({ message: "Collection updated successfully" }); - } catch (error) { - console.error("Error updating collection:", error); - return c.json({ error: "Failed to update collection" }, 500); - } -}); -adminApiRoutes.delete("/collections/:id", async (c) => { - try { - const id = c.req.param("id"); - const db = c.env.DB; - const collectionStmt = db.prepare("SELECT name FROM collections WHERE id = ?"); - const collection = await collectionStmt.bind(id).first(); - if (!collection) { - return c.json({ error: "Collection not found" }, 404); - } - const contentStmt = db.prepare("SELECT COUNT(*) as count FROM content WHERE collection_id = ?"); - const contentResult = await contentStmt.bind(id).first(); - if (contentResult && contentResult.count > 0) { - return c.json({ - error: `Cannot delete collection: it contains ${contentResult.count} content item(s). Delete all content first.` - }, 400); - } - const deleteFieldsStmt = db.prepare("DELETE FROM content_fields WHERE collection_id = ?"); - await deleteFieldsStmt.bind(id).run(); - const deleteStmt = db.prepare("DELETE FROM collections WHERE id = ?"); - await deleteStmt.bind(id).run(); - try { - await c.env.CACHE_KV.delete("cache:collections:all"); - await c.env.CACHE_KV.delete(`cache:collection:${collection.name}`); - } catch (e) { - console.error("Error clearing cache:", e); - } - return c.json({ message: "Collection deleted successfully" }); - } catch (error) { - console.error("Error deleting collection:", error); - return c.json({ error: "Failed to delete collection" }, 500); - } -}); -adminApiRoutes.get("/migrations/status", async (c) => { - try { - const { MigrationService: MigrationService2 } = await import('./migrations-VH7IQRJT.cjs'); - const db = c.env.DB; - const migrationService = new MigrationService2(db); - const status = await migrationService.getMigrationStatus(); - return c.json({ - success: true, - data: status - }); - } catch (error) { - console.error("Error fetching migration status:", error); - return c.json({ - success: false, - error: "Failed to fetch migration status" - }, 500); - } -}); -adminApiRoutes.post("/migrations/run", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.json({ - success: false, - error: "Unauthorized. Admin access required." - }, 403); - } - const { MigrationService: MigrationService2 } = await import('./migrations-VH7IQRJT.cjs'); - const db = c.env.DB; - const migrationService = new MigrationService2(db); - const result = await migrationService.runPendingMigrations(); - return c.json({ - success: result.success, - message: result.message, - applied: result.applied - }); - } catch (error) { - console.error("Error running migrations:", error); - return c.json({ - success: false, - error: "Failed to run migrations" - }, 500); - } -}); -adminApiRoutes.get("/migrations/validate", async (c) => { - try { - const { MigrationService: MigrationService2 } = await import('./migrations-VH7IQRJT.cjs'); - const db = c.env.DB; - const migrationService = new MigrationService2(db); - const validation = await migrationService.validateSchema(); - return c.json({ - success: true, - data: validation - }); - } catch (error) { - console.error("Error validating schema:", error); - return c.json({ - success: false, - error: "Failed to validate schema" - }, 500); - } -}); -var admin_api_default = adminApiRoutes; - -// src/templates/pages/auth-login.template.ts -function renderLoginPage(data, demoLoginActive = false) { - return ` - - - - - - Login - SonicJS AI - - - - - - - -
- -
-
- -
-

Welcome Back

-

Sign in to your account to continue

-
- - -
-
- - ${data.error ? `
${chunkSHCYIZAN_cjs.renderAlert({ type: "error", message: data.error })}
` : ""} - ${data.message ? `
${chunkSHCYIZAN_cjs.renderAlert({ type: "success", message: data.message })}
` : ""} - - -
- - -
- -
- - -
- - -
- - -
- - - -
- - -
-

- Don't have an account? - Create one here -

-
-
- - -
- - v${data.version || "0.1.0"} - -
-
-
- - ${demoLoginActive ? ` - - ` : ""} - - - `; -} - -// src/templates/pages/auth-register.template.ts -function renderRegisterPage(data) { - return ` - - - - - - Register - SonicJS AI - - - - - - - -
- -
-
- - - -
-

SonicJS AI

-

Create your account and get started

-
- - -
-
- - ${data.error ? `
${chunkSHCYIZAN_cjs.renderAlert({ type: "error", message: data.error })}
` : ""} - - -
- -
-
- - -
-
- - -
-
- - -
- - -
- - -
- - -
- - -
- - -
- - - -
- - -
-

- Already have an account? - Sign in here -

-
- -
-
-
-
- - - `; -} -async function isRegistrationEnabled(db) { - try { - const plugin = await db.prepare("SELECT settings FROM plugins WHERE id = ?").bind("core-auth").first(); - if (plugin?.settings) { - const settings = JSON.parse(plugin.settings); - const enabled = settings?.registration?.enabled; - return enabled !== false && enabled !== 0; - } - return true; - } catch { - return true; - } -} -async function isFirstUserRegistration(db) { - try { - const result = await db.prepare("SELECT COUNT(*) as count FROM users").first(); - return result?.count === 0; - } catch { - return false; - } -} -var baseRegistrationSchema = zod.z.object({ - email: zod.z.string().email("Valid email is required"), - password: zod.z.string().min(8, "Password must be at least 8 characters"), - username: zod.z.string().min(3, "Username must be at least 3 characters").optional(), - firstName: zod.z.string().min(1, "First name is required").optional(), - lastName: zod.z.string().min(1, "Last name is required").optional() -}); -var authValidationService = { - /** - * Build registration schema dynamically based on auth settings - * For now, returns a static schema with standard fields - */ - async buildRegistrationSchema(_db) { - return baseRegistrationSchema; - }, - /** - * Generate default values for optional fields - */ - generateDefaultValue(field, data) { - switch (field) { - case "username": - return data.email ? data.email.split("@")[0] : `user${Date.now()}`; - case "firstName": - return "User"; - case "lastName": - return data.email ? data.email.split("@")[0] : "Account"; - default: - return ""; - } - } -}; - -// src/routes/auth.ts -var authRoutes = new hono.Hono(); -authRoutes.get("/login", async (c) => { - const error = c.req.query("error"); - const message = c.req.query("message"); - const pageData = { - error: error || void 0, - message: message || void 0, - version: c.get("appVersion") - }; - const db = c.env.DB; - let demoLoginActive = false; - try { - const plugin = await db.prepare("SELECT * FROM plugins WHERE id = ? AND status = ?").bind("demo-login-prefill", "active").first(); - demoLoginActive = !!plugin; - } catch (error2) { - } - return c.html(renderLoginPage(pageData, demoLoginActive)); -}); -authRoutes.get("/register", async (c) => { - const db = c.env.DB; - const isFirstUser = await isFirstUserRegistration(db); - if (!isFirstUser) { - const registrationEnabled = await isRegistrationEnabled(db); - if (!registrationEnabled) { - return c.redirect("/auth/login?error=Registration is currently disabled"); - } - } - const error = c.req.query("error"); - const pageData = { - error: error || void 0 - }; - return c.html(renderRegisterPage(pageData)); -}); -var loginSchema = zod.z.object({ - email: zod.z.string().email("Valid email is required"), - password: zod.z.string().min(1, "Password is required") -}); -authRoutes.post( - "/register", - async (c) => { - try { - const db = c.env.DB; - const isFirstUser = await isFirstUserRegistration(db); - if (!isFirstUser) { - const registrationEnabled = await isRegistrationEnabled(db); - if (!registrationEnabled) { - return c.json({ error: "Registration is currently disabled" }, 403); - } - } - let requestData; - try { - requestData = await c.req.json(); - } catch (parseError) { - return c.json({ error: "Invalid JSON in request body" }, 400); - } - const validationSchema = await authValidationService.buildRegistrationSchema(db); - let validatedData; - try { - validatedData = await validationSchema.parseAsync(requestData); - } catch (validationError) { - return c.json({ - error: "Validation failed", - details: validationError.issues?.map((e) => e.message) || [validationError.message || "Invalid request data"] - }, 400); - } - const email = validatedData.email; - const password = validatedData.password; - const username = validatedData.username || authValidationService.generateDefaultValue("username", validatedData); - const firstName = validatedData.firstName || authValidationService.generateDefaultValue("firstName", validatedData); - const lastName = validatedData.lastName || authValidationService.generateDefaultValue("lastName", validatedData); - const normalizedEmail = email.toLowerCase(); - const existingUser = await db.prepare("SELECT id FROM users WHERE email = ? OR username = ?").bind(normalizedEmail, username).first(); - if (existingUser) { - return c.json({ error: "User with this email or username already exists" }, 400); - } - const passwordHash = await chunkDVQA5II3_cjs.AuthManager.hashPassword(password); - const userId = crypto.randomUUID(); - const now = /* @__PURE__ */ new Date(); - await db.prepare(` - INSERT INTO users (id, email, username, first_name, last_name, password_hash, role, is_active, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).bind( - userId, - normalizedEmail, - username, - firstName, - lastName, - passwordHash, - "viewer", - // Default role - 1, - // is_active - now.getTime(), - now.getTime() - ).run(); - const token = await chunkDVQA5II3_cjs.AuthManager.generateToken(userId, normalizedEmail, "viewer"); - cookie.setCookie(c, "auth_token", token, { - httpOnly: true, - secure: true, - sameSite: "Strict", - maxAge: 60 * 60 * 24 - // 24 hours - }); - return c.json({ - user: { - id: userId, - email: normalizedEmail, - username, - firstName, - lastName, - role: "viewer" - }, - token - }, 201); - } catch (error) { - console.error("Registration error:", error); - if (error instanceof Error && error.message.includes("validation")) { - return c.json({ error: error.message }, 400); - } - return c.json({ - error: "Registration failed", - details: error instanceof Error ? error.message : String(error) - }, 500); - } - } -); -authRoutes.post("/login", async (c) => { - try { - const body = await c.req.json(); - const validation = loginSchema.safeParse(body); - if (!validation.success) { - return c.json({ error: "Validation failed", details: validation.error.issues }, 400); - } - const { email, password } = validation.data; - const db = c.env.DB; - const normalizedEmail = email.toLowerCase(); - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.user); - let user = await cache.get(cache.generateKey("user", `email:${normalizedEmail}`)); - if (!user) { - user = await db.prepare("SELECT * FROM users WHERE email = ? AND is_active = 1").bind(normalizedEmail).first(); - if (user) { - await cache.set(cache.generateKey("user", `email:${normalizedEmail}`), user); - await cache.set(cache.generateKey("user", user.id), user); - } - } - if (!user) { - return c.json({ error: "Invalid email or password" }, 401); - } - const isValidPassword = await chunkDVQA5II3_cjs.AuthManager.verifyPassword(password, user.password_hash); - if (!isValidPassword) { - return c.json({ error: "Invalid email or password" }, 401); - } - const token = await chunkDVQA5II3_cjs.AuthManager.generateToken(user.id, user.email, user.role); - cookie.setCookie(c, "auth_token", token, { - httpOnly: true, - secure: true, - sameSite: "Strict", - maxAge: 60 * 60 * 24 - // 24 hours - }); - await db.prepare("UPDATE users SET last_login_at = ? WHERE id = ?").bind((/* @__PURE__ */ new Date()).getTime(), user.id).run(); - await cache.delete(cache.generateKey("user", user.id)); - await cache.delete(cache.generateKey("user", `email:${normalizedEmail}`)); - return c.json({ - user: { - id: user.id, - email: user.email, - username: user.username, - firstName: user.first_name, - lastName: user.last_name, - role: user.role - }, - token - }); - } catch (error) { - console.error("Login error:", error); - return c.json({ error: "Login failed" }, 500); - } -}); -authRoutes.post("/logout", (c) => { - cookie.setCookie(c, "auth_token", "", { - httpOnly: true, - secure: false, - // Set to true in production with HTTPS - sameSite: "Strict", - maxAge: 0 - // Expire immediately - }); - return c.json({ message: "Logged out successfully" }); -}); -authRoutes.get("/logout", (c) => { - cookie.setCookie(c, "auth_token", "", { - httpOnly: true, - secure: false, - // Set to true in production with HTTPS - sameSite: "Strict", - maxAge: 0 - // Expire immediately - }); - return c.redirect("/auth/login?message=You have been logged out successfully"); -}); -authRoutes.get("/me", chunkDVQA5II3_cjs.requireAuth(), async (c) => { - try { - const user = c.get("user"); - if (!user) { - return c.json({ error: "Not authenticated" }, 401); - } - const db = c.env.DB; - const userData = await db.prepare("SELECT id, email, username, first_name, last_name, role, created_at FROM users WHERE id = ?").bind(user.userId).first(); - if (!userData) { - return c.json({ error: "User not found" }, 404); - } - return c.json({ user: userData }); - } catch (error) { - console.error("Get user error:", error); - return c.json({ error: "Failed to get user" }, 500); - } -}); -authRoutes.post("/refresh", chunkDVQA5II3_cjs.requireAuth(), async (c) => { - try { - const user = c.get("user"); - if (!user) { - return c.json({ error: "Not authenticated" }, 401); - } - const token = await chunkDVQA5II3_cjs.AuthManager.generateToken(user.userId, user.email, user.role); - cookie.setCookie(c, "auth_token", token, { - httpOnly: true, - secure: true, - sameSite: "Strict", - maxAge: 60 * 60 * 24 - // 24 hours - }); - return c.json({ token }); - } catch (error) { - console.error("Token refresh error:", error); - return c.json({ error: "Token refresh failed" }, 500); - } -}); -authRoutes.post("/register/form", async (c) => { - try { - const db = c.env.DB; - const isFirstUser = await isFirstUserRegistration(db); - if (!isFirstUser) { - const registrationEnabled = await isRegistrationEnabled(db); - if (!registrationEnabled) { - return c.html(html.html` -
- Registration is currently disabled. Please contact an administrator. -
- `); - } - } - const formData = await c.req.formData(); - const requestData = { - email: formData.get("email"), - password: formData.get("password"), - username: formData.get("username"), - firstName: formData.get("firstName"), - lastName: formData.get("lastName") - }; - const normalizedEmail = requestData.email?.toLowerCase(); - requestData.email = normalizedEmail; - const validationSchema = await authValidationService.buildRegistrationSchema(db); - const validation = await validationSchema.safeParseAsync(requestData); - if (!validation.success) { - return c.html(html.html` -
- ${validation.error.issues.map((err) => err.message).join(", ")} -
- `); - } - const validatedData = validation.data; - const password = validatedData.password; - const username = validatedData.username || authValidationService.generateDefaultValue("username", validatedData); - const firstName = validatedData.firstName || authValidationService.generateDefaultValue("firstName", validatedData); - const lastName = validatedData.lastName || authValidationService.generateDefaultValue("lastName", validatedData); - const existingUser = await db.prepare("SELECT id FROM users WHERE email = ? OR username = ?").bind(normalizedEmail, username).first(); - if (existingUser) { - return c.html(html.html` -
- User with this email or username already exists -
- `); - } - const passwordHash = await chunkDVQA5II3_cjs.AuthManager.hashPassword(password); - const role = isFirstUser ? "admin" : "viewer"; - const userId = crypto.randomUUID(); - const now = /* @__PURE__ */ new Date(); - await db.prepare(` - INSERT INTO users (id, email, username, first_name, last_name, password_hash, role, is_active, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).bind( - userId, - normalizedEmail, - username, - firstName, - lastName, - passwordHash, - role, - 1, - // is_active - now.getTime(), - now.getTime() - ).run(); - const token = await chunkDVQA5II3_cjs.AuthManager.generateToken(userId, normalizedEmail, role); - cookie.setCookie(c, "auth_token", token, { - httpOnly: true, - secure: false, - // Set to true in production with HTTPS - sameSite: "Strict", - maxAge: 60 * 60 * 24 - // 24 hours - }); - const redirectUrl = role === "admin" ? "/admin/dashboard" : "/admin/dashboard"; - return c.html(html.html` -
- Account created successfully! Redirecting... - -
- `); - } catch (error) { - console.error("Registration error:", error); - return c.html(html.html` -
- Registration failed. Please try again. -
- `); - } -}); -authRoutes.post("/login/form", async (c) => { - try { - const formData = await c.req.formData(); - const email = formData.get("email"); - const password = formData.get("password"); - const normalizedEmail = email.toLowerCase(); - const validation = loginSchema.safeParse({ email: normalizedEmail, password }); - if (!validation.success) { - return c.html(html.html` -
- ${validation.error.issues.map((err) => err.message).join(", ")} -
- `); - } - const db = c.env.DB; - const user = await db.prepare("SELECT * FROM users WHERE email = ? AND is_active = 1").bind(normalizedEmail).first(); - if (!user) { - return c.html(html.html` -
- Invalid email or password -
- `); - } - const isValidPassword = await chunkDVQA5II3_cjs.AuthManager.verifyPassword(password, user.password_hash); - if (!isValidPassword) { - return c.html(html.html` -
- Invalid email or password -
- `); - } - const token = await chunkDVQA5II3_cjs.AuthManager.generateToken(user.id, user.email, user.role); - cookie.setCookie(c, "auth_token", token, { - httpOnly: true, - secure: false, - // Set to true in production with HTTPS - sameSite: "Strict", - maxAge: 60 * 60 * 24 - // 24 hours - }); - await db.prepare("UPDATE users SET last_login_at = ? WHERE id = ?").bind((/* @__PURE__ */ new Date()).getTime(), user.id).run(); - return c.html(html.html` -
-
-
- - - -
-

Login successful! Redirecting to admin dashboard...

-
-
- -
-
- `); - } catch (error) { - console.error("Login error:", error); - return c.html(html.html` -
- Login failed. Please try again. -
- `); - } -}); -authRoutes.post("/seed-admin", async (c) => { - try { - const db = c.env.DB; - await db.prepare(` - CREATE TABLE IF NOT EXISTS users ( - id TEXT PRIMARY KEY, - email TEXT NOT NULL UNIQUE, - username TEXT NOT NULL UNIQUE, - first_name TEXT NOT NULL, - last_name TEXT NOT NULL, - password_hash TEXT, - role TEXT NOT NULL DEFAULT 'viewer', - avatar TEXT, - is_active INTEGER NOT NULL DEFAULT 1, - last_login_at INTEGER, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL - ) - `).run(); - const existingAdmin = await db.prepare("SELECT id FROM users WHERE email = ? OR username = ?").bind("admin@sonicjs.com", "admin").first(); - if (existingAdmin) { - const passwordHash2 = await chunkDVQA5II3_cjs.AuthManager.hashPassword("sonicjs!"); - await db.prepare("UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?").bind(passwordHash2, Date.now(), existingAdmin.id).run(); - return c.json({ - message: "Admin user already exists (password updated)", - user: { - id: existingAdmin.id, - email: "admin@sonicjs.com", - username: "admin", - role: "admin" - } - }); - } - const passwordHash = await chunkDVQA5II3_cjs.AuthManager.hashPassword("sonicjs!"); - const userId = "admin-user-id"; - const now = Date.now(); - const adminEmail = "admin@sonicjs.com".toLowerCase(); - await db.prepare(` - INSERT INTO users (id, email, username, first_name, last_name, password_hash, role, is_active, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).bind( - userId, - adminEmail, - "admin", - "Admin", - "User", - passwordHash, - "admin", - 1, - // is_active - now, - now - ).run(); - return c.json({ - message: "Admin user created successfully", - user: { - id: userId, - email: adminEmail, - username: "admin", - role: "admin" - }, - passwordHash - // For debugging - }); - } catch (error) { - console.error("Seed admin error:", error); - return c.json({ error: "Failed to create admin user", details: error instanceof Error ? error.message : String(error) }, 500); - } -}); -authRoutes.get("/accept-invitation", async (c) => { - try { - const token = c.req.query("token"); - if (!token) { - return c.html(` - - Invalid Invitation - -

Invalid Invitation

-

The invitation link is invalid or has expired.

- Go to Login - - - `); - } - const db = c.env.DB; - const userStmt = db.prepare(` - SELECT id, email, first_name, last_name, role, invited_at - FROM users - WHERE invitation_token = ? AND is_active = 0 - `); - const invitedUser = await userStmt.bind(token).first(); - if (!invitedUser) { - return c.html(` - - Invalid Invitation - -

Invalid Invitation

-

The invitation link is invalid or has expired.

- Go to Login - - - `); - } - const invitationAge = Date.now() - invitedUser.invited_at; - const maxAge = 7 * 24 * 60 * 60 * 1e3; - if (invitationAge > maxAge) { - return c.html(` - - Invitation Expired - -

Invitation Expired

-

This invitation has expired. Please contact your administrator for a new invitation.

- Go to Login - - - `); - } - return c.html(` - - - - - - Accept Invitation - SonicJS AI - - - - -
-
-
-
- - - -
-

Accept Invitation

-

Complete your account setup

-

- You've been invited as ${invitedUser.first_name} ${invitedUser.last_name}
- ${invitedUser.email}
- ${invitedUser.role} -

-
- -
- - -
- - -
- -
- - -

Password must be at least 8 characters long

-
- -
- - -
- - -
-
-
- - - `); - } catch (error) { - console.error("Accept invitation page error:", error); - return c.html(` - - Error - -

Error

-

An error occurred while processing your invitation.

- Go to Login - - - `); - } -}); -authRoutes.post("/accept-invitation", async (c) => { - try { - const formData = await c.req.formData(); - const token = formData.get("token")?.toString(); - const username = formData.get("username")?.toString()?.trim(); - const password = formData.get("password")?.toString(); - const confirmPassword = formData.get("confirm_password")?.toString(); - if (!token || !username || !password || !confirmPassword) { - return c.json({ error: "All fields are required" }, 400); - } - if (password !== confirmPassword) { - return c.json({ error: "Passwords do not match" }, 400); - } - if (password.length < 8) { - return c.json({ error: "Password must be at least 8 characters long" }, 400); - } - const db = c.env.DB; - const userStmt = db.prepare(` - SELECT id, email, first_name, last_name, role, invited_at - FROM users - WHERE invitation_token = ? AND is_active = 0 - `); - const invitedUser = await userStmt.bind(token).first(); - if (!invitedUser) { - return c.json({ error: "Invalid or expired invitation" }, 400); - } - const invitationAge = Date.now() - invitedUser.invited_at; - const maxAge = 7 * 24 * 60 * 60 * 1e3; - if (invitationAge > maxAge) { - return c.json({ error: "Invitation has expired" }, 400); - } - const existingUsernameStmt = db.prepare(` - SELECT id FROM users WHERE username = ? AND id != ? - `); - const existingUsername = await existingUsernameStmt.bind(username, invitedUser.id).first(); - if (existingUsername) { - return c.json({ error: "Username is already taken" }, 400); - } - const passwordHash = await chunkDVQA5II3_cjs.AuthManager.hashPassword(password); - const updateStmt = db.prepare(` - UPDATE users SET - username = ?, - password_hash = ?, - is_active = 1, - email_verified = 1, - invitation_token = NULL, - accepted_invitation_at = ?, - updated_at = ? - WHERE id = ? - `); - await updateStmt.bind( - username, - passwordHash, - Date.now(), - Date.now(), - invitedUser.id - ).run(); - const authToken = await chunkDVQA5II3_cjs.AuthManager.generateToken(invitedUser.id, invitedUser.email, invitedUser.role); - cookie.setCookie(c, "auth_token", authToken, { - httpOnly: true, - secure: true, - sameSite: "Strict", - maxAge: 60 * 60 * 24 - // 24 hours - }); - return c.redirect("/admin/dashboard?welcome=true"); - } catch (error) { - console.error("Accept invitation error:", error); - return c.json({ error: "Failed to accept invitation" }, 500); - } -}); -authRoutes.post("/request-password-reset", async (c) => { - try { - const formData = await c.req.formData(); - const email = formData.get("email")?.toString()?.trim()?.toLowerCase(); - if (!email) { - return c.json({ error: "Email is required" }, 400); - } - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailRegex.test(email)) { - return c.json({ error: "Please enter a valid email address" }, 400); - } - const db = c.env.DB; - const userStmt = db.prepare(` - SELECT id, email, first_name, last_name FROM users - WHERE email = ? AND is_active = 1 - `); - const user = await userStmt.bind(email).first(); - if (!user) { - return c.json({ - success: true, - message: "If an account with this email exists, a password reset link has been sent." - }); - } - const resetToken = crypto.randomUUID(); - const resetExpires = Date.now() + 60 * 60 * 1e3; - const updateStmt = db.prepare(` - UPDATE users SET - password_reset_token = ?, - password_reset_expires = ?, - updated_at = ? - WHERE id = ? - `); - await updateStmt.bind( - resetToken, - resetExpires, - Date.now(), - user.id - ).run(); - const resetLink = `${c.req.header("origin") || "http://localhost:8787"}/auth/reset-password?token=${resetToken}`; - return c.json({ - success: true, - message: "If an account with this email exists, a password reset link has been sent.", - reset_link: resetLink - // In production, this would be sent via email - }); - } catch (error) { - console.error("Password reset request error:", error); - return c.json({ error: "Failed to process password reset request" }, 500); - } -}); -authRoutes.get("/reset-password", async (c) => { - try { - const token = c.req.query("token"); - if (!token) { - return c.html(` - - Invalid Reset Link - -

Invalid Reset Link

-

The password reset link is invalid or has expired.

- Go to Login - - - `); - } - const db = c.env.DB; - const userStmt = db.prepare(` - SELECT id, email, first_name, last_name, password_reset_expires - FROM users - WHERE password_reset_token = ? AND is_active = 1 - `); - const user = await userStmt.bind(token).first(); - if (!user) { - return c.html(` - - Invalid Reset Link - -

Invalid Reset Link

-

The password reset link is invalid or has already been used.

- Go to Login - - - `); - } - if (Date.now() > user.password_reset_expires) { - return c.html(` - - Reset Link Expired - -

Reset Link Expired

-

The password reset link has expired. Please request a new one.

- Go to Login - - - `); - } - return c.html(` - - - - - - Reset Password - SonicJS AI - - - - -
-
-
-
- - - -
-

Reset Password

-

Choose a new password for your account

-

- Reset password for ${user.first_name} ${user.last_name}
- ${user.email} -

-
- -
- - -
- - -

Password must be at least 8 characters long

-
- -
- - -
- - -
- - -
-
- - - `); - } catch (error) { - console.error("Password reset page error:", error); - return c.html(` - - Error - -

Error

-

An error occurred while processing your password reset.

- Go to Login - - - `); - } -}); -authRoutes.post("/reset-password", async (c) => { - try { - const formData = await c.req.formData(); - const token = formData.get("token")?.toString(); - const password = formData.get("password")?.toString(); - const confirmPassword = formData.get("confirm_password")?.toString(); - if (!token || !password || !confirmPassword) { - return c.json({ error: "All fields are required" }, 400); - } - if (password !== confirmPassword) { - return c.json({ error: "Passwords do not match" }, 400); - } - if (password.length < 8) { - return c.json({ error: "Password must be at least 8 characters long" }, 400); - } - const db = c.env.DB; - const userStmt = db.prepare(` - SELECT id, email, password_hash, password_reset_expires - FROM users - WHERE password_reset_token = ? AND is_active = 1 - `); - const user = await userStmt.bind(token).first(); - if (!user) { - return c.json({ error: "Invalid or expired reset token" }, 400); - } - if (Date.now() > user.password_reset_expires) { - return c.json({ error: "Reset token has expired" }, 400); - } - const newPasswordHash = await chunkDVQA5II3_cjs.AuthManager.hashPassword(password); - try { - const historyStmt = db.prepare(` - INSERT INTO password_history (id, user_id, password_hash, created_at) - VALUES (?, ?, ?, ?) - `); - await historyStmt.bind( - crypto.randomUUID(), - user.id, - user.password_hash, - Date.now() - ).run(); - } catch (historyError) { - console.warn("Could not store password history:", historyError); - } - const updateStmt = db.prepare(` - UPDATE users SET - password_hash = ?, - password_reset_token = NULL, - password_reset_expires = NULL, - updated_at = ? - WHERE id = ? - `); - await updateStmt.bind( - newPasswordHash, - Date.now(), - user.id - ).run(); - return c.redirect("/auth/login?message=Password reset successfully. Please log in with your new password."); - } catch (error) { - console.error("Password reset error:", error); - return c.json({ error: "Failed to reset password" }, 500); - } -}); -var auth_default = authRoutes; -var app = new hono.Hono(); -app.post("/test-cleanup", async (c) => { - const db = c.env.DB; - if (c.env.ENVIRONMENT === "production") { - return c.json({ error: "Cleanup endpoint not available in production" }, 403); - } - try { - let deletedCount = 0; - await db.prepare(` - DELETE FROM content_versions - WHERE content_id IN ( - SELECT id FROM content - WHERE title LIKE 'Test %' OR title LIKE '%E2E%' OR title LIKE '%Playwright%' OR title LIKE '%Sample%' - ) - `).run(); - await db.prepare(` - DELETE FROM workflow_history - WHERE content_id IN ( - SELECT id FROM content - WHERE title LIKE 'Test %' OR title LIKE '%E2E%' OR title LIKE '%Playwright%' OR title LIKE '%Sample%' - ) - `).run(); - try { - await db.prepare(` - DELETE FROM content_data - WHERE content_id IN ( - SELECT id FROM content - WHERE title LIKE 'Test %' OR title LIKE '%E2E%' OR title LIKE '%Playwright%' OR title LIKE '%Sample%' - ) - `).run(); - } catch (e) { - } - const contentResult = await db.prepare(` - DELETE FROM content - WHERE title LIKE 'Test %' OR title LIKE '%E2E%' OR title LIKE '%Playwright%' OR title LIKE '%Sample%' - `).run(); - deletedCount += contentResult.meta?.changes || 0; - await db.prepare(` - DELETE FROM api_tokens - WHERE user_id IN ( - SELECT id FROM users - WHERE email != 'admin@sonicjs.com' AND (email LIKE '%test%' OR email LIKE '%example.com%') - ) - `).run(); - await db.prepare(` - DELETE FROM media - WHERE uploaded_by IN ( - SELECT id FROM users - WHERE email != 'admin@sonicjs.com' AND (email LIKE '%test%' OR email LIKE '%example.com%') - ) - `).run(); - const usersResult = await db.prepare(` - DELETE FROM users - WHERE email != 'admin@sonicjs.com' AND (email LIKE '%test%' OR email LIKE '%example.com%') - `).run(); - deletedCount += usersResult.meta?.changes || 0; - try { - await db.prepare(` - DELETE FROM collection_fields - WHERE collection_id IN ( - SELECT id FROM collections - WHERE name LIKE 'test_%' OR name IN ('blog_posts', 'test_collection', 'products', 'articles') - ) - `).run(); - } catch (e) { - } - await db.prepare(` - DELETE FROM content - WHERE collection_id IN ( - SELECT id FROM collections - WHERE name LIKE 'test_%' OR name IN ('blog_posts', 'test_collection', 'products', 'articles') - ) - `).run(); - const collectionsResult = await db.prepare(` - DELETE FROM collections - WHERE name LIKE 'test_%' OR name IN ('blog_posts', 'test_collection', 'products', 'articles') - `).run(); - deletedCount += collectionsResult.meta?.changes || 0; - try { - await db.prepare(` - DELETE FROM content_data WHERE content_id NOT IN (SELECT id FROM content) - `).run(); - } catch (e) { - } - try { - await db.prepare(` - DELETE FROM collection_fields WHERE collection_id NOT IN (SELECT id FROM collections) - `).run(); - } catch (e) { - } - try { - await db.prepare(` - DELETE FROM content_versions WHERE content_id NOT IN (SELECT id FROM content) - `).run(); - } catch (e) { - } - try { - await db.prepare(` - DELETE FROM workflow_history WHERE content_id NOT IN (SELECT id FROM content) - `).run(); - } catch (e) { - } - await db.prepare(` - DELETE FROM activity_logs - WHERE id NOT IN ( - SELECT id FROM activity_logs - ORDER BY created_at DESC - LIMIT 100 - ) - `).run(); - return c.json({ - success: true, - deletedCount, - message: "Test data cleaned up successfully" - }); - } catch (error) { - console.error("Test cleanup error:", error); - return c.json({ - success: false, - error: error instanceof Error ? error.message : "Unknown error" - }, 500); - } -}); -app.post("/test-cleanup/users", async (c) => { - const db = c.env.DB; - if (c.env.ENVIRONMENT === "production") { - return c.json({ error: "Cleanup endpoint not available in production" }, 403); - } - try { - const result = await db.prepare(` - DELETE FROM users - WHERE email != 'admin@sonicjs.com' - AND ( - email LIKE '%test%' - OR email LIKE '%example.com%' - OR first_name = 'Test' - ) - `).run(); - return c.json({ - success: true, - deletedCount: result.meta?.changes || 0, - message: "Test users cleaned up successfully" - }); - } catch (error) { - console.error("User cleanup error:", error); - return c.json({ - success: false, - error: error instanceof Error ? error.message : "Unknown error" - }, 500); - } -}); -app.post("/test-cleanup/collections", async (c) => { - const db = c.env.DB; - if (c.env.ENVIRONMENT === "production") { - return c.json({ error: "Cleanup endpoint not available in production" }, 403); - } - try { - let deletedCount = 0; - const collections = await db.prepare(` - SELECT id FROM collections - WHERE name LIKE 'test_%' - OR name IN ('blog_posts', 'test_collection', 'products', 'articles') - `).all(); - if (collections.results && collections.results.length > 0) { - const collectionIds = collections.results.map((c2) => c2.id); - for (const id of collectionIds) { - await db.prepare("DELETE FROM collection_fields WHERE collection_id = ?").bind(id).run(); - } - for (const id of collectionIds) { - await db.prepare("DELETE FROM content WHERE collection_id = ?").bind(id).run(); - } - const result = await db.prepare(` - DELETE FROM collections - WHERE id IN (${collectionIds.map(() => "?").join(",")}) - `).bind(...collectionIds).run(); - deletedCount = result.meta?.changes || 0; - } - return c.json({ - success: true, - deletedCount, - message: "Test collections cleaned up successfully" - }); - } catch (error) { - console.error("Collection cleanup error:", error); - return c.json({ - success: false, - error: error instanceof Error ? error.message : "Unknown error" - }, 500); - } -}); -app.post("/test-cleanup/content", async (c) => { - const db = c.env.DB; - if (c.env.ENVIRONMENT === "production") { - return c.json({ error: "Cleanup endpoint not available in production" }, 403); - } - try { - const result = await db.prepare(` - DELETE FROM content - WHERE title LIKE 'Test %' - OR title LIKE '%E2E%' - OR title LIKE '%Playwright%' - OR title LIKE '%Sample%' - `).run(); - await db.prepare(` - DELETE FROM content_data - WHERE content_id NOT IN (SELECT id FROM content) - `).run(); - return c.json({ - success: true, - deletedCount: result.meta?.changes || 0, - message: "Test content cleaned up successfully" - }); - } catch (error) { - console.error("Content cleanup error:", error); - return c.json({ - success: false, - error: error instanceof Error ? error.message : "Unknown error" - }, 500); - } -}); -var test_cleanup_default = app; - -// src/templates/pages/admin-content-form.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); - -// src/templates/components/drag-sortable.template.ts -function getDragSortableScript() { - return ` - - `; -} - -// src/templates/components/dynamic-field.template.ts -function getReadFieldValueScript() { - return ` - - `; -} -function renderDynamicField(field, options = {}) { - const { value = "", errors = [], disabled = false, className = "", pluginStatuses = {}, collectionId = "", contentId = "" } = options; - const opts = field.field_options || {}; - const required = field.is_required ? "required" : ""; - const baseClasses = `w-full rounded-lg px-3 py-2 text-sm text-zinc-950 dark:text-white bg-white dark:bg-zinc-800 shadow-sm ring-1 ring-inset ring-zinc-950/10 dark:ring-white/10 placeholder:text-zinc-400 dark:placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-zinc-950 dark:focus:ring-white transition-shadow ${className}`; - const errorClasses = errors.length > 0 ? "ring-pink-600 dark:ring-pink-500 focus:ring-pink-600 dark:focus:ring-pink-500" : ""; - const fieldId = `field-${field.field_name}`; - const fieldName = field.field_name; - let fallbackToTextarea = false; - let fallbackWarning = ""; - if (field.field_type === "quill" && !pluginStatuses.quillEnabled) { - fallbackToTextarea = true; - fallbackWarning = "\u26A0\uFE0F Quill Editor plugin is inactive. Using textarea fallback."; - } else if (field.field_type === "mdxeditor" && !pluginStatuses.mdxeditorEnabled) { - fallbackToTextarea = true; - fallbackWarning = "\u26A0\uFE0F MDXEditor plugin is inactive. Using textarea fallback."; - } else if (field.field_type === "tinymce" && !pluginStatuses.tinymceEnabled) { - fallbackToTextarea = true; - fallbackWarning = "\u26A0\uFE0F TinyMCE plugin is inactive. Using textarea fallback."; - } - if (fallbackToTextarea) { - return ` -
- ${fallbackWarning ? `
${fallbackWarning}
` : ""} - -
- `; - } - let fieldHTML = ""; - switch (field.field_type) { - case "text": - let patternHelp = ""; - let autoSlugScript = ""; - if (opts.pattern) { - if (opts.pattern === "^[a-z0-9-]+$" || opts.pattern === "^[a-zA-Z0-9_-]+$") { - patternHelp = '

Use letters, numbers, underscores, and hyphens only

'; - if (fieldName === "slug") { - patternHelp += ``; - autoSlugScript = ` - - `; - } - } else { - patternHelp = '

Must match required format

'; - } - } - fieldHTML = ` - - ${patternHelp} - ${autoSlugScript} - ${opts.pattern ? ` - - ` : ""} - `; - break; - case "textarea": - fieldHTML = ` - - `; - break; - case "richtext": - fieldHTML = ` -
- -
- `; - break; - case "quill": - fieldHTML = ` -
- -
${value}
- - - -
- `; - break; - case "mdxeditor": - fieldHTML = ` -
- -
- `; - break; - case "number": - fieldHTML = ` - - `; - break; - case "boolean": - const checked = value === true || value === "true" || value === "1" ? "checked" : ""; - fieldHTML = ` -
- - -
- - `; - break; - case "date": - fieldHTML = ` - - `; - break; - case "datetime": - fieldHTML = ` - - `; - break; - case "slug": - const slugPattern = opts.pattern || "^[a-z0-9-]+$"; - const collectionIdValue = collectionId || opts.collectionId || ""; - const contentIdValue = contentId || opts.contentId || ""; - const isEditMode = !!value; - fieldHTML = ` -
- -
- -

Use lowercase letters, numbers, and hyphens only

-
- - - `; - break; - case "select": - const selectOptions = opts.options || []; - const multiple = opts.multiple ? "multiple" : ""; - const selectedValues = Array.isArray(value) ? value : [value]; - fieldHTML = ` - - ${opts.allowCustom ? ` -
- -
- ` : ""} - `; - break; - case "reference": - let referenceCollections = []; - if (Array.isArray(opts.collection)) { - referenceCollections = opts.collection.filter(Boolean); - } else if (typeof opts.collection === "string" && opts.collection) { - referenceCollections = [opts.collection]; - } - const referenceCollectionsAttr = referenceCollections.join(","); - const hasReferenceCollection = referenceCollections.length > 0; - const hasReferenceValue = Boolean(value); - fieldHTML = ` -
- -
-
- ${hasReferenceCollection ? hasReferenceValue ? "Loading selection..." : "No reference selected." : "Reference collection not configured."} -
-
- - -
-
-
- `; - break; - case "media": - const isMultiple = opts.multiple === true; - const mediaValues = isMultiple && value ? Array.isArray(value) ? value : String(value).split(",").filter(Boolean) : []; - const singleValue = !isMultiple ? value : ""; - const isVideoUrl = (url) => { - const videoExtensions = [".mp4", ".webm", ".ogg", ".mov", ".avi"]; - return videoExtensions.some((ext) => url.toLowerCase().endsWith(ext)); - }; - const renderMediaPreview = (url, alt, classes) => { - if (isVideoUrl(url)) { - return ``; - } - return `${alt}`; - }; - fieldHTML = ` -
- - - ${isMultiple ? ` -
- ${mediaValues.map((url, idx) => ` -
- ${renderMediaPreview(url, `Media ${idx + 1}`, "w-full h-24 object-cover rounded-lg border border-white/20")} - -
- `).join("")} -
- ` : ` -
- ${singleValue ? renderMediaPreview(singleValue, "Selected media", "w-32 h-32 object-cover rounded-lg border border-white/20") : ""} -
- `} - -
- - ${(isMultiple ? mediaValues.length > 0 : singleValue) ? ` - - ` : ""} -
-
- `; - break; - case "object": - return renderStructuredObjectField(field, options); - case "array": - const itemsConfig = opts.items && typeof opts.items === "object" ? opts.items : {}; - if (itemsConfig.blocks && typeof itemsConfig.blocks === "object") { - return renderBlocksField(field, options, baseClasses, errorClasses); - } - return renderStructuredArrayField(field, options); - default: - fieldHTML = ` - - `; - } - const showLabel = field.field_type !== "boolean"; - return ` -
- ${showLabel ? ` - - ` : ""} - ${fieldHTML} - ${errors.length > 0 ? ` -
- ${errors.map((error) => `
${escapeHtml2(error)}
`).join("")} -
- ` : ""} - ${opts.helpText ? ` -
- ${escapeHtml2(opts.helpText)} -
- ` : ""} -
- `; -} -function renderFieldGroup(title, fields, collapsible = false) { - const groupId = title.toLowerCase().replace(/\s+/g, "-"); - return ` -
-
-

- ${escapeHtml2(title)} - ${collapsible ? ` - - - - ` : ""} -

-
-
- ${fields.join("")} -
-
- `; -} -function renderBlocksField(field, options, baseClasses, errorClasses) { - const { value = [], pluginStatuses = {} } = options; - const opts = field.field_options || {}; - const itemsConfig = opts.items && typeof opts.items === "object" ? opts.items : {}; - const blocks = normalizeBlockDefinitions(itemsConfig.blocks); - const discriminator = typeof itemsConfig.discriminator === "string" && itemsConfig.discriminator ? itemsConfig.discriminator : "blockType"; - const blockValues = normalizeBlocksValue(value, discriminator); - const fieldId = `field-${field.field_name}`; - const fieldName = field.field_name; - const emptyState = blockValues.length === 0 ? ` -
- No blocks yet. Add your first block to get started. -
- ` : ""; - const blockOptions = blocks.map((block) => ``).join(""); - const blockItems = blockValues.map( - (blockValue, index) => renderBlockItem(field, blockValue, blocks, discriminator, index, pluginStatuses) - ).join(""); - const templates = blocks.map((block) => renderBlockTemplate(field, block, discriminator, pluginStatuses)).join(""); - return ` -
- - -
-
- -
- -
- -
- ${blockItems || emptyState} -
- - ${templates} -
- ${getDragSortableScript()} - ${getBlocksFieldScript()} - `; -} -function renderStructuredObjectField(field, options, baseClasses, errorClasses) { - const { value = {}, pluginStatuses = {} } = options; - const opts = field.field_options || {}; - const properties = opts.properties && typeof opts.properties === "object" ? opts.properties : {}; - const fieldId = `field-${field.field_name}`; - const fieldName = field.field_name; - const objectValue = normalizeStructuredObjectValue(value); - const subfields = Object.entries(properties).map( - ([propertyName, propertyConfig]) => renderStructuredSubfield( - field, - propertyName, - propertyConfig, - objectValue, - pluginStatuses, - field.field_name - ) - ).join(""); - return ` -
- -
- ${subfields} -
-
- ${getStructuredFieldScript()} - `; -} -function renderStructuredArrayField(field, options, baseClasses, errorClasses) { - const { value = [], pluginStatuses = {} } = options; - const opts = field.field_options || {}; - const itemsConfig = opts.items && typeof opts.items === "object" ? opts.items : {}; - const fieldId = `field-${field.field_name}`; - const fieldName = field.field_name; - const arrayValue = normalizeStructuredArrayValue(value); - const items = arrayValue.map( - (itemValue, index) => renderStructuredArrayItem(field, itemsConfig, String(index), itemValue, pluginStatuses) - ).join(""); - const emptyState = arrayValue.length === 0 ? ` -
- No items yet. Add the first item to get started. -
- ` : ""; - return ` -
- - -
-
- ${escapeHtml2(opts.itemLabel || "Items")} -
- -
- -
- ${items || emptyState} -
- - -
- ${getDragSortableScript()} - ${getStructuredFieldScript()} - `; -} -function renderStructuredArrayItem(field, itemConfig, index, itemValue, pluginStatuses) { - const itemFields = renderStructuredItemFields(field, itemConfig, index, itemValue, pluginStatuses); - return ` -
-
-
-
- - - -
-
- Item -
-
-
- - - -
-
-
- ${itemFields} -
-
- `; -} -function renderStructuredItemFields(field, itemConfig, index, itemValue, pluginStatuses) { - const itemType = itemConfig?.type || "string"; - if (itemType === "object" && itemConfig?.properties && typeof itemConfig.properties === "object") { - const fieldPrefix = `array-${field.field_name}-${index}`; - return Object.entries(itemConfig.properties).map( - ([propertyName, propertyConfig]) => renderStructuredSubfield( - field, - propertyName, - propertyConfig, - itemValue || {}, - pluginStatuses, - fieldPrefix - ) - ).join(""); - } - const normalizedField = normalizeBlockField(itemConfig, "Item"); - const fieldValue = itemValue ?? normalizedField.defaultValue ?? ""; - const fieldDefinition = { - id: `array-${field.field_name}-${index}-value`, - field_name: `array-${field.field_name}-${index}-value`, - field_type: normalizedField.type, - field_label: normalizedField.label, - field_options: normalizedField.options, - is_required: normalizedField.required}; - return ` -
- ${renderDynamicField(fieldDefinition, { value: fieldValue, pluginStatuses })} -
- `; -} -function renderStructuredSubfield(field, propertyName, propertyConfig, objectValue, pluginStatuses, fieldPrefix) { - const normalizedField = normalizeBlockField(propertyConfig, propertyName); - const fieldValue = objectValue?.[propertyName] ?? normalizedField.defaultValue ?? ""; - const fieldDefinition = { - field_name: `${fieldPrefix}__${propertyName}`, - field_type: normalizedField.type, - field_label: normalizedField.label, - field_options: normalizedField.options, - is_required: normalizedField.required}; - return ` -
- ${renderDynamicField(fieldDefinition, { value: fieldValue, pluginStatuses })} -
- `; -} -function normalizeStructuredObjectValue(value) { - if (!value) return {}; - if (typeof value === "string") { - try { - const parsed = JSON.parse(value); - return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; - } catch { - return {}; - } - } - if (typeof value === "object" && !Array.isArray(value)) return value; - return {}; -} -function normalizeStructuredArrayValue(value) { - if (!value) return []; - if (Array.isArray(value)) return value; - if (typeof value === "string") { - try { - const parsed = JSON.parse(value); - return Array.isArray(parsed) ? parsed : []; - } catch { - return []; - } - } - return []; -} -function normalizeBlockDefinitions(rawBlocks) { - if (!rawBlocks || typeof rawBlocks !== "object") return []; - return Object.entries(rawBlocks).filter(([name, block]) => typeof name === "string" && block && typeof block === "object").map(([name, block]) => ({ - name, - label: block.label || name, - description: block.description, - properties: block.properties && typeof block.properties === "object" ? block.properties : {} - })); -} -function normalizeBlocksValue(value, discriminator) { - const normalizeItem = (item) => { - if (!item || typeof item !== "object") return null; - if (item[discriminator]) return item; - if (item.blockType && item.data && typeof item.data === "object") { - return { [discriminator]: item.blockType, ...item.data }; - } - return item; - }; - const fromArray = (items) => items.map(normalizeItem).filter((item) => item && typeof item === "object"); - if (Array.isArray(value)) return fromArray(value); - if (typeof value === "string" && value.trim()) { - try { - const parsed = JSON.parse(value); - return Array.isArray(parsed) ? fromArray(parsed) : []; - } catch { - return []; - } - } - return []; -} -function renderBlockTemplate(field, block, discriminator, pluginStatuses) { - return ` - - `; -} -function renderBlockItem(field, blockValue, blocks, discriminator, index, pluginStatuses) { - const blockType = blockValue?.[discriminator] || blockValue?.blockType; - const blockDefinition = blocks.find((block) => block.name === blockType); - if (!blockDefinition) { - return ` -
- Unknown block type: ${escapeHtml2(String(blockType || "unknown"))}. This block will be preserved as-is. -
- `; - } - const data = blockValue && typeof blockValue === "object" ? Object.fromEntries(Object.entries(blockValue).filter(([key]) => key !== discriminator)) : {}; - return renderBlockCard(field, blockDefinition, discriminator, String(index), data, pluginStatuses); -} -function renderBlockCard(field, block, discriminator, index, data, pluginStatuses) { - const blockFields = Object.entries(block.properties).map(([fieldName, fieldConfig]) => { - if (fieldConfig?.type === "array" && fieldConfig?.items?.blocks) { - return ` -
- Nested blocks are not supported yet for "${escapeHtml2(fieldName)}". -
- `; - } - const normalizedField = normalizeBlockField(fieldConfig, fieldName); - const fieldValue = data?.[fieldName] ?? normalizedField.defaultValue ?? ""; - const fieldDefinition = { - id: `block-${field.field_name}-${index}-${fieldName}`, - field_name: `block-${field.field_name}-${index}-${fieldName}`, - field_type: normalizedField.type, - field_label: normalizedField.label, - field_options: normalizedField.options, - is_required: normalizedField.required}; - return ` -
- ${renderDynamicField(fieldDefinition, { value: fieldValue, pluginStatuses })} -
- `; - }).join(""); - return ` -
-
-
-
- - - -
-
-
- ${escapeHtml2(block.label)} - -
- ${block.description ? `

${escapeHtml2(block.description)}

` : ""} -
-
-
- - - -
-
-
- ${blockFields} -
-
- `; -} -function normalizeBlockField(fieldConfig, fieldName) { - const type = fieldConfig?.type || "text"; - const label = fieldConfig?.title || fieldName; - const required = fieldConfig?.required === true; - const options = { ...fieldConfig }; - if (type === "select" && Array.isArray(fieldConfig?.enum)) { - options.options = fieldConfig.enum.map((value, index) => ({ - value, - label: fieldConfig.enumLabels?.[index] || value - })); - } - return { - type, - label, - required, - defaultValue: fieldConfig?.default, - options - }; -} -function getStructuredFieldScript() { - return ` - ${getReadFieldValueScript()} - - `; -} -function getBlocksFieldScript() { - return ` - ${getReadFieldValueScript()} - - `; -} -function escapeHtml2(text) { - if (typeof text !== "string") return String(text || ""); - return text.replace(/[&<>"']/g, (char) => ({ - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'" - })[char] || char); -} - -// src/plugins/available/tinymce-plugin/index.ts -var builder = chunk6FHNRRJ3_cjs.PluginBuilder.create({ - name: "tinymce-plugin", - version: "1.0.0", - description: "Powerful WYSIWYG rich text editor for content creation" -}); -builder.metadata({ - author: { - name: "SonicJS Team", - email: "team@sonicjs.com" - }, - license: "MIT", - compatibility: "^2.0.0" -}); -builder.lifecycle({ - activate: async () => { - console.info("\u2705 TinyMCE plugin activated"); - }, - deactivate: async () => { - console.info("\u274C TinyMCE plugin deactivated"); - } -}); -builder.build(); -function getTinyMCEScript(apiKey = "no-api-key") { - return ``; -} -function getTinyMCEInitScript(config) { - const skin = config?.skin || "oxide-dark"; - const contentCss = skin.includes("dark") ? "dark" : "default"; - const defaultHeight = config?.defaultHeight || 300; - return ` - // Initialize TinyMCE for all richtext fields - function initializeTinyMCE() { - if (typeof tinymce !== 'undefined') { - // Find all textareas that need TinyMCE - document.querySelectorAll('.richtext-container textarea').forEach((textarea) => { - // Skip if already initialized - if (tinymce.get(textarea.id)) { - return; - } - - // Get configuration from data attributes - const container = textarea.closest('.richtext-container'); - const height = container?.dataset.height || ${defaultHeight}; - const toolbar = container?.dataset.toolbar || 'full'; - - tinymce.init({ - selector: '#' + textarea.id, - skin: '${skin}', - content_css: '${contentCss}', - height: parseInt(height), - menubar: false, - plugins: [ - 'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview', - 'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen', - 'insertdatetime', 'media', 'table', 'help', 'wordcount' - ], - toolbar: toolbar === 'simple' - ? 'bold italic underline | bullist numlist | link' - : toolbar === 'minimal' - ? 'bold italic | link' - : 'undo redo | blocks | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help', - content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; font-size: 14px }' - }); - }); - } - } - - // Initialize on DOMContentLoaded - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', initializeTinyMCE); - } else { - // DOM already loaded, initialize immediately - initializeTinyMCE(); - } - - // Also reinitialize after HTMX swaps (for dynamic content) - document.addEventListener('htmx:afterSwap', function(event) { - // Give the DOM a moment to settle - setTimeout(initializeTinyMCE, 100); - }); - `; -} - -// src/plugins/core-plugins/quill-editor/index.ts -var QUILL_TOOLBARS = { - full: [ - [{ "header": [1, 2, 3, 4, 5, 6, false] }], - ["bold", "italic", "underline", "strike"], - [{ "color": [] }, { "background": [] }], - [{ "align": [] }], - [{ "list": "ordered" }, { "list": "bullet" }], - [{ "indent": "-1" }, { "indent": "+1" }], - ["blockquote", "code-block"], - ["link", "image", "video"], - ["clean"] - ], - simple: [ - ["bold", "italic", "underline"], - [{ "list": "ordered" }, { "list": "bullet" }], - ["link"] - ], - minimal: [ - ["bold", "italic"], - ["link"] - ] -}; -function getQuillInitScript() { - return ` - - `; -} -function getQuillCDN(version = "2.0.2") { - return ` - - - - - - - - - - `; -} -function createQuillEditorPlugin() { - const builder3 = chunk6FHNRRJ3_cjs.PluginBuilder.create({ - name: "quill-editor", - version: "1.0.0", - description: "Quill rich text editor integration for SonicJS" - }); - builder3.metadata({ - author: { - name: "SonicJS Team", - email: "team@sonicjs.com" - }, - license: "MIT", - compatibility: "^2.0.0" - }); - builder3.lifecycle({ - activate: async () => { - console.info("\u2705 Quill Editor plugin activated"); - }, - deactivate: async () => { - console.info("\u274C Quill Editor plugin deactivated"); - } - }); - return builder3.build(); -} -createQuillEditorPlugin(); - -// src/plugins/available/easy-mdx/index.ts -var builder2 = chunk6FHNRRJ3_cjs.PluginBuilder.create({ - name: "easy-mdx", - version: "1.0.0", - description: "Lightweight markdown editor with live preview" -}); -builder2.metadata({ - author: { - name: "SonicJS Team", - email: "team@sonicjs.com" - }, - license: "MIT", - compatibility: "^2.0.0" -}); -builder2.lifecycle({ - activate: async () => { - console.info("\u2705 EasyMDE editor plugin activated"); - }, - deactivate: async () => { - console.info("\u274C EasyMDE editor plugin deactivated"); - } -}); -builder2.build(); -function getMDXEditorScripts() { - return ` - - - - - `; -} -function getMDXEditorInitScript(config) { - const defaultHeight = config?.defaultHeight || 400; - const toolbar = config?.toolbar || "full"; - const placeholder = config?.placeholder || "Start writing your content..."; - return ` - // Initialize EasyMDE (Markdown Editor) for all richtext fields - function initializeMDXEditor() { - if (typeof EasyMDE === 'undefined') { - console.warn('EasyMDE not loaded yet, retrying...'); - setTimeout(initializeMDXEditor, 100); - return; - } - - // Find all textareas that need EasyMDE - document.querySelectorAll('.richtext-container textarea').forEach((textarea) => { - // Skip if already initialized - if (textarea.dataset.mdxeditorInitialized === 'true') { - return; - } - - // Mark as initialized - textarea.dataset.mdxeditorInitialized = 'true'; - - // Get configuration from data attributes - const container = textarea.closest('.richtext-container'); - const height = container?.dataset.height || ${defaultHeight}; - const editorToolbar = container?.dataset.toolbar || '${toolbar}'; - - // Initialize EasyMDE - try { - const toolbarButtons = editorToolbar === 'minimal' - ? ['bold', 'italic', 'heading', '|', 'quote', 'unordered-list', 'ordered-list', '|', 'link', 'preview'] - : ['bold', 'italic', 'heading', '|', 'quote', 'unordered-list', 'ordered-list', '|', 'link', 'image', 'table', '|', 'preview', 'side-by-side', 'fullscreen', '|', 'guide']; - - const easyMDE = new EasyMDE({ - element: textarea, - placeholder: '${placeholder}', - spellChecker: false, - minHeight: height + 'px', - toolbar: toolbarButtons, - status: ['lines', 'words', 'cursor'], - renderingConfig: { - singleLineBreaks: false, - codeSyntaxHighlighting: true - } - }); - - // Store reference to editor instance - textarea.easyMDEInstance = easyMDE; - - // Sync changes back to textarea - easyMDE.codemirror.on("change", () => { - textarea.value = easyMDE.value(); - textarea.dispatchEvent(new Event("input", { bubbles: true })); - textarea.dispatchEvent(new Event("change", { bubbles: true })); - }); - - console.log('EasyMDE initialized for field:', textarea.id || textarea.name); - } catch (error) { - console.error('Error initializing EasyMDE:', error); - // Show textarea as fallback - textarea.style.display = 'block'; - } - }); - } - - // Initialize on DOMContentLoaded - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', initializeMDXEditor); - } else { - // DOM already loaded, initialize immediately - initializeMDXEditor(); - } - - // Also reinitialize after HTMX swaps (for dynamic content) - document.addEventListener('htmx:afterSwap', function(event) { - // Give the DOM a moment to settle - setTimeout(initializeMDXEditor, 100); - }); - `; -} - -// src/templates/pages/admin-content-form.template.ts -function renderContentFormPage(data) { - const isEdit = data.isEdit || !!data.id; - const title = isEdit ? `Edit: ${data.title || "Content"}` : `New ${data.collection.display_name}`; - const backUrl = data.referrerParams ? `/admin/content?${data.referrerParams}` : `/admin/content?collection=${data.collection.id}`; - const coreFields = data.fields.filter((f) => ["title", "slug", "content"].includes(f.field_name)); - const contentFields = data.fields.filter((f) => !["title", "slug", "content"].includes(f.field_name) && !f.field_name.startsWith("meta_")); - const metaFields = data.fields.filter((f) => f.field_name.startsWith("meta_")); - const getFieldValue = (fieldName) => { - if (fieldName === "title") return data.title || data.data?.[fieldName] || ""; - if (fieldName === "slug") return data.slug || data.data?.[fieldName] || ""; - return data.data?.[fieldName] || ""; - }; - const pluginStatuses = { - quillEnabled: data.quillEnabled || false, - mdxeditorEnabled: data.mdxeditorEnabled || false, - tinymceEnabled: data.tinymceEnabled || false - }; - const coreFieldsHTML = coreFields.sort((a, b) => a.field_order - b.field_order).map((field) => renderDynamicField(field, { - value: getFieldValue(field.field_name), - errors: data.validationErrors?.[field.field_name] || [], - pluginStatuses, - collectionId: data.collection.id, - contentId: data.id - // Pass content ID when editing - })); - const contentFieldsHTML = contentFields.sort((a, b) => a.field_order - b.field_order).map((field) => renderDynamicField(field, { - value: getFieldValue(field.field_name), - errors: data.validationErrors?.[field.field_name] || [], - pluginStatuses, - collectionId: data.collection.id, - contentId: data.id - })); - const metaFieldsHTML = metaFields.sort((a, b) => a.field_order - b.field_order).map((field) => renderDynamicField(field, { - value: getFieldValue(field.field_name), - errors: data.validationErrors?.[field.field_name] || [], - pluginStatuses, - collectionId: data.collection.id, - contentId: data.id - })); - const pageContent = ` -
- -
-
-

${isEdit ? "Edit Content" : "New Content"}

-

- ${data.collection.description || `Manage ${data.collection.display_name.toLowerCase()} content`} -

-
- -
- - -
- -
-
-
- - - -
-
-

${data.collection.display_name}

-

${isEdit ? "Update your content" : "Create new content"}

-
-
-
- - -
-
- ${data.error ? chunkSHCYIZAN_cjs.renderAlert({ type: "error", message: data.error, dismissible: true }) : ""} - ${data.success ? chunkSHCYIZAN_cjs.renderAlert({ type: "success", message: data.success, dismissible: true }) : ""} -
- -
- -
-
- - ${isEdit ? `` : ""} - ${data.referrerParams ? `` : ""} - - - ${renderFieldGroup("Basic Information", coreFieldsHTML)} - - - ${contentFields.length > 0 ? renderFieldGroup("Content Details", contentFieldsHTML) : ""} - - - ${metaFields.length > 0 ? renderFieldGroup("SEO & Metadata", metaFieldsHTML, true) : ""} - -
-
-
- - -
- -
-

Publishing

- - ${data.workflowEnabled ? ` - -
- -
- - -
-
- - -
- - -

Leave empty to publish immediately

-
- - -
- - -

Automatically unpublish at this time

-
- ` : ` - -
- -
- - -
-

Enable Workflow plugin for advanced status management

-
- `} -
- - - ${isEdit ? ` -
-

Content Info

- -
-
-
Created
-
${data.data?.created_at ? new Date(data.data.created_at).toLocaleDateString() : "Unknown"}
-
-
-
Last Modified
-
${data.data?.updated_at ? new Date(data.data.updated_at).toLocaleDateString() : "Unknown"}
-
-
-
Author
-
${data.data?.author || "Unknown"}
-
- ${data.data?.published_at ? ` -
-
Published
-
${new Date(data.data.published_at).toLocaleDateString()}
-
- ` : ""} -
- -
- -
-
- ` : ""} - - -
-

Quick Actions

- -
- - - - - ${isEdit ? ` - - ` : ""} -
-
-
- - -
- - - - - Cancel - - -
- - - ${data.user?.role !== "viewer" ? ` - - ` : ""} -
-
-
-
-
- - - ${chunkSHCYIZAN_cjs.renderConfirmationDialog({ - id: "duplicate-content-confirm", - title: "Duplicate Content", - message: "Create a copy of this content?", - confirmText: "Duplicate", - cancelText: "Cancel", - iconColor: "blue", - confirmClass: "bg-blue-500 hover:bg-blue-400", - onConfirm: "performDuplicateContent()" - })} - - ${chunkSHCYIZAN_cjs.renderConfirmationDialog({ - id: "delete-content-confirm", - title: "Delete Content", - message: "Are you sure you want to delete this content? This action cannot be undone.", - confirmText: "Delete", - cancelText: "Cancel", - iconColor: "red", - confirmClass: "bg-red-500 hover:bg-red-400", - onConfirm: `performDeleteContent('${data.id}')` - })} - - ${chunkSHCYIZAN_cjs.getConfirmationDialogScript()} - - ${data.tinymceEnabled ? getTinyMCEScript(data.tinymceSettings?.apiKey) : ""} - - ${data.quillEnabled ? getQuillCDN(data.quillSettings?.version) : ""} - - ${data.quillEnabled ? getQuillInitScript() : ""} - - ${data.mdxeditorEnabled ? getMDXEditorScripts() : ""} - - - - `; - const layoutData = { - title, - pageTitle: "Content Management", - currentPath: "/admin/content", - user: data.user, - content: pageContent, - version: data.version - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/pages/admin-content-list.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderContentListPage(data) { - const urlParams = new URLSearchParams(); - if (data.modelName && data.modelName !== "all") urlParams.set("model", data.modelName); - if (data.status && data.status !== "all") urlParams.set("status", data.status); - if (data.search) urlParams.set("search", data.search); - if (data.page && data.page !== 1) urlParams.set("page", data.page.toString()); - const currentParams = urlParams.toString(); - data.modelName !== "all" || data.status !== "all" || !!data.search; - const filterBarData = { - filters: [ - { - name: "model", - label: "Model", - options: [ - { value: "all", label: "All Models", selected: data.modelName === "all" }, - ...data.models.map((model) => ({ - value: model.name, - label: model.displayName, - selected: data.modelName === model.name - })) - ] - }, - { - name: "status", - label: "Status", - options: [ - { value: "all", label: "All Status", selected: data.status === "all" }, - { value: "draft", label: "Draft", selected: data.status === "draft" }, - { value: "review", label: "Under Review", selected: data.status === "review" }, - { value: "scheduled", label: "Scheduled", selected: data.status === "scheduled" }, - { value: "published", label: "Published", selected: data.status === "published" }, - { value: "archived", label: "Archived", selected: data.status === "archived" }, - { value: "deleted", label: "Deleted", selected: data.status === "deleted" } - ] - } - ], - actions: [ - { - label: "Advanced Search", - className: "btn-primary", - onclick: "openAdvancedSearch()" - }, - { - label: "Refresh", - className: "btn-secondary", - onclick: "location.reload()" - } - ], - bulkActions: [ - { label: "Publish", value: "publish", icon: "check-circle" }, - { label: "Unpublish", value: "unpublish", icon: "x-circle" }, - { label: "Delete", value: "delete", icon: "trash", className: "text-pink-600" } - ] - }; - const tableColumns = [ - { - key: "title", - label: "Title", - sortable: true, - sortType: "string", - render: (value, row) => ` -
-
- -
${row.slug}
-
-
- ` - }, - { - key: "modelName", - label: "Model", - sortable: true, - sortType: "string", - className: "text-sm text-zinc-500 dark:text-zinc-400" - }, - { - key: "statusBadge", - label: "Status", - sortable: true, - sortType: "string", - render: (value) => value - }, - { - key: "authorName", - label: "Author", - sortable: true, - sortType: "string", - className: "text-sm text-zinc-500 dark:text-zinc-400" - }, - { - key: "formattedDate", - label: "Updated", - sortable: true, - sortType: "date", - className: "text-sm text-zinc-500 dark:text-zinc-400" - }, - { - key: "actions", - label: "Actions", - sortable: false, - className: "text-sm font-medium", - render: (value, row) => ` -
- - - -
- ` - } - ]; - const tableData = { - tableId: "content-table", - columns: tableColumns, - rows: data.contentItems, - selectable: true, - rowClickable: true, - rowClickUrl: (row) => `/admin/content/${row.id}/edit${currentParams ? `?ref=${encodeURIComponent(currentParams)}` : ""}`, - emptyMessage: "No content found. Create your first content item to get started." - }; - const totalPages = Math.ceil(data.totalItems / data.itemsPerPage); - const startItem = (data.page - 1) * data.itemsPerPage + 1; - const endItem = Math.min(data.page * data.itemsPerPage, data.totalItems); - const paginationData = { - currentPage: data.page, - totalPages, - totalItems: data.totalItems, - itemsPerPage: data.itemsPerPage, - startItem, - endItem, - baseUrl: "/admin/content", - queryParams: { - model: data.modelName, - status: data.status, - ...data.search ? { search: data.search } : {} - }, - showPageSizeSelector: true, - pageSizeOptions: [10, 20, 50, 100] - }; - const pageContent = ` -
- -
-
-

Content Management

-

Manage and organize your content items

-
- -
- -
- -
- -
-
-
-
- -
- -
- - -
-
- - -
- -
- - -
-
- - -
- -
-
- -
- - - -
- -
- -
- -
-
-
- ${data.totalItems} ${data.totalItems === 1 ? "item" : "items"} - ${filterBarData.actions?.map((action) => ` - - `).join("") || ""} - ${filterBarData.bulkActions && filterBarData.bulkActions.length > 0 ? ` -
- - - -
- ` : ""} -
-
-
-
-
- - -
- ${chunkSHCYIZAN_cjs.renderTable(tableData)} - ${chunkSHCYIZAN_cjs.renderPagination(paginationData)} -
- -
- - -
-
- - - - - ${chunkSHCYIZAN_cjs.renderConfirmationDialog({ - id: "bulk-action-confirm", - title: "Confirm Bulk Action", - message: "Are you sure you want to perform this action? This operation will affect multiple items.", - confirmText: "Confirm", - cancelText: "Cancel", - confirmClass: "bg-blue-500 hover:bg-blue-400", - iconColor: "blue", - onConfirm: "executeBulkAction()" - })} - - - ${chunkSHCYIZAN_cjs.getConfirmationDialogScript()} - - - - - - `; - const layoutData = { - title: "Content Management", - pageTitle: "Content Management", - currentPath: "/admin/content", - user: data.user, - version: data.version, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/components/version-history.template.ts -function renderVersionHistory(data) { - return ` -
-
- -
-
-
-

Version History

- -
-
- - -
-
- ${data.versions.map((version, index) => ` -
-
-
- - Version ${version.version}${version.is_current ? " (Current)" : ""} - - - ${new Date(version.created_at).toLocaleString()} - -
-
- ${!version.is_current ? ` - - ` : ""} - -
-
- - -
-
-
- Title: - ${escapeHtml3(version.data?.title || "Untitled")} -
-
- Author: - ${escapeHtml3(version.author_name || "Unknown")} -
- ${version.data?.excerpt ? ` -
- Excerpt: -

${escapeHtml3(version.data.excerpt.substring(0, 200))}${version.data.excerpt.length > 200 ? "..." : ""}

-
- ` : ""} -
-
- - - ${!version.is_current && index < data.versions.length - 1 ? ` -
- - -
- ` : ""} -
- `).join("")} -
-
- - -
-
- - ${data.versions.length} version${data.versions.length !== 1 ? "s" : ""} total - - -
-
-
-
- - - `; -} -function escapeHtml3(text) { - if (typeof text !== "string") return String(text || ""); - return text.replace(/[&<>"']/g, (char) => ({ - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'" - })[char] || char); -} - -// src/middleware/plugin-middleware.ts -async function isPluginActive2(db, pluginId) { - try { - const result = await db.prepare("SELECT status FROM plugins WHERE id = ?").bind(pluginId).first(); - return result?.status === "active"; - } catch (error) { - console.error(`[isPluginActive] Error checking plugin status for ${pluginId}:`, error); - return false; - } -} - -// src/routes/admin-content.ts -var adminContentRoutes = new hono.Hono(); -function parseFieldValue(field, formData, options = {}) { - const { skipValidation = false } = options; - const value = formData.get(field.field_name); - const errors = []; - const blocksConfig = chunk5HMR2SJW_cjs.getBlocksFieldConfig(field.field_options); - if (blocksConfig) { - const parsed = chunk5HMR2SJW_cjs.parseBlocksValue(value, blocksConfig); - if (!skipValidation && field.is_required && parsed.value.length === 0) { - parsed.errors.push(`${field.field_label} is required`); - } - return { value: parsed.value, errors: parsed.errors }; - } - if (!skipValidation && field.is_required && (!value || value.toString().trim() === "")) { - return { value: null, errors: [`${field.field_label} is required`] }; - } - switch (field.field_type) { - case "number": - if (value && isNaN(Number(value))) { - if (!skipValidation) { - errors.push(`${field.field_label} must be a valid number`); - } - return { value: null, errors }; - } - return { value: value ? Number(value) : null, errors: [] }; - case "boolean": - const submitted = formData.get(`${field.field_name}_submitted`); - return { value: submitted ? value === "true" : false, errors: [] }; - case "select": - if (field.field_options?.multiple) { - return { value: formData.getAll(`${field.field_name}[]`), errors: [] }; - } - return { value, errors: [] }; - case "array": { - if (!value || value.toString().trim() === "") { - if (!skipValidation && field.is_required) { - errors.push(`${field.field_label} is required`); - } - return { value: [], errors }; - } - try { - const parsed = JSON.parse(value.toString()); - if (!Array.isArray(parsed)) { - if (!skipValidation) { - errors.push(`${field.field_label} must be a JSON array`); - } - return { value: [], errors }; - } - if (!skipValidation && field.is_required && parsed.length === 0) { - errors.push(`${field.field_label} is required`); - } - return { value: parsed, errors }; - } catch { - if (!skipValidation) { - errors.push(`${field.field_label} must be valid JSON`); - } - return { value: [], errors }; - } - } - case "object": { - if (!value || value.toString().trim() === "") { - if (!skipValidation && field.is_required) { - errors.push(`${field.field_label} is required`); - } - return { value: {}, errors }; - } - try { - const parsed = JSON.parse(value.toString()); - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { - if (!skipValidation) { - errors.push(`${field.field_label} must be a JSON object`); - } - return { value: {}, errors }; - } - if (!skipValidation && field.is_required && Object.keys(parsed).length === 0) { - errors.push(`${field.field_label} is required`); - } - return { value: parsed, errors }; - } catch { - if (!skipValidation) { - errors.push(`${field.field_label} must be valid JSON`); - } - return { value: {}, errors }; - } - } - case "json": { - if (!value || value.toString().trim() === "") { - if (!skipValidation && field.is_required) { - errors.push(`${field.field_label} is required`); - } - return { value: null, errors }; - } - try { - return { value: JSON.parse(value.toString()), errors: [] }; - } catch { - if (!skipValidation) { - errors.push(`${field.field_label} must be valid JSON`); - } - return { value: null, errors }; - } - } - default: - return { value, errors: [] }; - } -} -function extractFieldData(fields, formData, options = {}) { - const data = {}; - const errors = {}; - for (const field of fields) { - const result = parseFieldValue(field, formData, options); - data[field.field_name] = result.value; - if (result.errors.length > 0) { - errors[field.field_name] = result.errors; - } - } - return { data, errors }; -} -adminContentRoutes.use("*", chunkDVQA5II3_cjs.requireAuth()); -async function getCollectionFields(db, collectionId) { - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.collection); - return cache.getOrSet( - cache.generateKey("fields", collectionId), - async () => { - const collectionStmt = db.prepare("SELECT schema FROM collections WHERE id = ?"); - const collectionRow = await collectionStmt.bind(collectionId).first(); - if (collectionRow && collectionRow.schema) { - try { - const schema = typeof collectionRow.schema === "string" ? JSON.parse(collectionRow.schema) : collectionRow.schema; - if (schema && schema.properties) { - let fieldOrder = 0; - return Object.entries(schema.properties).map(([fieldName, fieldConfig]) => { - let fieldOptions = { ...fieldConfig }; - if (fieldConfig.type === "select" && fieldConfig.enum) { - fieldOptions.options = fieldConfig.enum.map((value, index) => ({ - value, - label: fieldConfig.enumLabels?.[index] || value - })); - } - return { - id: `schema-${fieldName}`, - field_name: fieldName, - field_type: fieldConfig.type || "string", - field_label: fieldConfig.title || fieldName, - field_options: fieldOptions, - field_order: fieldOrder++, - is_required: fieldConfig.required === true || schema.required && schema.required.includes(fieldName), - is_searchable: false - }; - }); - } - } catch (e) { - console.error("Error parsing collection schema:", e); - } - } - const stmt = db.prepare(` - SELECT * FROM content_fields - WHERE collection_id = ? - ORDER BY field_order ASC - `); - const { results } = await stmt.bind(collectionId).all(); - return (results || []).map((row) => ({ - id: row.id, - field_name: row.field_name, - field_type: row.field_type, - field_label: row.field_label, - field_options: row.field_options ? JSON.parse(row.field_options) : {}, - field_order: row.field_order, - is_required: row.is_required === 1, - is_searchable: row.is_searchable === 1 - })); - } - ); -} -async function getCollection(db, collectionId) { - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.collection); - return cache.getOrSet( - cache.generateKey("collection", collectionId), - async () => { - const stmt = db.prepare("SELECT * FROM collections WHERE id = ? AND is_active = 1"); - const collection = await stmt.bind(collectionId).first(); - if (!collection) return null; - return { - id: collection.id, - name: collection.name, - display_name: collection.display_name, - description: collection.description, - schema: collection.schema ? JSON.parse(collection.schema) : {} - }; - } - ); -} -adminContentRoutes.get("/", async (c) => { - try { - const user = c.get("user"); - const url = new URL(c.req.url); - const db = c.env.DB; - const page = parseInt(url.searchParams.get("page") || "1"); - const limit = parseInt(url.searchParams.get("limit") || "20"); - const modelName = url.searchParams.get("model") || "all"; - const status = url.searchParams.get("status") || "all"; - const search = url.searchParams.get("search") || ""; - const offset = (page - 1) * limit; - const collectionsStmt = db.prepare("SELECT id, name, display_name FROM collections WHERE is_active = 1 ORDER BY display_name"); - const { results: collectionsResults } = await collectionsStmt.all(); - const models = (collectionsResults || []).map((row) => ({ - name: row.name, - displayName: row.display_name - })); - const conditions = []; - const params = []; - if (status !== "deleted") { - conditions.push("c.status != 'deleted'"); - } - if (search) { - conditions.push("(c.title LIKE ? OR c.slug LIKE ? OR c.data LIKE ?)"); - params.push(`%${search}%`, `%${search}%`, `%${search}%`); - } - if (modelName !== "all") { - conditions.push("col.name = ?"); - params.push(modelName); - } - if (status !== "all" && status !== "deleted") { - conditions.push("c.status = ?"); - params.push(status); - } else if (status === "deleted") { - conditions.push("c.status = 'deleted'"); - } - const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : ""; - const countStmt = db.prepare(` - SELECT COUNT(*) as count - FROM content c - JOIN collections col ON c.collection_id = col.id - ${whereClause} - `); - const countResult = await countStmt.bind(...params).first(); - const totalItems = countResult?.count || 0; - const contentStmt = db.prepare(` - SELECT c.id, c.title, c.slug, c.status, c.created_at, c.updated_at, - col.name as collection_name, col.display_name as collection_display_name, - u.first_name, u.last_name, u.email as author_email - FROM content c - JOIN collections col ON c.collection_id = col.id - LEFT JOIN users u ON c.author_id = u.id - ${whereClause} - ORDER BY c.updated_at DESC - LIMIT ? OFFSET ? - `); - const { results } = await contentStmt.bind(...params, limit, offset).all(); - const contentItems = (results || []).map((row) => { - const statusConfig = { - draft: { - class: "bg-zinc-50 dark:bg-zinc-500/10 text-zinc-700 dark:text-zinc-400 ring-1 ring-inset ring-zinc-600/20 dark:ring-zinc-500/20", - text: "Draft" - }, - review: { - class: "bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 ring-1 ring-inset ring-amber-600/20 dark:ring-amber-500/20", - text: "Under Review" - }, - scheduled: { - class: "bg-blue-50 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 ring-1 ring-inset ring-blue-600/20 dark:ring-blue-500/20", - text: "Scheduled" - }, - published: { - class: "bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 ring-1 ring-inset ring-green-600/20 dark:ring-green-500/20", - text: "Published" - }, - archived: { - class: "bg-purple-50 dark:bg-purple-500/10 text-purple-700 dark:text-purple-400 ring-1 ring-inset ring-purple-600/20 dark:ring-purple-500/20", - text: "Archived" - }, - deleted: { - class: "bg-red-50 dark:bg-red-500/10 text-red-700 dark:text-red-400 ring-1 ring-inset ring-red-600/20 dark:ring-red-500/20", - text: "Deleted" - } - }; - const config = statusConfig[row.status] || statusConfig.draft; - const statusBadge = ` - - ${config?.text || row.status} - - `; - const authorName = row.first_name && row.last_name ? `${row.first_name} ${row.last_name}` : row.author_email || "Unknown"; - const formattedDate = new Date(row.updated_at).toLocaleDateString(); - const availableActions = []; - switch (row.status) { - case "draft": - availableActions.push("submit_for_review", "publish"); - break; - case "review": - availableActions.push("approve", "request_changes"); - break; - case "published": - availableActions.push("unpublish", "archive"); - break; - case "scheduled": - availableActions.push("unschedule"); - break; - } - return { - id: row.id, - title: row.title, - slug: row.slug, - modelName: row.collection_display_name, - statusBadge, - authorName, - formattedDate, - availableActions - }; - }); - const pageData = { - modelName, - status, - page, - search, - models, - contentItems, - totalItems, - itemsPerPage: limit, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion") - }; - return c.html(renderContentListPage(pageData)); - } catch (error) { - console.error("Error fetching content list:", error); - return c.html(`

Error loading content: ${error}

`); - } -}); -adminContentRoutes.get("/new", async (c) => { - try { - const user = c.get("user"); - const url = new URL(c.req.url); - const collectionId = url.searchParams.get("collection"); - if (!collectionId) { - const db2 = c.env.DB; - const collectionsStmt = db2.prepare("SELECT id, name, display_name, description FROM collections WHERE is_active = 1 ORDER BY display_name"); - const { results } = await collectionsStmt.all(); - const collections = (results || []).map((row) => ({ - id: row.id, - name: row.name, - display_name: row.display_name, - description: row.description - })); - const selectionHTML = ` - - - - Select Collection - SonicJS AI Admin - - - -
-
-

Create New Content

-

Select a collection to create content in:

- -
- ${collections.map((collection2) => ` - -

${collection2.display_name}

-

${collection2.description || "No description"}

-
- `).join("")} -
- - -
-
- - - `; - return c.html(selectionHTML); - } - const db = c.env.DB; - const collection = await getCollection(db, collectionId); - if (!collection) { - const formData2 = { - collection: { id: "", name: "", display_name: "Unknown", schema: {} }, - fields: [], - error: "Collection not found.", - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - }; - return c.html(renderContentFormPage(formData2)); - } - const fields = await getCollectionFields(db, collectionId); - const workflowEnabled = await isPluginActive2(db, "workflow"); - const tinymceEnabled = await isPluginActive2(db, "tinymce-plugin"); - let tinymceSettings; - if (tinymceEnabled) { - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - const tinymcePlugin2 = await pluginService.getPlugin("tinymce-plugin"); - tinymceSettings = tinymcePlugin2?.settings; - } - const quillEnabled = await isPluginActive2(db, "quill-editor"); - let quillSettings; - if (quillEnabled) { - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - const quillPlugin = await pluginService.getPlugin("quill-editor"); - quillSettings = quillPlugin?.settings; - } - const mdxeditorEnabled = await isPluginActive2(db, "easy-mdx"); - let mdxeditorSettings; - if (mdxeditorEnabled) { - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - const mdxeditorPlugin = await pluginService.getPlugin("easy-mdx"); - mdxeditorSettings = mdxeditorPlugin?.settings; - } - console.log("[Content Form /new] Editor plugins status:", { - tinymce: tinymceEnabled, - quill: quillEnabled, - mdxeditor: mdxeditorEnabled, - mdxeditorSettings - }); - const formData = { - collection, - fields, - isEdit: false, - workflowEnabled, - tinymceEnabled, - tinymceSettings, - quillEnabled, - quillSettings, - mdxeditorEnabled, - mdxeditorSettings, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - }; - return c.html(renderContentFormPage(formData)); - } catch (error) { - console.error("Error loading new content form:", error); - const formData = { - collection: { id: "", name: "", display_name: "Unknown", schema: {} }, - fields: [], - error: "Failed to load content form.", - user: c.get("user") ? { - name: c.get("user").email, - email: c.get("user").email, - role: c.get("user").role - } : void 0 - }; - return c.html(renderContentFormPage(formData)); - } -}); -adminContentRoutes.get("/:id/edit", async (c) => { - try { - const id = c.req.param("id"); - const user = c.get("user"); - const db = c.env.DB; - const url = new URL(c.req.url); - const referrerParams = url.searchParams.get("ref") || ""; - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.content); - const content = await cache.getOrSet( - cache.generateKey("content", id), - async () => { - const contentStmt = db.prepare(` - SELECT c.*, col.id as collection_id, col.name as collection_name, - col.display_name as collection_display_name, col.description as collection_description, - col.schema as collection_schema - FROM content c - JOIN collections col ON c.collection_id = col.id - WHERE c.id = ? - `); - return await contentStmt.bind(id).first(); - } - ); - if (!content) { - const formData2 = { - collection: { id: "", name: "", display_name: "Unknown", schema: {} }, - fields: [], - error: "Content not found.", - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - }; - return c.html(renderContentFormPage(formData2)); - } - const collection = { - id: content.collection_id, - name: content.collection_name, - display_name: content.collection_display_name, - description: content.collection_description, - schema: content.collection_schema ? JSON.parse(content.collection_schema) : {} - }; - const fields = await getCollectionFields(db, content.collection_id); - const contentData = content.data ? JSON.parse(content.data) : {}; - const workflowEnabled = await isPluginActive2(db, "workflow"); - const tinymceEnabled = await isPluginActive2(db, "tinymce-plugin"); - let tinymceSettings; - if (tinymceEnabled) { - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - const tinymcePlugin2 = await pluginService.getPlugin("tinymce-plugin"); - tinymceSettings = tinymcePlugin2?.settings; - } - const quillEnabled = await isPluginActive2(db, "quill-editor"); - let quillSettings; - if (quillEnabled) { - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - const quillPlugin = await pluginService.getPlugin("quill-editor"); - quillSettings = quillPlugin?.settings; - } - const mdxeditorEnabled = await isPluginActive2(db, "easy-mdx"); - let mdxeditorSettings; - if (mdxeditorEnabled) { - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - const mdxeditorPlugin = await pluginService.getPlugin("easy-mdx"); - mdxeditorSettings = mdxeditorPlugin?.settings; - } - const formData = { - id: content.id, - title: content.title, - slug: content.slug, - data: contentData, - status: content.status, - scheduled_publish_at: content.scheduled_publish_at, - scheduled_unpublish_at: content.scheduled_unpublish_at, - review_status: content.review_status, - meta_title: content.meta_title, - meta_description: content.meta_description, - collection, - fields, - isEdit: true, - workflowEnabled, - tinymceEnabled, - tinymceSettings, - quillEnabled, - quillSettings, - mdxeditorEnabled, - mdxeditorSettings, - referrerParams, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion") - }; - return c.html(renderContentFormPage(formData)); - } catch (error) { - console.error("Error loading edit content form:", error); - const formData = { - collection: { id: "", name: "", display_name: "Unknown", schema: {} }, - fields: [], - error: "Failed to load content for editing.", - user: c.get("user") ? { - name: c.get("user").email, - email: c.get("user").email, - role: c.get("user").role - } : void 0 - }; - return c.html(renderContentFormPage(formData)); - } -}); -adminContentRoutes.post("/", async (c) => { - try { - const user = c.get("user"); - const formData = await c.req.formData(); - const collectionId = formData.get("collection_id"); - const action = formData.get("action"); - if (!collectionId) { - return c.html(html.html` -
- Collection ID is required. -
- `); - } - const db = c.env.DB; - const collection = await getCollection(db, collectionId); - if (!collection) { - return c.html(html.html` -
- Collection not found. -
- `); - } - const fields = await getCollectionFields(db, collectionId); - const { data, errors } = extractFieldData(fields, formData); - if (Object.keys(errors).length > 0) { - const formDataWithErrors = { - collection, - fields, - data, - validationErrors: errors, - error: "Please fix the validation errors below.", - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - }; - return c.html(renderContentFormPage(formDataWithErrors)); - } - let slug = data.slug || data.title; - if (slug) { - slug = slug.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim("-"); - } - let status = formData.get("status") || "draft"; - if (action === "save_and_publish") { - status = "published"; - } - const scheduledPublishAt = formData.get("scheduled_publish_at"); - const scheduledUnpublishAt = formData.get("scheduled_unpublish_at"); - const contentId = crypto.randomUUID(); - const now = Date.now(); - const insertStmt = db.prepare(` - INSERT INTO content ( - id, collection_id, slug, title, data, status, - author_id, created_at, updated_at - ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await insertStmt.bind( - contentId, - collectionId, - slug, - data.title || "Untitled", - JSON.stringify(data), - status, - user?.userId || "unknown", - now, - now - ).run(); - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.content); - await cache.invalidate(`content:list:${collectionId}:*`); - const versionStmt = db.prepare(` - INSERT INTO content_versions (id, content_id, version, data, author_id, created_at) - VALUES (?, ?, ?, ?, ?, ?) - `); - await versionStmt.bind( - crypto.randomUUID(), - contentId, - 1, - JSON.stringify(data), - user?.userId || "unknown", - now - ).run(); - const workflowStmt = db.prepare(` - INSERT INTO workflow_history (id, content_id, action, from_status, to_status, user_id, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?) - `); - await workflowStmt.bind( - crypto.randomUUID(), - contentId, - "created", - "none", - status, - user?.userId || "unknown", - now - ).run(); - const referrerParams = formData.get("referrer_params"); - const redirectUrl = action === "save_and_continue" ? `/admin/content/${contentId}/edit?success=Content saved successfully!${referrerParams ? `&ref=${encodeURIComponent(referrerParams)}` : ""}` : referrerParams ? `/admin/content?${referrerParams}&success=Content created successfully!` : `/admin/content?collection=${collectionId}&success=Content created successfully!`; - const isHTMX = c.req.header("HX-Request") === "true"; - if (isHTMX) { - return c.text("", 200, { - "HX-Redirect": redirectUrl - }); - } else { - return c.redirect(redirectUrl); - } - } catch (error) { - console.error("Error creating content:", error); - return c.html(html.html` -
- Failed to create content. Please try again. -
- `); - } -}); -adminContentRoutes.put("/:id", async (c) => { - try { - const id = c.req.param("id"); - const user = c.get("user"); - const formData = await c.req.formData(); - const action = formData.get("action"); - const db = c.env.DB; - const contentStmt = db.prepare("SELECT * FROM content WHERE id = ?"); - const existingContent = await contentStmt.bind(id).first(); - if (!existingContent) { - return c.html(html.html` -
- Content not found. -
- `); - } - const collection = await getCollection(db, existingContent.collection_id); - if (!collection) { - return c.html(html.html` -
- Collection not found. -
- `); - } - const fields = await getCollectionFields(db, existingContent.collection_id); - const { data, errors } = extractFieldData(fields, formData); - if (Object.keys(errors).length > 0) { - const formDataWithErrors = { - id, - collection, - fields, - data, - validationErrors: errors, - error: "Please fix the validation errors below.", - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - }; - return c.html(renderContentFormPage(formDataWithErrors)); - } - let slug = data.slug || data.title; - if (slug) { - slug = slug.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim("-"); - } - let status = formData.get("status") || existingContent.status; - if (action === "save_and_publish") { - status = "published"; - } - const scheduledPublishAt = formData.get("scheduled_publish_at"); - const scheduledUnpublishAt = formData.get("scheduled_unpublish_at"); - const now = Date.now(); - const updateStmt = db.prepare(` - UPDATE content SET - slug = ?, title = ?, data = ?, status = ?, - scheduled_publish_at = ?, scheduled_unpublish_at = ?, - meta_title = ?, meta_description = ?, updated_at = ? - WHERE id = ? - `); - await updateStmt.bind( - slug, - data.title || "Untitled", - JSON.stringify(data), - status, - scheduledPublishAt ? new Date(scheduledPublishAt).getTime() : null, - scheduledUnpublishAt ? new Date(scheduledUnpublishAt).getTime() : null, - data.meta_title || null, - data.meta_description || null, - now, - id - ).run(); - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.content); - await cache.delete(cache.generateKey("content", id)); - await cache.invalidate(`content:list:${existingContent.collection_id}:*`); - const existingData = JSON.parse(existingContent.data || "{}"); - if (JSON.stringify(existingData) !== JSON.stringify(data)) { - const versionCountStmt = db.prepare("SELECT MAX(version) as max_version FROM content_versions WHERE content_id = ?"); - const versionResult = await versionCountStmt.bind(id).first(); - const nextVersion = (versionResult?.max_version || 0) + 1; - const versionStmt = db.prepare(` - INSERT INTO content_versions (id, content_id, version, data, author_id, created_at) - VALUES (?, ?, ?, ?, ?, ?) - `); - await versionStmt.bind( - crypto.randomUUID(), - id, - nextVersion, - JSON.stringify(data), - user?.userId || "unknown", - now - ).run(); - } - if (status !== existingContent.status) { - const workflowStmt = db.prepare(` - INSERT INTO workflow_history (id, content_id, action, from_status, to_status, user_id, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?) - `); - await workflowStmt.bind( - crypto.randomUUID(), - id, - "status_changed", - existingContent.status, - status, - user?.userId || "unknown", - now - ).run(); - } - const referrerParams = formData.get("referrer_params"); - const redirectUrl = action === "save_and_continue" ? `/admin/content/${id}/edit?success=Content updated successfully!${referrerParams ? `&ref=${encodeURIComponent(referrerParams)}` : ""}` : referrerParams ? `/admin/content?${referrerParams}&success=Content updated successfully!` : `/admin/content?collection=${existingContent.collection_id}&success=Content updated successfully!`; - const isHTMX = c.req.header("HX-Request") === "true"; - if (isHTMX) { - return c.text("", 200, { - "HX-Redirect": redirectUrl - }); - } else { - return c.redirect(redirectUrl); - } - } catch (error) { - console.error("Error updating content:", error); - return c.html(html.html` -
- Failed to update content. Please try again. -
- `); - } -}); -adminContentRoutes.post("/preview", async (c) => { - try { - const formData = await c.req.formData(); - const collectionId = formData.get("collection_id"); - const db = c.env.DB; - const collection = await getCollection(db, collectionId); - if (!collection) { - return c.html("

Collection not found

"); - } - const fields = await getCollectionFields(db, collectionId); - const { data } = extractFieldData(fields, formData, { skipValidation: true }); - const previewHTML = ` - - - - - - Preview: ${data.title || "Untitled"} - - - -

${data.title || "Untitled"}

-
- Collection: ${collection.display_name}
- Status: ${formData.get("status") || "draft"}
- ${data.meta_description ? `Description: ${data.meta_description}
` : ""} -
-
- ${data.content || "

No content provided.

"} -
- -

All Fields:

- - - ${fields.map((field) => ` - - - - - `).join("")} -
FieldValue
${field.field_label}${data[field.field_name] || "empty"}
- - - `; - return c.html(previewHTML); - } catch (error) { - console.error("Error generating preview:", error); - return c.html("

Error generating preview

"); - } -}); -adminContentRoutes.post("/duplicate", async (c) => { - try { - const user = c.get("user"); - const formData = await c.req.formData(); - const originalId = formData.get("id"); - if (!originalId) { - return c.json({ success: false, error: "Content ID required" }); - } - const db = c.env.DB; - const contentStmt = db.prepare("SELECT * FROM content WHERE id = ?"); - const original = await contentStmt.bind(originalId).first(); - if (!original) { - return c.json({ success: false, error: "Content not found" }); - } - const newId = crypto.randomUUID(); - const now = Date.now(); - const originalData = JSON.parse(original.data || "{}"); - originalData.title = `${originalData.title || "Untitled"} (Copy)`; - const insertStmt = db.prepare(` - INSERT INTO content ( - id, collection_id, slug, title, data, status, - author_id, created_at, updated_at - ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await insertStmt.bind( - newId, - original.collection_id, - `${original.slug}-copy-${Date.now()}`, - originalData.title, - JSON.stringify(originalData), - "draft", - // Always start as draft - user?.userId || "unknown", - now, - now - ).run(); - return c.json({ success: true, id: newId }); - } catch (error) { - console.error("Error duplicating content:", error); - return c.json({ success: false, error: "Failed to duplicate content" }); - } -}); -adminContentRoutes.get("/bulk-actions", async (c) => { - const bulkActionsModal = ` -
-
-
-

Bulk Actions

- -
-

- Select items from the table below to perform bulk actions. -

-
- - - -
-
-
- - `; - return c.html(bulkActionsModal); -}); -adminContentRoutes.post("/bulk-action", async (c) => { - try { - const user = c.get("user"); - const body = await c.req.json(); - const { action, ids } = body; - if (!action || !ids || ids.length === 0) { - return c.json({ success: false, error: "Action and IDs required" }); - } - const db = c.env.DB; - const now = Date.now(); - if (action === "delete") { - const placeholders = ids.map(() => "?").join(","); - const stmt = db.prepare(` - UPDATE content - SET status = 'deleted', updated_at = ? - WHERE id IN (${placeholders}) - `); - await stmt.bind(now, ...ids).run(); - } else if (action === "publish" || action === "draft") { - const placeholders = ids.map(() => "?").join(","); - const publishedAt = action === "publish" ? now : null; - const stmt = db.prepare(` - UPDATE content - SET status = ?, published_at = ?, updated_at = ? - WHERE id IN (${placeholders}) - `); - await stmt.bind(action, publishedAt, now, ...ids).run(); - } else { - return c.json({ success: false, error: "Invalid action" }); - } - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.content); - for (const contentId of ids) { - await cache.delete(cache.generateKey("content", contentId)); - } - await cache.invalidate("content:list:*"); - return c.json({ success: true, count: ids.length }); - } catch (error) { - console.error("Bulk action error:", error); - return c.json({ success: false, error: "Failed to perform bulk action" }); - } -}); -adminContentRoutes.delete("/:id", async (c) => { - try { - const id = c.req.param("id"); - const db = c.env.DB; - const user = c.get("user"); - const contentStmt = db.prepare("SELECT id, title FROM content WHERE id = ?"); - const content = await contentStmt.bind(id).first(); - if (!content) { - return c.json({ success: false, error: "Content not found" }, 404); - } - const now = Date.now(); - const deleteStmt = db.prepare(` - UPDATE content - SET status = 'deleted', updated_at = ? - WHERE id = ? - `); - await deleteStmt.bind(now, id).run(); - const cache = chunkVNLR35GO_cjs.getCacheService(chunkVNLR35GO_cjs.CACHE_CONFIGS.content); - await cache.delete(cache.generateKey("content", id)); - await cache.invalidate("content:list:*"); - return c.html(` -
-
-
- - - -

Content deleted successfully. Refreshing...

-
-
-
- `); - } catch (error) { - console.error("Delete content error:", error); - return c.json({ success: false, error: "Failed to delete content" }, 500); - } -}); -adminContentRoutes.get("/:id/versions", async (c) => { - try { - const id = c.req.param("id"); - const db = c.env.DB; - const contentStmt = db.prepare("SELECT * FROM content WHERE id = ?"); - const content = await contentStmt.bind(id).first(); - if (!content) { - return c.html("

Content not found

"); - } - const versionsStmt = db.prepare(` - SELECT cv.*, u.first_name, u.last_name, u.email - FROM content_versions cv - LEFT JOIN users u ON cv.author_id = u.id - WHERE cv.content_id = ? - ORDER BY cv.version DESC - `); - const { results } = await versionsStmt.bind(id).all(); - const versions = (results || []).map((row) => ({ - id: row.id, - version: row.version, - data: JSON.parse(row.data || "{}"), - author_id: row.author_id, - author_name: row.first_name && row.last_name ? `${row.first_name} ${row.last_name}` : row.email, - created_at: row.created_at, - is_current: false - // Will be set below - })); - if (versions.length > 0) { - versions[0].is_current = true; - } - const data = { - contentId: id, - versions, - currentVersion: versions.length > 0 ? versions[0].version : 1 - }; - return c.html(renderVersionHistory(data)); - } catch (error) { - console.error("Error loading version history:", error); - return c.html("

Error loading version history

"); - } -}); -adminContentRoutes.post("/:id/restore/:version", async (c) => { - try { - const id = c.req.param("id"); - const version = parseInt(c.req.param("version")); - const user = c.get("user"); - const db = c.env.DB; - const versionStmt = db.prepare(` - SELECT * FROM content_versions - WHERE content_id = ? AND version = ? - `); - const versionData = await versionStmt.bind(id, version).first(); - if (!versionData) { - return c.json({ success: false, error: "Version not found" }); - } - const contentStmt = db.prepare("SELECT * FROM content WHERE id = ?"); - const currentContent = await contentStmt.bind(id).first(); - if (!currentContent) { - return c.json({ success: false, error: "Content not found" }); - } - const restoredData = JSON.parse(versionData.data); - const now = Date.now(); - const updateStmt = db.prepare(` - UPDATE content SET - title = ?, data = ?, updated_at = ? - WHERE id = ? - `); - await updateStmt.bind( - restoredData.title || "Untitled", - versionData.data, - now, - id - ).run(); - const nextVersionStmt = db.prepare("SELECT MAX(version) as max_version FROM content_versions WHERE content_id = ?"); - const nextVersionResult = await nextVersionStmt.bind(id).first(); - const nextVersion = (nextVersionResult?.max_version || 0) + 1; - const newVersionStmt = db.prepare(` - INSERT INTO content_versions (id, content_id, version, data, author_id, created_at) - VALUES (?, ?, ?, ?, ?, ?) - `); - await newVersionStmt.bind( - crypto.randomUUID(), - id, - nextVersion, - versionData.data, - user?.userId || "unknown", - now - ).run(); - const workflowStmt = db.prepare(` - INSERT INTO workflow_history (id, content_id, action, from_status, to_status, user_id, comment, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - `); - await workflowStmt.bind( - crypto.randomUUID(), - id, - "version_restored", - currentContent.status, - currentContent.status, - user?.userId || "unknown", - `Restored to version ${version}`, - now - ).run(); - return c.json({ success: true }); - } catch (error) { - console.error("Error restoring version:", error); - return c.json({ success: false, error: "Failed to restore version" }); - } -}); -adminContentRoutes.get("/:id/version/:version/preview", async (c) => { - try { - const id = c.req.param("id"); - const version = parseInt(c.req.param("version")); - const db = c.env.DB; - const versionStmt = db.prepare(` - SELECT cv.*, c.collection_id, col.display_name as collection_name - FROM content_versions cv - JOIN content c ON cv.content_id = c.id - JOIN collections col ON c.collection_id = col.id - WHERE cv.content_id = ? AND cv.version = ? - `); - const versionData = await versionStmt.bind(id, version).first(); - if (!versionData) { - return c.html("

Version not found

"); - } - const data = JSON.parse(versionData.data || "{}"); - const previewHTML = ` - - - - - - Version ${version} Preview: ${data.title || "Untitled"} - - - -
- Version ${version} - Collection: ${versionData.collection_name}
- Created: ${new Date(versionData.created_at).toLocaleString()}
- This is a historical version preview -
- -

${data.title || "Untitled"}

- -
- ${data.content || "

No content provided.

"} -
- - ${data.excerpt ? `

Excerpt:

${data.excerpt}

` : ""} - -

All Field Data:

-
-${JSON.stringify(data, null, 2)}
-        
- - - `; - return c.html(previewHTML); - } catch (error) { - console.error("Error generating version preview:", error); - return c.html("

Error generating preview

"); - } -}); -var admin_content_default = adminContentRoutes; - -// src/templates/pages/admin-profile.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderAvatarImage(avatarUrl, firstName, lastName) { - return `
- ${avatarUrl ? `Profile picture` : `${firstName.charAt(0)}${lastName.charAt(0)}`} -
`; -} -function renderProfilePage(data) { - const pageContent = ` -
- -
-
-

User Profile

-

- Manage your account settings and preferences -

-
-
- - - ${data.error ? chunkSHCYIZAN_cjs.renderAlert({ type: "error", message: data.error, dismissible: true }) : ""} - ${data.success ? chunkSHCYIZAN_cjs.renderAlert({ type: "success", message: data.success, dismissible: true }) : ""} - - -
- -
-
- -
-
-
- - - -
-
-

Profile Information

-

Update your account details

-
-
-
- - -
-
- - -
-
- - -
-
- - -
-
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- - -
-

Preferences

- -
-
- -
- - -
-
-
- -
- - -
-
-
-
- - -
-

Notifications

- -
-
-
-
- - - - -
-
-
- -

Receive email updates about new features and product announcements.

-
-
-
-
- - -
- -
-
-
-
- - -
- -
-

Profile Picture

- -
- ${renderAvatarImage(data.profile.avatar_url, data.profile.first_name, data.profile.last_name)} - -
- - -
- -
-
-
- - -
-

Account Information

- -
-
-
Role
-
- - ${data.profile.role} - -
-
-
-
Member Since
-
${new Date(data.profile.created_at).toLocaleDateString()}
-
- ${data.profile.last_login_at ? ` -
-
Last Login
-
${new Date(data.profile.last_login_at).toLocaleDateString()}
-
- ` : ""} -
-
Two-Factor Auth
-
- ${data.profile.two_factor_enabled ? 'Enabled' : 'Disabled'} -
-
-
-
- - -
-

Security

- -
- - - -
-
-
-
-
- - - - - - `; - const layoutData = { - title: "User Profile", - pageTitle: "Profile", - currentPath: "/admin/profile", - user: data.user, - version: data.version, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/components/alert.template.ts -function renderAlert2(data) { - const typeClasses = { - success: "bg-green-50 dark:bg-green-500/10 border border-green-600/20 dark:border-green-500/20", - error: "bg-error/10 border border-red-600/20 dark:border-red-500/20", - warning: "bg-amber-50 dark:bg-amber-500/10 border border-amber-600/20 dark:border-amber-500/20", - info: "bg-blue-50 dark:bg-blue-500/10 border border-blue-600/20 dark:border-blue-500/20" - }; - const iconClasses = { - success: "text-green-600 dark:text-green-400", - error: "text-red-600 dark:text-red-400", - warning: "text-amber-600 dark:text-amber-400", - info: "text-blue-600 dark:text-blue-400" - }; - const textClasses = { - success: "text-green-900 dark:text-green-300", - error: "text-red-900 dark:text-red-300", - warning: "text-amber-900 dark:text-amber-300", - info: "text-blue-900 dark:text-blue-300" - }; - const messageTextClasses = { - success: "text-green-700 dark:text-green-400", - error: "text-red-700 dark:text-red-400", - warning: "text-amber-700 dark:text-amber-400", - info: "text-blue-700 dark:text-blue-400" - }; - const icons = { - success: ``, - error: ``, - warning: ``, - info: `` - }; - return ` -
-
- ${data.icon !== false ? ` -
- - ${icons[data.type]} - -
- ` : ""} -
- ${data.title ? ` -

- ${data.title} -

- ` : ""} -
-

${data.message}

-
-
- ${data.dismissible ? ` -
-
- -
-
- ` : ""} -
-
- `; -} - -// src/templates/pages/admin-activity-logs.template.ts -function renderActivityLogsPage(data) { - const pageContent = ` -
- -
-
-

Activity Logs

-

Monitor user actions and system activity

-
-
- - - - - -
-

Filters

- -
-
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - - Clear Filters - -
-
-
- - -
-
-
-
-

Recent Activity

-
- Showing ${data.logs.length} of ${data.pagination.total} logs -
-
-
- -
- - - - - - - - - - - - - ${data.logs.map((log) => ` - - - - - - - - - `).join("")} - -
TimestampUserActionResourceIP AddressDetails
- ${new Date(log.created_at).toLocaleString()} - -
${log.user_name || "Unknown"}
-
${log.user_email || "N/A"}
-
- - ${formatAction(log.action)} - - - ${log.resource_type ? ` -
${log.resource_type}
- ${log.resource_id ? `
${log.resource_id}
` : ""} - ` : "N/A"} -
- ${log.ip_address || "N/A"} - - ${log.details ? ` -
- View Details -
${JSON.stringify(log.details, null, 2)}
-
- ` : "N/A"} -
-
- - ${data.logs.length === 0 ? ` -
- - - -

No activity logs found

-

Try adjusting your filters or check back later.

-
- ` : ""} - - - ${data.pagination.pages > 1 ? ` -
-
- Page ${data.pagination.page} of ${data.pagination.pages} (${data.pagination.total} total logs) -
-
- ${data.pagination.page > 1 ? ` - - Previous - - ` : ""} - ${data.pagination.page < data.pagination.pages ? ` - - Next - - ` : ""} -
-
- ` : ""} -
-
- `; - const layoutData = { - title: "Activity Logs", - pageTitle: "Activity Logs", - currentPath: "/admin/activity-logs", - user: data.user, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayout(layoutData); -} -function getActionBadgeClass(action) { - if (action.includes("login") || action.includes("logout")) { - return "bg-blue-500/20 text-blue-300"; - } else if (action.includes("create") || action.includes("invite")) { - return "bg-green-500/20 text-green-300"; - } else if (action.includes("update") || action.includes("change")) { - return "bg-yellow-500/20 text-yellow-300"; - } else if (action.includes("delete") || action.includes("cancel")) { - return "bg-red-500/20 text-red-300"; - } else { - return "bg-gray-500/20 text-gray-300"; - } -} -function formatAction(action) { - return action.split(".").map((part) => part.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase())).join(" - "); -} - -// src/templates/pages/admin-user-edit.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); - -// src/templates/components/confirmation-dialog.template.ts -function renderConfirmationDialog2(options) { - const { - id, - title, - message, - confirmText = "Confirm", - cancelText = "Cancel", - confirmClass = "bg-red-500 hover:bg-red-400", - iconColor = "red", - onConfirm = "" - } = options; - const iconColorClasses = { - red: "bg-red-500/10 text-red-400", - yellow: "bg-yellow-500/10 text-yellow-400", - blue: "bg-blue-500/10 text-blue-400" - }; - return ` - - - - -
- -
-
- -
-
-

${title}

-
-

${message}

-
-
-
-
- - -
-
-
-
-
- `; -} -function getConfirmationDialogScript2() { - return ` - - - `; -} - -// src/templates/pages/admin-user-edit.template.ts -function renderUserEditPage(data) { - const pageContent = ` -
- -
-
-
- - - - - -

Edit User

-
-

Update user account and permissions

-
-
- - - Cancel - -
-
- - -
- ${data.error ? chunkSHCYIZAN_cjs.renderAlert({ type: "error", message: data.error, dismissible: true }) : ""} - ${data.success ? chunkSHCYIZAN_cjs.renderAlert({ type: "success", message: data.success, dismissible: true }) : ""} -
- - -
- -
-
-
- - -
-

Basic Information

-
-
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- -
- - -
-
-
-
- - -
-

Profile Information

-

Extended profile data for this user

-
-
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
-
- -
- - -
-
- - -
-

Account Status

-
-
-
-
- - - - - -
-
-
- -

User can sign in and access the system

-
-
- -
-
-
- - - - - -
-
-
- -

User has verified their email address

-
-
-
-
- -
-
-
- - -
- -
-

User Details

-
-
-
User ID
-
${data.userToEdit.id}
-
-
-
Created
-
${new Date(data.userToEdit.createdAt).toLocaleDateString()}
-
- ${data.userToEdit.lastLoginAt ? ` -
-
Last Login
-
${new Date(data.userToEdit.lastLoginAt).toLocaleDateString()}
-
- ` : ""} -
-
Status
-
- ${data.userToEdit.isActive ? 'Active' : 'Inactive'} -
-
- ${data.userToEdit.twoFactorEnabled ? ` -
-
Security
-
- 2FA Enabled -
-
- ` : ""} -
-
- - -
-

Danger Zone

-

Irreversible and destructive actions

- -
-
-
- - - - - -
-
-
- -

Permanently remove from database. Unchecked performs soft delete (deactivate only).

-
-
- - -
-
-
-
- - - - - ${renderConfirmationDialog2({ - id: "delete-user-confirm", - title: "Delete User", - message: 'Are you sure you want to delete this user? Check the "Hard Delete" option to permanently remove all data from the database. This action cannot be undone!', - confirmText: "Delete", - cancelText: "Cancel", - iconColor: "red", - confirmClass: "bg-red-500 hover:bg-red-400", - onConfirm: "performDeleteUser()" - })} - - ${getConfirmationDialogScript2()} - `; - const layoutData = { - title: "Edit User", - pageTitle: `Edit User - ${data.userToEdit.firstName} ${data.userToEdit.lastName}`, - currentPath: "/admin/users", - user: data.user, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/pages/admin-user-new.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderUserNewPage(data) { - const pageContent = ` -
- -
-
-
- - - - - -

Create New User

-
-

Add a new user account to the system

-
-
- - - Cancel - -
-
- - -
- ${data.error ? chunkSHCYIZAN_cjs.renderAlert({ type: "error", message: data.error, dismissible: true }) : ""} - ${data.success ? chunkSHCYIZAN_cjs.renderAlert({ type: "success", message: data.success, dismissible: true }) : ""} -
- - -
- -
-
-
- - -
-

Basic Information

-
-
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- -
- - -
-
-
- -
- - -
-
- - -
-

Password

-
-
- - -
- -
- - -
-
-
- - -
-

Account Status

-
-
-
-
- - - - - -
-
-
- -

User can sign in and access the system

-
-
- -
-
-
- - - - - -
-
-
- -

Mark email as verified

-
-
-
-
- -
-
-
- - -
- -
-

Creating a User

-
-

Fill in the required fields marked with * to create a new user account.

-

The password must be at least 8 characters long.

-

By default, new users are created as active and can sign in immediately.

-

You can edit user details and permissions after creation.

-
-
- - -
-

Role Descriptions

-
-
-
Administrator
-
Full system access and permissions
-
-
-
Editor
-
Can create and edit content
-
-
-
Author
-
Can create own content
-
-
-
Viewer
-
Read-only access
-
-
-
-
-
-
- `; - const layoutData = { - title: "Create User", - pageTitle: "Create New User", - currentPath: "/admin/users", - user: data.user, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/pages/admin-users-list.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderUsersListPage(data) { - const columns = [ - { - key: "avatar", - label: "", - className: "w-12", - sortable: false, - render: (value, row) => { - const initials = `${row.firstName.charAt(0)}${row.lastName.charAt(0)}`.toUpperCase(); - if (value) { - return `${row.firstName} ${row.lastName}`; - } - return ` -
- ${initials} -
- `; - } - }, - { - key: "name", - label: "Name", - sortable: true, - sortType: "string", - render: (_value, row) => { - const escapeHtml6 = (text) => text.replace(/[&<>"']/g, (char) => ({ - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'" - })[char] || char); - const truncatedFirstName = row.firstName.length > 25 ? row.firstName.substring(0, 25) + "..." : row.firstName; - const truncatedLastName = row.lastName.length > 25 ? row.lastName.substring(0, 25) + "..." : row.lastName; - const fullName = escapeHtml6(`${truncatedFirstName} ${truncatedLastName}`); - const truncatedUsername = row.username.length > 100 ? row.username.substring(0, 100) + "..." : row.username; - const username = escapeHtml6(truncatedUsername); - const statusBadge = row.isActive ? 'Active' : 'Inactive'; - return ` -
-
${fullName}${statusBadge}
-
@${username}
-
- `; - } - }, - { - key: "email", - label: "Email", - sortable: true, - sortType: "string", - render: (value) => { - const escapeHtml6 = (text) => text.replace(/[&<>"']/g, (char) => ({ - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'" - })[char] || char); - const escapedEmail = escapeHtml6(value); - return `${escapedEmail}`; - } - }, - { - key: "role", - label: "Role", - sortable: true, - sortType: "string", - render: (value) => { - const roleColors = { - admin: "bg-red-50 dark:bg-red-500/10 text-red-700 dark:text-red-400 ring-1 ring-inset ring-red-700/10 dark:ring-red-500/20", - editor: "bg-blue-50 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 ring-1 ring-inset ring-blue-700/10 dark:ring-blue-500/20", - author: "bg-cyan-50 dark:bg-cyan-500/10 text-cyan-700 dark:text-cyan-400 ring-1 ring-inset ring-cyan-700/10 dark:ring-cyan-500/20", - viewer: "bg-zinc-50 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400 ring-1 ring-inset ring-zinc-500/10 dark:ring-zinc-400/20" - }; - const colorClass = roleColors[value] || "bg-zinc-50 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400 ring-1 ring-inset ring-zinc-500/10 dark:ring-zinc-400/20"; - return `${value.charAt(0).toUpperCase() + value.slice(1)}`; - } - }, - { - key: "lastLoginAt", - label: "Last Login", - sortable: true, - sortType: "date", - render: (value) => { - if (!value) return 'Never'; - return `${new Date(value).toLocaleDateString()}`; - } - }, - { - key: "createdAt", - label: "Created", - sortable: true, - sortType: "date", - render: (value) => `${new Date(value).toLocaleDateString()}` - }, - { - key: "actions", - label: "Actions", - className: "text-right", - sortable: false, - render: (_value, row) => ` -
- ${row.isActive ? `` : ``} -
- ` - } - ]; - const tableData = { - tableId: "users-table", - columns, - rows: data.users, - selectable: false, - rowClickable: true, - rowClickUrl: (row) => `/admin/users/${row.id}/edit`, - emptyMessage: "No users found" - }; - const pageContent = ` -
- -
-
-

User Management

-

Manage user accounts and permissions

-
-
- - - - - Add User - - -
-
- - - ${data.error ? chunkSHCYIZAN_cjs.renderAlert({ type: "error", message: data.error, dismissible: true }) : ""} - ${data.success ? chunkSHCYIZAN_cjs.renderAlert({ type: "success", message: data.success, dismissible: true }) : ""} - - -
-

User Statistics

-
-
-
Total Users
-
-
- ${data.totalUsers} -
-
- - - - Increased by - 5.2% -
-
-
-
-
Active Users
-
-
- ${data.users.filter((u) => u.isActive).length} -
-
- - - - Increased by - 3.1% -
-
-
-
-
Administrators
-
-
- ${data.users.filter((u) => u.role === "admin").length} -
-
- - - - Increased by - 1.8% -
-
-
-
-
Active This Week
-
-
- ${data.users.filter((u) => u.lastLoginAt && u.lastLoginAt > Date.now() - 7 * 24 * 60 * 60 * 1e3).length} -
-
- - - - Decreased by - 2.3% -
-
-
-
-
- - -
- -
- - -
-
-
- -
- -
- - -
- - - -
-
-
- -
- -
- - -
-
- -
- -
- - -
-
- -
- -
- -
-
-
-
-
-
- - - ${chunkSHCYIZAN_cjs.renderTable(tableData)} - - - ${data.pagination ? chunkSHCYIZAN_cjs.renderPagination(data.pagination) : ""} -
- - - - - ${renderConfirmationDialog2({ - id: "toggle-user-status-confirm", - title: "Toggle User Status", - message: "Are you sure you want to activate/deactivate this user?", - confirmText: "Confirm", - cancelText: "Cancel", - iconColor: "yellow", - confirmClass: "bg-yellow-500 hover:bg-yellow-400", - onConfirm: "performToggleUserStatus()" - })} - - ${getConfirmationDialogScript2()} - `; - const layoutData = { - title: "Users", - pageTitle: "User Management", - currentPath: "/admin/users", - user: data.user, - version: data.version, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/routes/admin-users.ts -var userRoutes = new hono.Hono(); -userRoutes.use("*", chunkDVQA5II3_cjs.requireAuth()); -userRoutes.get("/", (c) => { - return c.redirect("/admin/dashboard"); -}); -var TIMEZONES = [ - { value: "UTC", label: "UTC" }, - { value: "America/New_York", label: "Eastern Time" }, - { value: "America/Chicago", label: "Central Time" }, - { value: "America/Denver", label: "Mountain Time" }, - { value: "America/Los_Angeles", label: "Pacific Time" }, - { value: "Europe/London", label: "London" }, - { value: "Europe/Paris", label: "Paris" }, - { value: "Europe/Berlin", label: "Berlin" }, - { value: "Asia/Tokyo", label: "Tokyo" }, - { value: "Asia/Shanghai", label: "Shanghai" }, - { value: "Australia/Sydney", label: "Sydney" } -]; -var LANGUAGES = [ - { value: "en", label: "English" }, - { value: "es", label: "Spanish" }, - { value: "fr", label: "French" }, - { value: "de", label: "German" }, - { value: "it", label: "Italian" }, - { value: "pt", label: "Portuguese" }, - { value: "ja", label: "Japanese" }, - { value: "ko", label: "Korean" }, - { value: "zh", label: "Chinese" } -]; -var ROLES = [ - { value: "admin", label: "Administrator" }, - { value: "editor", label: "Editor" }, - { value: "author", label: "Author" }, - { value: "viewer", label: "Viewer" } -]; -userRoutes.get("/profile", async (c) => { - const user = c.get("user"); - const db = c.env.DB; - try { - const userStmt = db.prepare(` - SELECT id, email, username, first_name, last_name, phone, bio, avatar_url, - timezone, language, theme, email_notifications, two_factor_enabled, - role, created_at, last_login_at - FROM users - WHERE id = ? AND is_active = 1 - `); - const userProfile = await userStmt.bind(user.userId).first(); - if (!userProfile) { - return c.json({ error: "User not found" }, 404); - } - const profile = { - id: userProfile.id, - email: userProfile.email, - username: userProfile.username || "", - first_name: userProfile.first_name || "", - last_name: userProfile.last_name || "", - phone: userProfile.phone, - bio: userProfile.bio, - avatar_url: userProfile.avatar_url, - timezone: userProfile.timezone || "UTC", - language: userProfile.language || "en", - theme: userProfile.theme || "dark", - email_notifications: Boolean(userProfile.email_notifications), - two_factor_enabled: Boolean(userProfile.two_factor_enabled), - role: userProfile.role, - created_at: userProfile.created_at, - last_login_at: userProfile.last_login_at - }; - const pageData = { - profile, - timezones: TIMEZONES, - languages: LANGUAGES, - user: { - name: `${profile.first_name} ${profile.last_name}`.trim() || profile.username || user.email, - email: user.email, - role: user.role - } - }; - return c.html(renderProfilePage(pageData)); - } catch (error) { - console.error("Profile page error:", error); - const pageData = { - profile: {}, - timezones: TIMEZONES, - languages: LANGUAGES, - error: "Failed to load profile. Please try again.", - user: { - name: user.email, - email: user.email, - role: user.role - } - }; - return c.html(renderProfilePage(pageData)); - } -}); -userRoutes.put("/profile", async (c) => { - const user = c.get("user"); - const db = c.env.DB; - try { - const formData = await c.req.formData(); - const firstName = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("first_name")?.toString()); - const lastName = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("last_name")?.toString()); - const username = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("username")?.toString()); - const email = formData.get("email")?.toString()?.trim().toLowerCase() || ""; - const phone = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("phone")?.toString()) || null; - const bio = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("bio")?.toString()) || null; - const timezone = formData.get("timezone")?.toString() || "UTC"; - const language = formData.get("language")?.toString() || "en"; - const emailNotifications = formData.get("email_notifications") === "1"; - if (!firstName || !lastName || !username || !email) { - return c.html(renderAlert2({ - type: "error", - message: "First name, last name, username, and email are required.", - dismissible: true - })); - } - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailRegex.test(email)) { - return c.html(renderAlert2({ - type: "error", - message: "Please enter a valid email address.", - dismissible: true - })); - } - const checkStmt = db.prepare(` - SELECT id FROM users - WHERE (username = ? OR email = ?) AND id != ? AND is_active = 1 - `); - const existingUser = await checkStmt.bind(username, email, user.userId).first(); - if (existingUser) { - return c.html(renderAlert2({ - type: "error", - message: "Username or email is already taken by another user!.", - dismissible: true - })); - } - const updateStmt = db.prepare(` - UPDATE users SET - first_name = ?, last_name = ?, username = ?, email = ?, - phone = ?, bio = ?, timezone = ?, language = ?, - email_notifications = ?, updated_at = ? - WHERE id = ? - `); - await updateStmt.bind( - firstName, - lastName, - username, - email, - phone, - bio, - timezone, - language, - emailNotifications ? 1 : 0, - Date.now(), - user.userId - ).run(); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "profile.update", - "users", - user.userId, - { fields: ["first_name", "last_name", "username", "email", "phone", "bio", "timezone", "language", "email_notifications"] }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - return c.html(renderAlert2({ - type: "success", - message: "Profile updated successfully!", - dismissible: true - })); - } catch (error) { - console.error("Profile update error:", error); - return c.html(renderAlert2({ - type: "error", - message: "Failed to update profile. Please try again.", - dismissible: true - })); - } -}); -userRoutes.post("/profile/avatar", async (c) => { - const user = c.get("user"); - const db = c.env.DB; - try { - const formData = await c.req.formData(); - const avatarFile = formData.get("avatar"); - if (!avatarFile || typeof avatarFile === "string" || !avatarFile.name) { - return c.html(renderAlert2({ - type: "error", - message: "Please select an image file.", - dismissible: true - })); - } - const allowedTypes = ["image/jpeg", "image/png", "image/gif", "image/webp"]; - if (!allowedTypes.includes(avatarFile.type)) { - return c.html(renderAlert2({ - type: "error", - message: "Please upload a valid image file (JPEG, PNG, GIF, or WebP).", - dismissible: true - })); - } - const maxSize = 5 * 1024 * 1024; - if (avatarFile.size > maxSize) { - return c.html(renderAlert2({ - type: "error", - message: "Image file must be smaller than 5MB.", - dismissible: true - })); - } - const avatarUrl = `/uploads/avatars/${user.userId}-${Date.now()}.${avatarFile.type.split("/")[1]}`; - const updateStmt = db.prepare(` - UPDATE users SET avatar_url = ?, updated_at = ? - WHERE id = ? - `); - await updateStmt.bind(avatarUrl, Date.now(), user.userId).run(); - const userStmt = db.prepare(` - SELECT first_name, last_name FROM users WHERE id = ? - `); - const userData = await userStmt.bind(user.userId).first(); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "profile.avatar_update", - "users", - user.userId, - { avatar_url: avatarUrl }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - const alertHtml = renderAlert2({ - type: "success", - message: "Profile picture updated successfully!", - dismissible: true - }); - const avatarUrlWithCache = `${avatarUrl}?t=${Date.now()}`; - const avatarImageHtml = renderAvatarImage(avatarUrlWithCache, userData.first_name, userData.last_name); - const avatarImageWithOob = avatarImageHtml.replace( - 'id="avatar-image-container"', - 'id="avatar-image-container" hx-swap-oob="true"' - ); - return c.html(alertHtml + avatarImageWithOob); - } catch (error) { - console.error("Avatar upload error:", error); - return c.html(renderAlert2({ - type: "error", - message: "Failed to upload profile picture. Please try again.", - dismissible: true - })); - } -}); -userRoutes.post("/profile/password", async (c) => { - const user = c.get("user"); - const db = c.env.DB; - try { - const formData = await c.req.formData(); - const currentPassword = formData.get("current_password")?.toString() || ""; - const newPassword = formData.get("new_password")?.toString() || ""; - const confirmPassword = formData.get("confirm_password")?.toString() || ""; - if (!currentPassword || !newPassword || !confirmPassword) { - return c.html(renderAlert2({ - type: "error", - message: "All password fields are required.", - dismissible: true - })); - } - if (newPassword !== confirmPassword) { - return c.html(renderAlert2({ - type: "error", - message: "New passwords do not match.", - dismissible: true - })); - } - if (newPassword.length < 8) { - return c.html(renderAlert2({ - type: "error", - message: "New password must be at least 8 characters long.", - dismissible: true - })); - } - const userStmt = db.prepare(` - SELECT password_hash FROM users WHERE id = ? AND is_active = 1 - `); - const userData = await userStmt.bind(user.userId).first(); - if (!userData) { - return c.html(renderAlert2({ - type: "error", - message: "User not found.", - dismissible: true - })); - } - const validPassword = await chunkDVQA5II3_cjs.AuthManager.verifyPassword(currentPassword, userData.password_hash); - if (!validPassword) { - return c.html(renderAlert2({ - type: "error", - message: "Current password is incorrect.", - dismissible: true - })); - } - const newPasswordHash = await chunkDVQA5II3_cjs.AuthManager.hashPassword(newPassword); - const historyStmt = db.prepare(` - INSERT INTO password_history (id, user_id, password_hash, created_at) - VALUES (?, ?, ?, ?) - `); - await historyStmt.bind( - crypto.randomUUID(), - user.userId, - userData.password_hash, - Date.now() - ).run(); - const updateStmt = db.prepare(` - UPDATE users SET password_hash = ?, updated_at = ? - WHERE id = ? - `); - await updateStmt.bind(newPasswordHash, Date.now(), user.userId).run(); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "profile.password_change", - "users", - user.userId, - null, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - return c.html(renderAlert2({ - type: "success", - message: "Password updated successfully!", - dismissible: true - })); - } catch (error) { - console.error("Password change error:", error); - return c.html(renderAlert2({ - type: "error", - message: "Failed to update password. Please try again.", - dismissible: true - })); - } -}); -userRoutes.get("/users", async (c) => { - const db = c.env.DB; - const user = c.get("user"); - try { - const page = parseInt(c.req.query("page") || "1"); - const limit = parseInt(c.req.query("limit") || "20"); - const search = c.req.query("search") || ""; - const roleFilter = c.req.query("role") || ""; - const statusFilter = c.req.query("status") || "active"; - const offset = (page - 1) * limit; - let whereClause = ""; - let params = []; - if (statusFilter === "active") { - whereClause = "WHERE u.is_active = 1"; - } else if (statusFilter === "inactive") { - whereClause = "WHERE u.is_active = 0"; - } else { - whereClause = "WHERE 1=1"; - } - if (search) { - whereClause += " AND (u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR u.username LIKE ?)"; - const searchParam = `%${search}%`; - params.push(searchParam, searchParam, searchParam, searchParam); - } - if (roleFilter) { - whereClause += " AND u.role = ?"; - params.push(roleFilter); - } - const usersStmt = db.prepare(` - SELECT u.id, u.email, u.username, u.first_name, u.last_name, - u.role, u.avatar_url, u.created_at, u.last_login_at, u.updated_at, - u.email_verified, u.two_factor_enabled, u.is_active - FROM users u - ${whereClause} - ORDER BY u.created_at DESC - LIMIT ? OFFSET ? - `); - const { results: usersData } = await usersStmt.bind(...params, limit, offset).all(); - const countStmt = db.prepare(` - SELECT COUNT(*) as total FROM users u ${whereClause} - `); - const countResult = await countStmt.bind(...params).first(); - const totalUsers = countResult?.total || 0; - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "users.list_view", - "users", - void 0, - { search, page, limit }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - const acceptHeader = c.req.header("accept") || ""; - const isApiRequest = acceptHeader.includes("application/json"); - if (isApiRequest) { - return c.json({ - users: usersData || [], - pagination: { - page, - limit, - total: totalUsers, - pages: Math.ceil(totalUsers / limit) - } - }); - } - const users = (usersData || []).map((u) => ({ - id: u.id, - email: u.email, - username: u.username || "", - firstName: u.first_name || "", - lastName: u.last_name || "", - role: u.role, - avatar: u.avatar_url, - isActive: Boolean(u.is_active), - lastLoginAt: u.last_login_at, - createdAt: u.created_at, - updatedAt: u.updated_at, - formattedLastLogin: u.last_login_at ? new Date(u.last_login_at).toLocaleDateString() : void 0, - formattedCreatedAt: new Date(u.created_at).toLocaleDateString() - })); - const pageData = { - users, - currentPage: page, - totalPages: Math.ceil(totalUsers / limit), - totalUsers, - searchFilter: search, - roleFilter, - statusFilter, - pagination: { - currentPage: page, - totalPages: Math.ceil(totalUsers / limit), - totalItems: totalUsers, - itemsPerPage: limit, - startItem: offset + 1, - endItem: Math.min(offset + limit, totalUsers), - baseUrl: "/admin/users" - }, - user: { - name: user.email.split("@")[0] || user.email, - email: user.email, - role: user.role - } - }; - return c.html(renderUsersListPage(pageData)); - } catch (error) { - console.error("Users list error:", error); - const acceptHeader = c.req.header("accept") || ""; - const isApiRequest = acceptHeader.includes("application/json"); - if (isApiRequest) { - return c.json({ error: "Failed to load users" }, 500); - } - return c.html(renderAlert2({ - type: "error", - message: "Failed to load users. Please try again.", - dismissible: true - }), 500); - } -}); -userRoutes.get("/users/new", async (c) => { - const user = c.get("user"); - try { - const pageData = { - roles: ROLES, - user: { - name: user.email.split("@")[0] || user.email, - email: user.email, - role: user.role - } - }; - return c.html(renderUserNewPage(pageData)); - } catch (error) { - console.error("User new page error:", error); - return c.html(renderAlert2({ - type: "error", - message: "Failed to load user creation page. Please try again.", - dismissible: true - }), 500); - } -}); -userRoutes.post("/users/new", async (c) => { - const db = c.env.DB; - const user = c.get("user"); - try { - const formData = await c.req.formData(); - const firstName = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("first_name")?.toString()); - const lastName = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("last_name")?.toString()); - const username = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("username")?.toString()); - const email = formData.get("email")?.toString()?.trim().toLowerCase() || ""; - const phone = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("phone")?.toString()) || null; - const bio = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("bio")?.toString()) || null; - const role = formData.get("role")?.toString() || "viewer"; - const password = formData.get("password")?.toString() || ""; - const confirmPassword = formData.get("confirm_password")?.toString() || ""; - const isActive = formData.get("is_active") === "1"; - const emailVerified = formData.get("email_verified") === "1"; - if (!firstName || !lastName || !username || !email || !password) { - return c.html(renderAlert2({ - type: "error", - message: "First name, last name, username, email, and password are required.", - dismissible: true - })); - } - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailRegex.test(email)) { - return c.html(renderAlert2({ - type: "error", - message: "Please enter a valid email address.", - dismissible: true - })); - } - if (password.length < 8) { - return c.html(renderAlert2({ - type: "error", - message: "Password must be at least 8 characters long.", - dismissible: true - })); - } - if (password !== confirmPassword) { - return c.html(renderAlert2({ - type: "error", - message: "Passwords do not match.", - dismissible: true - })); - } - const checkStmt = db.prepare(` - SELECT id FROM users - WHERE username = ? OR email = ? - `); - const existingUser = await checkStmt.bind(username, email).first(); - if (existingUser) { - return c.html(renderAlert2({ - type: "error", - message: "Username or email is already taken.", - dismissible: true - })); - } - const passwordHash = await chunkDVQA5II3_cjs.AuthManager.hashPassword(password); - const userId = crypto.randomUUID(); - const createStmt = db.prepare(` - INSERT INTO users ( - id, email, username, first_name, last_name, phone, bio, - password_hash, role, is_active, email_verified, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await createStmt.bind( - userId, - email, - username, - firstName, - lastName, - phone, - bio, - passwordHash, - role, - isActive ? 1 : 0, - emailVerified ? 1 : 0, - Date.now(), - Date.now() - ).run(); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "user!.create", - "users", - userId, - { email, username, role }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - return c.redirect(`/admin/users/${userId}/edit?success=User created successfully`); - } catch (error) { - console.error("User creation error:", error); - return c.html(renderAlert2({ - type: "error", - message: "Failed to create user!. Please try again.", - dismissible: true - })); - } -}); -userRoutes.get("/users/:id", async (c) => { - if (c.req.path.endsWith("/edit")) { - return c.notFound(); - } - const db = c.env.DB; - const user = c.get("user"); - const userId = c.req.param("id"); - try { - const userStmt = db.prepare(` - SELECT id, email, username, first_name, last_name, phone, bio, avatar_url, - role, is_active, email_verified, two_factor_enabled, created_at, last_login_at - FROM users - WHERE id = ? - `); - const userRecord = await userStmt.bind(userId).first(); - if (!userRecord) { - return c.json({ error: "User not found" }, 404); - } - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "user!.view", - "users", - userId, - null, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - return c.json({ - user: { - id: userRecord.id, - email: userRecord.email, - username: userRecord.username, - first_name: userRecord.first_name, - last_name: userRecord.last_name, - phone: userRecord.phone, - bio: userRecord.bio, - avatar_url: userRecord.avatar_url, - role: userRecord.role, - is_active: userRecord.is_active, - email_verified: userRecord.email_verified, - two_factor_enabled: userRecord.two_factor_enabled, - created_at: userRecord.created_at, - last_login_at: userRecord.last_login_at - } - }); - } catch (error) { - console.error("User fetch error:", error); - return c.json({ error: "Failed to fetch user" }, 500); - } -}); -userRoutes.get("/users/:id/edit", async (c) => { - const db = c.env.DB; - const user = c.get("user"); - const userId = c.req.param("id"); - try { - const userStmt = db.prepare(` - SELECT id, email, username, first_name, last_name, phone, avatar_url, - role, is_active, email_verified, two_factor_enabled, created_at, last_login_at - FROM users - WHERE id = ? - `); - const userToEdit = await userStmt.bind(userId).first(); - if (!userToEdit) { - return c.html(renderAlert2({ - type: "error", - message: "User not found", - dismissible: true - }), 404); - } - const profileStmt = db.prepare(` - SELECT display_name, bio, company, job_title, website, location, date_of_birth - FROM user_profiles - WHERE user_id = ? - `); - const profileData = await profileStmt.bind(userId).first(); - const profile = profileData ? { - displayName: profileData.display_name, - bio: profileData.bio, - company: profileData.company, - jobTitle: profileData.job_title, - website: profileData.website, - location: profileData.location, - dateOfBirth: profileData.date_of_birth - } : void 0; - const editData = { - id: userToEdit.id, - email: userToEdit.email, - username: userToEdit.username || "", - firstName: userToEdit.first_name || "", - lastName: userToEdit.last_name || "", - phone: userToEdit.phone, - avatarUrl: userToEdit.avatar_url, - role: userToEdit.role, - isActive: Boolean(userToEdit.is_active), - emailVerified: Boolean(userToEdit.email_verified), - twoFactorEnabled: Boolean(userToEdit.two_factor_enabled), - createdAt: userToEdit.created_at, - lastLoginAt: userToEdit.last_login_at, - profile - }; - const pageData = { - userToEdit: editData, - roles: ROLES, - user: { - name: user.email.split("@")[0] || user.email, - email: user.email, - role: user.role - } - }; - return c.html(renderUserEditPage(pageData)); - } catch (error) { - console.error("User edit page error:", error); - return c.html(renderAlert2({ - type: "error", - message: "Failed to load user. Please try again.", - dismissible: true - }), 500); - } -}); -userRoutes.put("/users/:id", async (c) => { - const db = c.env.DB; - const user = c.get("user"); - const userId = c.req.param("id"); - try { - const formData = await c.req.formData(); - const firstName = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("first_name")?.toString()); - const lastName = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("last_name")?.toString()); - const username = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("username")?.toString()); - const email = formData.get("email")?.toString()?.trim().toLowerCase() || ""; - const phone = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("phone")?.toString()) || null; - const role = formData.get("role")?.toString() || "viewer"; - const isActive = formData.get("is_active") === "1"; - const emailVerified = formData.get("email_verified") === "1"; - const profileDisplayName = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("profile_display_name")?.toString()) || null; - const profileBio = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("profile_bio")?.toString()) || null; - const profileCompany = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("profile_company")?.toString()) || null; - const profileJobTitle = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("profile_job_title")?.toString()) || null; - const profileWebsite = formData.get("profile_website")?.toString()?.trim() || null; - const profileLocation = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("profile_location")?.toString()) || null; - const profileDateOfBirthStr = formData.get("profile_date_of_birth")?.toString()?.trim() || null; - const profileDateOfBirth = profileDateOfBirthStr ? new Date(profileDateOfBirthStr).getTime() : null; - if (!firstName || !lastName || !username || !email) { - return c.html(renderAlert2({ - type: "error", - message: "First name, last name, username, and email are required.", - dismissible: true - })); - } - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailRegex.test(email)) { - return c.html(renderAlert2({ - type: "error", - message: "Please enter a valid email address.", - dismissible: true - })); - } - if (profileWebsite) { - try { - new URL(profileWebsite); - } catch { - return c.html(renderAlert2({ - type: "error", - message: "Please enter a valid website URL.", - dismissible: true - })); - } - } - const checkStmt = db.prepare(` - SELECT id FROM users - WHERE (username = ? OR email = ?) AND id != ? - `); - const existingUser = await checkStmt.bind(username, email, userId).first(); - if (existingUser) { - return c.html(renderAlert2({ - type: "error", - message: "Username or email is already taken by another user.", - dismissible: true - })); - } - const updateStmt = db.prepare(` - UPDATE users SET - first_name = ?, last_name = ?, username = ?, email = ?, - phone = ?, role = ?, is_active = ?, email_verified = ?, - updated_at = ? - WHERE id = ? - `); - await updateStmt.bind( - firstName, - lastName, - username, - email, - phone, - role, - isActive ? 1 : 0, - emailVerified ? 1 : 0, - Date.now(), - userId - ).run(); - const hasProfileData = profileDisplayName || profileBio || profileCompany || profileJobTitle || profileWebsite || profileLocation || profileDateOfBirth; - if (hasProfileData) { - const now = Date.now(); - const profileCheckStmt = db.prepare(`SELECT id FROM user_profiles WHERE user_id = ?`); - const existingProfile = await profileCheckStmt.bind(userId).first(); - if (existingProfile) { - const updateProfileStmt = db.prepare(` - UPDATE user_profiles SET - display_name = ?, bio = ?, company = ?, job_title = ?, - website = ?, location = ?, date_of_birth = ?, updated_at = ? - WHERE user_id = ? - `); - await updateProfileStmt.bind( - profileDisplayName, - profileBio, - profileCompany, - profileJobTitle, - profileWebsite, - profileLocation, - profileDateOfBirth, - now, - userId - ).run(); - } else { - const profileId = `profile_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`; - const insertProfileStmt = db.prepare(` - INSERT INTO user_profiles (id, user_id, display_name, bio, company, job_title, website, location, date_of_birth, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await insertProfileStmt.bind( - profileId, - userId, - profileDisplayName, - profileBio, - profileCompany, - profileJobTitle, - profileWebsite, - profileLocation, - profileDateOfBirth, - now, - now - ).run(); - } - } - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "user.update", - "users", - userId, - { fields: ["first_name", "last_name", "username", "email", "phone", "role", "is_active", "email_verified", "profile"] }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - return c.html(renderAlert2({ - type: "success", - message: "User updated successfully!", - dismissible: true - })); - } catch (error) { - console.error("User update error:", error); - return c.html(renderAlert2({ - type: "error", - message: "Failed to update user. Please try again.", - dismissible: true - })); - } -}); -userRoutes.post("/users/:id/toggle", async (c) => { - const db = c.env.DB; - const user = c.get("user"); - const userId = c.req.param("id"); - try { - const body = await c.req.json().catch(() => ({ active: true })); - const active = body.active === true; - if (userId === user.userId && !active) { - return c.json({ error: "You cannot deactivate your own account" }, 400); - } - const userStmt = db.prepare(` - SELECT id, email FROM users WHERE id = ? - `); - const userToToggle = await userStmt.bind(userId).first(); - if (!userToToggle) { - return c.json({ error: "User not found" }, 404); - } - const toggleStmt = db.prepare(` - UPDATE users SET is_active = ?, updated_at = ? WHERE id = ? - `); - await toggleStmt.bind(active ? 1 : 0, Date.now(), userId).run(); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - active ? "user.activate" : "user.deactivate", - "users", - userId, - { email: userToToggle.email }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - return c.json({ - success: true, - message: active ? "User activated successfully" : "User deactivated successfully" - }); - } catch (error) { - console.error("User toggle error:", error); - return c.json({ error: "Failed to toggle user status" }, 500); - } -}); -userRoutes.delete("/users/:id", async (c) => { - const db = c.env.DB; - const user = c.get("user"); - const userId = c.req.param("id"); - try { - const body = await c.req.json().catch(() => ({ hardDelete: false })); - const hardDelete = body.hardDelete === true; - if (userId === user.userId) { - return c.json({ error: "You cannot delete your own account" }, 400); - } - const userStmt = db.prepare(` - SELECT id, email FROM users WHERE id = ? - `); - const userToDelete = await userStmt.bind(userId).first(); - if (!userToDelete) { - return c.json({ error: "User not found" }, 404); - } - if (hardDelete) { - const deleteStmt = db.prepare(` - DELETE FROM users WHERE id = ? - `); - await deleteStmt.bind(userId).run(); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "user!.hard_delete", - "users", - userId, - { email: userToDelete.email, permanent: true }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - return c.json({ - success: true, - message: "User permanently deleted" - }); - } else { - const deleteStmt = db.prepare(` - UPDATE users SET is_active = 0, updated_at = ? WHERE id = ? - `); - await deleteStmt.bind(Date.now(), userId).run(); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "user!.soft_delete", - "users", - userId, - { email: userToDelete.email }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - return c.json({ - success: true, - message: "User deactivated successfully" - }); - } - } catch (error) { - console.error("User deletion error:", error); - return c.json({ error: "Failed to delete user" }, 500); - } -}); -userRoutes.post("/invite-user", async (c) => { - const db = c.env.DB; - const user = c.get("user"); - try { - const formData = await c.req.formData(); - const email = formData.get("email")?.toString()?.trim().toLowerCase() || ""; - const role = formData.get("role")?.toString()?.trim() || "viewer"; - const firstName = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("first_name")?.toString()); - const lastName = chunk5HMR2SJW_cjs.sanitizeInput(formData.get("last_name")?.toString()); - if (!email || !firstName || !lastName) { - return c.json({ error: "Email, first name, and last name are required" }, 400); - } - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailRegex.test(email)) { - return c.json({ error: "Please enter a valid email address" }, 400); - } - const existingUserStmt = db.prepare(` - SELECT id FROM users WHERE email = ? - `); - const existingUser = await existingUserStmt.bind(email).first(); - if (existingUser) { - return c.json({ error: "A user with this email already exists" }, 400); - } - const invitationToken = crypto.randomUUID(); - const userId = crypto.randomUUID(); - const createUserStmt = db.prepare(` - INSERT INTO users ( - id, email, first_name, last_name, role, - invitation_token, invited_by, invited_at, - is_active, email_verified, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await createUserStmt.bind( - userId, - email, - firstName, - lastName, - role, - invitationToken, - user.userId, - Date.now(), - 0, - 0, - Date.now(), - Date.now() - ).run(); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "user!.invite_sent", - "users", - userId, - { email, role, invited_user_id: userId }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - const invitationLink = `${c.req.header("origin") || "http://localhost:8787"}/auth/accept-invitation?token=${invitationToken}`; - return c.json({ - success: true, - message: "User invitation sent successfully", - user: { - id: userId, - email, - first_name: firstName, - last_name: lastName, - role - }, - invitation_link: invitationLink - // In production, this would be sent via email - }); - } catch (error) { - console.error("User invitation error:", error); - return c.json({ error: "Failed to send user invitation" }, 500); - } -}); -userRoutes.post("/resend-invitation/:id", async (c) => { - const db = c.env.DB; - const user = c.get("user"); - const userId = c.req.param("id"); - try { - const userStmt = db.prepare(` - SELECT id, email, first_name, last_name, role, invitation_token - FROM users - WHERE id = ? AND is_active = 0 AND invitation_token IS NOT NULL - `); - const invitedUser = await userStmt.bind(userId).first(); - if (!invitedUser) { - return c.json({ error: "User not found or invitation not valid" }, 404); - } - const newInvitationToken = crypto.randomUUID(); - const updateStmt = db.prepare(` - UPDATE users SET - invitation_token = ?, - invited_at = ?, - updated_at = ? - WHERE id = ? - `); - await updateStmt.bind( - newInvitationToken, - Date.now(), - Date.now(), - userId - ).run(); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "user!.invitation_resent", - "users", - userId, - { email: invitedUser.email }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - const invitationLink = `${c.req.header("origin") || "http://localhost:8787"}/auth/accept-invitation?token=${newInvitationToken}`; - return c.json({ - success: true, - message: "Invitation resent successfully", - invitation_link: invitationLink - }); - } catch (error) { - console.error("Resend invitation error:", error); - return c.json({ error: "Failed to resend invitation" }, 500); - } -}); -userRoutes.delete("/cancel-invitation/:id", async (c) => { - const db = c.env.DB; - const user = c.get("user"); - const userId = c.req.param("id"); - try { - const userStmt = db.prepare(` - SELECT id, email FROM users - WHERE id = ? AND is_active = 0 AND invitation_token IS NOT NULL - `); - const invitedUser = await userStmt.bind(userId).first(); - if (!invitedUser) { - return c.json({ error: "User not found or invitation not valid" }, 404); - } - const deleteStmt = db.prepare(`DELETE FROM users WHERE id = ?`); - await deleteStmt.bind(userId).run(); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "user!.invitation_cancelled", - "users", - userId, - { email: invitedUser.email }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - return c.json({ - success: true, - message: "Invitation cancelled successfully" - }); - } catch (error) { - console.error("Cancel invitation error:", error); - return c.json({ error: "Failed to cancel invitation" }, 500); - } -}); -userRoutes.get("/activity-logs", async (c) => { - const db = c.env.DB; - const user = c.get("user"); - try { - const page = parseInt(c.req.query("page") || "1"); - const limit = parseInt(c.req.query("limit") || "50"); - const offset = (page - 1) * limit; - const filters = { - action: c.req.query("action") || "", - resource_type: c.req.query("resource_type") || "", - date_from: c.req.query("date_from") || "", - date_to: c.req.query("date_to") || "", - user_id: c.req.query("user_id") || "" - }; - let whereConditions = []; - let params = []; - if (filters.action) { - whereConditions.push("al.action = ?"); - params.push(filters.action); - } - if (filters.resource_type) { - whereConditions.push("al.resource_type = ?"); - params.push(filters.resource_type); - } - if (filters.user_id) { - whereConditions.push("al.user_id = ?"); - params.push(filters.user_id); - } - if (filters.date_from) { - const fromTimestamp = new Date(filters.date_from).getTime(); - whereConditions.push("al.created_at >= ?"); - params.push(fromTimestamp); - } - if (filters.date_to) { - const toTimestamp = (/* @__PURE__ */ new Date(filters.date_to + " 23:59:59")).getTime(); - whereConditions.push("al.created_at <= ?"); - params.push(toTimestamp); - } - const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(" AND ")}` : ""; - const logsStmt = db.prepare(` - SELECT - al.id, al.user_id, al.action, al.resource_type, al.resource_id, - al.details, al.ip_address, al.user_agent, al.created_at, - u.email as user_email, - COALESCE(u.first_name || ' ' || u.last_name, u.username, u.email) as user_name - FROM activity_logs al - LEFT JOIN users u ON al.user_id = u.id - ${whereClause} - ORDER BY al.created_at DESC - LIMIT ? OFFSET ? - `); - const { results: logs } = await logsStmt.bind(...params, limit, offset).all(); - const countStmt = db.prepare(` - SELECT COUNT(*) as total - FROM activity_logs al - LEFT JOIN users u ON al.user_id = u.id - ${whereClause} - `); - const countResult = await countStmt.bind(...params).first(); - const totalLogs = countResult?.total || 0; - const formattedLogs = (logs || []).map((log) => ({ - ...log, - details: log.details ? JSON.parse(log.details) : null - })); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "activity.logs_viewed", - void 0, - void 0, - { filters, page, limit }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - const pageData = { - logs: formattedLogs, - pagination: { - page, - limit, - total: totalLogs, - pages: Math.ceil(totalLogs / limit) - }, - filters, - user: { - name: user.email.split("@")[0] || user.email, - // Use email username as fallback - email: user.email, - role: user.role - } - }; - return c.html(renderActivityLogsPage(pageData)); - } catch (error) { - console.error("Activity logs error:", error); - const pageData = { - logs: [], - pagination: { page: 1, limit: 50, total: 0, pages: 0 }, - filters: {}, - user: { - name: user.email, - email: user.email, - role: user.role - } - }; - return c.html(renderActivityLogsPage(pageData)); - } -}); -userRoutes.get("/activity-logs/export", async (c) => { - const db = c.env.DB; - const user = c.get("user"); - try { - const filters = { - action: c.req.query("action") || "", - resource_type: c.req.query("resource_type") || "", - date_from: c.req.query("date_from") || "", - date_to: c.req.query("date_to") || "", - user_id: c.req.query("user_id") || "" - }; - let whereConditions = []; - let params = []; - if (filters.action) { - whereConditions.push("al.action = ?"); - params.push(filters.action); - } - if (filters.resource_type) { - whereConditions.push("al.resource_type = ?"); - params.push(filters.resource_type); - } - if (filters.user_id) { - whereConditions.push("al.user_id = ?"); - params.push(filters.user_id); - } - if (filters.date_from) { - const fromTimestamp = new Date(filters.date_from).getTime(); - whereConditions.push("al.created_at >= ?"); - params.push(fromTimestamp); - } - if (filters.date_to) { - const toTimestamp = (/* @__PURE__ */ new Date(filters.date_to + " 23:59:59")).getTime(); - whereConditions.push("al.created_at <= ?"); - params.push(toTimestamp); - } - const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(" AND ")}` : ""; - const logsStmt = db.prepare(` - SELECT - al.id, al.user_id, al.action, al.resource_type, al.resource_id, - al.details, al.ip_address, al.user_agent, al.created_at, - u.email as user_email, - COALESCE(u.first_name || ' ' || u.last_name, u.username, u.email) as user_name - FROM activity_logs al - LEFT JOIN users u ON al.user_id = u.id - ${whereClause} - ORDER BY al.created_at DESC - LIMIT 10000 - `); - const { results: logs } = await logsStmt.bind(...params).all(); - const csvHeaders = ["Timestamp", "User", "Email", "Action", "Resource Type", "Resource ID", "IP Address", "Details"]; - const csvRows = [csvHeaders.join(",")]; - for (const log of logs || []) { - const row = [ - `"${new Date(log.created_at).toISOString()}"`, - `"${log.user_name || "Unknown"}"`, - `"${log.user_email || "N/A"}"`, - `"${log.action}"`, - `"${log.resource_type || "N/A"}"`, - `"${log.resource_id || "N/A"}"`, - `"${log.ip_address || "N/A"}"`, - `"${log.details ? JSON.stringify(JSON.parse(log.details)) : "N/A"}"` - ]; - csvRows.push(row.join(",")); - } - const csvContent = csvRows.join("\n"); - await chunkDVQA5II3_cjs.logActivity( - db, - user.userId, - "activity.logs_exported", - void 0, - void 0, - { filters, count: logs?.length || 0 }, - c.req.header("x-forwarded-for") || c.req.header("cf-connecting-ip"), - c.req.header("user-agent") - ); - const filename = `activity-logs-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.csv`; - return new Response(csvContent, { - headers: { - "Content-Type": "text/csv", - "Content-Disposition": `attachment; filename="${filename}"` - } - }); - } catch (error) { - console.error("Activity logs export error:", error); - return c.json({ error: "Failed to export activity logs" }, 500); - } -}); - -// src/templates/components/media-grid.template.ts -function renderMediaGrid(data) { - if (data.files.length === 0) { - return ` -
- - - -

No media files

-

${data.emptyMessage || "Get started by uploading your first file."}

-
- `; - } - const gridClass = data.viewMode === "list" ? "space-y-4" : "media-grid"; - return ` -
- ${data.files.map( - (file) => renderMediaFileCard(file, data.viewMode, data.selectable) - ).join("")} -
- `; -} -function renderMediaFileCard(file, viewMode = "grid", selectable = false) { - if (viewMode === "list") { - return ` -
-
- ${selectable ? ` -
-
- - - - - -
-
- ` : ""} - -
- ${file.isImage ? ` - ${file.alt || file.original_name} - ` : ` -
- ${getFileIcon(file.mime_type)} -
- `} -
- -
-
-

- ${file.original_name} -

-
- ${file.fileSize} - -
-
-
- ${file.uploadedAt} - ${file.tags.length > 0 ? ` - \u2022 -
- ${file.tags.slice(0, 2).map( - (tag) => ` - - ${tag} - - ` - ).join("")} - ${file.tags.length > 2 ? `+${file.tags.length - 2}` : ""} -
- ` : ""} -
-
-
-
- `; - } - return ` -
- ${selectable ? ` -
-
-
- - - - - -
-
-
- ` : ""} - -
- ${file.isImage ? ` - ${file.alt || file.original_name} - ` : ` -
- ${getFileIcon(file.mime_type)} -
- `} - - -
-
- - -
-
-
- -
-

- ${file.original_name} -

-
- ${file.fileSize} - ${file.uploadedAt} -
- ${file.tags.length > 0 ? ` -
- ${file.tags.slice(0, 2).map( - (tag) => ` - - ${tag} - - ` - ).join("")} - ${file.tags.length > 2 ? `+${file.tags.length - 2}` : ""} -
- ` : ""} -
-
- `; -} -function getFileIcon(mimeType) { - if (mimeType.startsWith("image/")) { - return ` - - - - `; - } else if (mimeType.startsWith("video/")) { - return ` - - - - `; - } else if (mimeType === "application/pdf") { - return ` - - - - `; - } else { - return ` - - - - `; - } -} - -// src/templates/pages/admin-media-library.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderMediaLibraryPage(data) { - const pageContent = ` -
- -
-
-

Media Library

-

Manage your media files and assets

-
-
- -
-
- -
- -
-
- -
- -
- - -
-

Folders

- -
- - -
-

File Types

- -
- - -
-

Quick Actions

-
- - -
-
-
-
- - -
- -
- -
- -
-
-
-
-
- -
- - -
-
- -
- -
- - - -
- - - -
-
- -
- ${data.files.length} files - -
- - - -
-
-
-
-
-
- - -
- ${renderMediaGrid({ - files: data.files, - viewMode: data.currentView, - selectable: true, - emptyMessage: "No media files found. Upload your first file to get started." - })} -
- - - ${data.hasNextPage ? ` -
-
- ${data.currentPage > 1 ? ` - - Previous - - ` : ""} - Page ${data.currentPage} - - Next - -
-
- ` : ""} -
-
-
- - - - - - - - - - - - - - - - - - - ${renderConfirmationDialog2({ - id: "media-bulk-delete-confirm", - title: "Delete Selected Files", - message: `Are you sure you want to delete ${data.files.length > 0 ? "the selected files" : "these files"}? This action cannot be undone and the files will be permanently removed.`, - confirmText: "Delete Files", - cancelText: "Cancel", - confirmClass: "bg-red-500 hover:bg-red-400", - iconColor: "red", - onConfirm: "performBulkDelete()" - })} - - - ${getConfirmationDialogScript2()} - `; - function buildPageUrl(page, folder, type) { - const params = new URLSearchParams(); - params.set("page", page.toString()); - if (folder !== "all") params.set("folder", folder); - if (type !== "all") params.set("type", type); - return `/admin/media?${params.toString()}`; - } - const layoutData = { - title: "Media Library", - pageTitle: "Media Library", - currentPath: "/admin/media", - user: data.user, - version: data.version, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/components/media-file-details.template.ts -function renderMediaFileDetails(data) { - const { file } = data; - return ` -
-

File Details

- -
- -
- -
-
- ${file.isImage ? ` - ${file.alt || file.filename} - ` : file.isVideo ? ` - - ` : ` -
- - - -
- `} -
- -
- - - Open Original - -
-
- - -
-
- -

${file.original_name}

-
- -
-
- -

${file.fileSize}

-
-
- -

${file.mime_type}

-
-
- - ${file.width && file.height ? ` -
-
- -

${file.width}px

-
-
- -

${file.height}px

-
-
- ` : ""} - -
- -

${file.folder}

-
- -
- -

${file.uploadedAt}

-
- - -
-
- - -
- -
- - -
- -
- - -
- -
- - -
-
-
-
- `; -} - -// src/routes/admin-media.ts -var fileValidationSchema2 = zod.z.object({ - name: zod.z.string().min(1).max(255), - type: zod.z.string().refine( - (type) => { - const allowedTypes = [ - // Images - "image/jpeg", - "image/jpg", - "image/png", - "image/gif", - "image/webp", - "image/svg+xml", - // Documents - "application/pdf", - "text/plain", - "application/msword", - "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - // Videos - "video/mp4", - "video/webm", - "video/ogg", - "video/avi", - "video/mov", - // Audio - "audio/mp3", - "audio/wav", - "audio/ogg", - "audio/m4a" - ]; - return allowedTypes.includes(type); - }, - { message: "Unsupported file type" } - ), - size: zod.z.number().min(1).max(50 * 1024 * 1024) - // 50MB max -}); -var adminMediaRoutes = new hono.Hono(); -adminMediaRoutes.use("*", chunkDVQA5II3_cjs.requireAuth()); -adminMediaRoutes.get("/", async (c) => { - try { - const user = c.get("user"); - const { searchParams } = new URL(c.req.url); - const folder = searchParams.get("folder") || "all"; - const type = searchParams.get("type") || "all"; - const view = searchParams.get("view") || "grid"; - const page = parseInt(searchParams.get("page") || "1"); - const _cacheBust = searchParams.get("t"); - const limit = 24; - const offset = (page - 1) * limit; - const db = c.env.DB; - let query = "SELECT * FROM media"; - const params = []; - const conditions = ["deleted_at IS NULL"]; - if (folder !== "all") { - conditions.push("folder = ?"); - params.push(folder); - } - if (type !== "all") { - switch (type) { - case "images": - conditions.push("mime_type LIKE ?"); - params.push("image/%"); - break; - case "documents": - conditions.push("mime_type IN (?, ?, ?)"); - params.push("application/pdf", "text/plain", "application/msword"); - break; - case "videos": - conditions.push("mime_type LIKE ?"); - params.push("video/%"); - break; - } - } - if (conditions.length > 0) { - query += ` WHERE ${conditions.join(" AND ")}`; - } - query += ` ORDER BY uploaded_at DESC LIMIT ${limit} OFFSET ${offset}`; - const stmt = db.prepare(query); - const { results } = await stmt.bind(...params).all(); - const foldersStmt = db.prepare(` - SELECT folder, COUNT(*) as count, SUM(size) as totalSize - FROM media - WHERE deleted_at IS NULL - GROUP BY folder - ORDER BY folder - `); - const { results: folders } = await foldersStmt.all(); - const typesStmt = db.prepare(` - SELECT - CASE - WHEN mime_type LIKE 'image/%' THEN 'images' - WHEN mime_type LIKE 'video/%' THEN 'videos' - WHEN mime_type IN ('application/pdf', 'text/plain') THEN 'documents' - ELSE 'other' - END as type, - COUNT(*) as count - FROM media - WHERE deleted_at IS NULL - GROUP BY type - `); - const { results: types } = await typesStmt.all(); - const mediaFiles = results.map((row) => ({ - id: row.id, - filename: row.filename, - original_name: row.original_name, - mime_type: row.mime_type, - size: row.size, - public_url: `/files/${row.r2_key}`, - thumbnail_url: row.mime_type.startsWith("image/") ? `/files/${row.r2_key}` : void 0, - alt: row.alt, - caption: row.caption, - tags: row.tags ? JSON.parse(row.tags) : [], - uploaded_at: row.uploaded_at, - fileSize: formatFileSize(row.size), - uploadedAt: new Date(row.uploaded_at).toLocaleDateString(), - isImage: row.mime_type.startsWith("image/"), - isVideo: row.mime_type.startsWith("video/"), - isDocument: !row.mime_type.startsWith("image/") && !row.mime_type.startsWith("video/") - })); - const pageData = { - files: mediaFiles, - folders: folders.map((f) => ({ - folder: f.folder, - count: f.count, - totalSize: f.totalSize - })), - types: types.map((t) => ({ - type: t.type, - count: t.count - })), - currentFolder: folder, - currentType: type, - currentView: view, - currentPage: page, - totalFiles: results.length, - hasNextPage: results.length === limit, - user: { - name: user.email, - email: user.email, - role: user.role - }, - version: c.get("appVersion") - }; - return c.html(renderMediaLibraryPage(pageData)); - } catch (error) { - console.error("Error loading media library:", error); - return c.html(html.html`

Error loading media library

`); - } -}); -adminMediaRoutes.get("/selector", async (c) => { - try { - const { searchParams } = new URL(c.req.url); - const search = searchParams.get("search") || ""; - const db = c.env.DB; - let query = "SELECT * FROM media WHERE deleted_at IS NULL"; - const params = []; - if (search.trim()) { - query += " AND (filename LIKE ? OR original_name LIKE ? OR alt LIKE ?)"; - const searchTerm = `%${search}%`; - params.push(searchTerm, searchTerm, searchTerm); - } - query += " ORDER BY uploaded_at DESC LIMIT 24"; - const stmt = db.prepare(query); - const { results } = await stmt.bind(...params).all(); - const mediaFiles = results.map((row) => ({ - id: row.id, - filename: row.filename, - original_name: row.original_name, - mime_type: row.mime_type, - size: row.size, - public_url: `/files/${row.r2_key}`, - thumbnail_url: row.mime_type.startsWith("image/") ? `/files/${row.r2_key}` : void 0, - alt: row.alt, - tags: row.tags ? JSON.parse(row.tags) : [], - uploaded_at: row.uploaded_at, - fileSize: formatFileSize(row.size), - uploadedAt: new Date(row.uploaded_at).toLocaleDateString(), - isImage: row.mime_type.startsWith("image/"), - isVideo: row.mime_type.startsWith("video/"), - isDocument: !row.mime_type.startsWith("image/") && !row.mime_type.startsWith("video/") - })); - return c.html(html.html` -
- -
- -
- ${html.raw(mediaFiles.map((file) => ` -
-
- ${file.isImage ? ` - ${file.alt || file.filename} - ` : file.isVideo ? ` - - ` : ` -
-
- - - - ${file.filename.split(".").pop()?.toUpperCase()} -
-
- `} - -
- -
-
- -
-

- ${file.original_name} -

-

- ${file.fileSize} -

-
-
- `).join(""))} -
- - ${mediaFiles.length === 0 ? html.html` -
- - - -

No media files found

-
- ` : ""} - `); - } catch (error) { - console.error("Error loading media selector:", error); - return c.html(html.html`
Error loading media files
`); - } -}); -adminMediaRoutes.get("/search", async (c) => { - try { - const { searchParams } = new URL(c.req.url); - const search = searchParams.get("search") || ""; - const folder = searchParams.get("folder") || "all"; - const type = searchParams.get("type") || "all"; - const db = c.env.DB; - let query = "SELECT * FROM media"; - const params = []; - const conditions = []; - if (search.trim()) { - conditions.push("(filename LIKE ? OR original_name LIKE ? OR alt LIKE ?)"); - const searchTerm = `%${search}%`; - params.push(searchTerm, searchTerm, searchTerm); - } - if (folder !== "all") { - conditions.push("folder = ?"); - params.push(folder); - } - if (type !== "all") { - switch (type) { - case "images": - conditions.push("mime_type LIKE ?"); - params.push("image/%"); - break; - case "documents": - conditions.push("mime_type IN (?, ?, ?)"); - params.push("application/pdf", "text/plain", "application/msword"); - break; - case "videos": - conditions.push("mime_type LIKE ?"); - params.push("video/%"); - break; - } - } - if (conditions.length > 0) { - query += ` WHERE ${conditions.join(" AND ")}`; - } - query += ` ORDER BY uploaded_at DESC LIMIT 24`; - const stmt = db.prepare(query); - const { results } = await stmt.bind(...params).all(); - const mediaFiles = results.map((row) => ({ - ...row, - public_url: `/files/${row.r2_key}`, - thumbnail_url: row.mime_type.startsWith("image/") ? `/files/${row.r2_key}` : void 0, - tags: row.tags ? JSON.parse(row.tags) : [], - uploadedAt: new Date(row.uploaded_at).toLocaleDateString(), - fileSize: formatFileSize(row.size), - isImage: row.mime_type.startsWith("image/"), - isVideo: row.mime_type.startsWith("video/"), - isDocument: !row.mime_type.startsWith("image/") && !row.mime_type.startsWith("video/") - })); - const gridHTML = mediaFiles.map((file) => generateMediaItemHTML(file)).join(""); - return c.html(html.raw(gridHTML)); - } catch (error) { - console.error("Error searching media:", error); - return c.html('
Error searching files
'); - } -}); -adminMediaRoutes.get("/:id/details", async (c) => { - try { - const id = c.req.param("id"); - const db = c.env.DB; - const stmt = db.prepare("SELECT * FROM media WHERE id = ?"); - const result = await stmt.bind(id).first(); - if (!result) { - return c.html('
File not found
'); - } - const file = { - id: result.id, - filename: result.filename, - original_name: result.original_name, - mime_type: result.mime_type, - size: result.size, - public_url: `/files/${result.r2_key}`, - thumbnail_url: result.mime_type.startsWith("image/") ? `/files/${result.r2_key}` : void 0, - alt: result.alt, - caption: result.caption, - tags: result.tags ? JSON.parse(result.tags) : [], - uploaded_at: result.uploaded_at, - fileSize: formatFileSize(result.size), - uploadedAt: new Date(result.uploaded_at).toLocaleString(), - isImage: result.mime_type.startsWith("image/"), - isVideo: result.mime_type.startsWith("video/"), - isDocument: !result.mime_type.startsWith("image/") && !result.mime_type.startsWith("video/"), - width: result.width, - height: result.height, - folder: result.folder - }; - const detailsData = { file }; - return c.html(renderMediaFileDetails(detailsData)); - } catch (error) { - console.error("Error fetching file details:", error); - return c.html('
Error loading file details
'); - } -}); -adminMediaRoutes.post("/upload", async (c) => { - try { - const user = c.get("user"); - const formData = await c.req.formData(); - const fileEntries = formData.getAll("files"); - const files = []; - for (const entry of fileEntries) { - if (entry instanceof File) { - files.push(entry); - } - } - if (!files || files.length === 0) { - return c.html(html.html` -
- No files provided -
- `); - } - const uploadResults = []; - const errors = []; - console.log("[MEDIA UPLOAD] c.env keys:", Object.keys(c.env)); - console.log("[MEDIA UPLOAD] MEDIA_BUCKET defined?", !!c.env.MEDIA_BUCKET); - console.log("[MEDIA UPLOAD] MEDIA_BUCKET type:", typeof c.env.MEDIA_BUCKET); - if (!c.env.MEDIA_BUCKET) { - console.error("[MEDIA UPLOAD] MEDIA_BUCKET is not available! Available env keys:", Object.keys(c.env)); - return c.html(html.html` -
- Media storage (R2) is not configured. Please check your wrangler.toml configuration. -
Debug: Available bindings: ${Object.keys(c.env).join(", ")} -
- `); - } - for (const file of files) { - try { - const validation = fileValidationSchema2.safeParse({ - name: file.name, - type: file.type, - size: file.size - }); - if (!validation.success) { - errors.push({ - filename: file.name, - error: validation.error.issues[0]?.message || "Validation failed" - }); - continue; - } - const fileId = crypto.randomUUID(); - const fileExtension = file.name.split(".").pop() || ""; - const filename = `${fileId}.${fileExtension}`; - const folder = formData.get("folder") || "uploads"; - const r2Key = `${folder}/${filename}`; - const arrayBuffer = await file.arrayBuffer(); - const uploadResult = await c.env.MEDIA_BUCKET.put(r2Key, arrayBuffer, { - httpMetadata: { - contentType: file.type, - contentDisposition: `inline; filename="${file.name}"` - }, - customMetadata: { - originalName: file.name, - uploadedBy: user.userId, - uploadedAt: (/* @__PURE__ */ new Date()).toISOString() - } - }); - if (!uploadResult) { - errors.push({ - filename: file.name, - error: "Failed to upload to storage" - }); - continue; - } - let width; - let height; - if (file.type.startsWith("image/") && !file.type.includes("svg")) { - try { - const dimensions = await getImageDimensions2(arrayBuffer); - width = dimensions.width; - height = dimensions.height; - } catch (error) { - console.warn("Failed to extract image dimensions:", error); - } - } - const publicUrl = `/files/${r2Key}`; - const thumbnailUrl = file.type.startsWith("image/") ? publicUrl : void 0; - const stmt = c.env.DB.prepare(` - INSERT INTO media ( - id, filename, original_name, mime_type, size, width, height, - folder, r2_key, public_url, thumbnail_url, uploaded_by, uploaded_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await stmt.bind( - fileId, - filename, - file.name, - file.type, - file.size, - width, - height, - folder, - r2Key, - publicUrl, - thumbnailUrl, - user.userId, - Math.floor(Date.now() / 1e3) - ).run(); - uploadResults.push({ - id: fileId, - filename, - originalName: file.name, - mimeType: file.type, - size: file.size, - publicUrl - }); - } catch (error) { - errors.push({ - filename: file.name, - error: "Upload failed: " + (error instanceof Error ? error.message : "Unknown error") - }); - } - } - let mediaGridHTML = ""; - if (uploadResults.length > 0) { - try { - const folderEntry = formData.get("folder"); - const folder = typeof folderEntry === "string" ? folderEntry : "uploads"; - const query = "SELECT * FROM media WHERE deleted_at IS NULL ORDER BY uploaded_at DESC LIMIT 24"; - const stmt = c.env.DB.prepare(query); - const { results } = await stmt.all(); - const mediaFiles = results.map((row) => ({ - id: row.id, - filename: row.filename, - original_name: row.original_name, - mime_type: row.mime_type, - size: row.size, - public_url: `/files/${row.r2_key}`, - thumbnail_url: row.mime_type.startsWith("image/") ? `/files/${row.r2_key}` : void 0, - tags: row.tags ? JSON.parse(row.tags) : [], - uploaded_at: row.uploaded_at, - fileSize: formatFileSize(row.size), - uploadedAt: new Date(row.uploaded_at).toLocaleDateString(), - isImage: row.mime_type.startsWith("image/"), - isVideo: row.mime_type.startsWith("video/"), - isDocument: !row.mime_type.startsWith("image/") && !row.mime_type.startsWith("video/") - })); - mediaGridHTML = mediaFiles.map((file) => renderMediaFileCard(file, "grid", true)).join(""); - } catch (error) { - console.error("Error fetching updated media list:", error); - } - } - return c.html(html.html` - ${uploadResults.length > 0 ? html.html` -
- Successfully uploaded ${uploadResults.length} file${uploadResults.length > 1 ? "s" : ""} -
- ` : ""} - - ${errors.length > 0 ? html.html` -
-

Upload errors:

-
    - ${errors.map((error) => html.html` -
  • ${error.filename}: ${error.error}
  • - `)} -
-
- ` : ""} - - ${uploadResults.length > 0 ? html.html` - - ` : ""} - `); - } catch (error) { - console.error("Upload error:", error); - return c.html(html.html` -
- Upload failed: ${error instanceof Error ? error.message : "Unknown error"} -
- `); - } -}); -adminMediaRoutes.get("/file/*", async (c) => { - try { - const r2Key = c.req.path.replace("/admin/media/file/", ""); - if (!r2Key) { - return c.notFound(); - } - const object = await c.env.MEDIA_BUCKET.get(r2Key); - if (!object) { - return c.notFound(); - } - const headers = new Headers(); - object.httpMetadata?.contentType && headers.set("Content-Type", object.httpMetadata.contentType); - object.httpMetadata?.contentDisposition && headers.set("Content-Disposition", object.httpMetadata.contentDisposition); - headers.set("Cache-Control", "public, max-age=31536000"); - return new Response(object.body, { - headers - }); - } catch (error) { - console.error("Error serving file:", error); - return c.notFound(); - } -}); -adminMediaRoutes.put("/:id", async (c) => { - try { - const user = c.get("user"); - const fileId = c.req.param("id"); - const formData = await c.req.formData(); - const stmt = c.env.DB.prepare("SELECT * FROM media WHERE id = ? AND deleted_at IS NULL"); - const fileRecord = await stmt.bind(fileId).first(); - if (!fileRecord) { - return c.html(html.html` -
- File not found -
- `); - } - if (fileRecord.uploaded_by !== user.userId && user.role !== "admin") { - return c.html(html.html` -
- Permission denied -
- `); - } - const alt = formData.get("alt") || null; - const caption = formData.get("caption") || null; - const tagsString = formData.get("tags") || ""; - const tags = tagsString ? tagsString.split(",").map((tag) => tag.trim()).filter((tag) => tag) : []; - const updateStmt = c.env.DB.prepare(` - UPDATE media - SET alt = ?, caption = ?, tags = ?, updated_at = ? - WHERE id = ? - `); - await updateStmt.bind( - alt, - caption, - JSON.stringify(tags), - Math.floor(Date.now() / 1e3), - fileId - ).run(); - return c.html(html.html` -
- File updated successfully -
- - `); - } catch (error) { - console.error("Update error:", error); - return c.html(html.html` -
- Update failed: ${error instanceof Error ? error.message : "Unknown error"} -
- `); - } -}); -adminMediaRoutes.delete("/cleanup", chunkDVQA5II3_cjs.requireRole("admin"), async (c) => { - try { - const db = c.env.DB; - const allMediaStmt = db.prepare("SELECT id, r2_key, filename FROM media WHERE deleted_at IS NULL"); - const { results: allMedia } = await allMediaStmt.all(); - const contentStmt = db.prepare("SELECT data FROM content"); - const { results: contentRecords } = await contentStmt.all(); - const referencedUrls = /* @__PURE__ */ new Set(); - for (const record of contentRecords || []) { - if (record.data) { - const dataStr = typeof record.data === "string" ? record.data : JSON.stringify(record.data); - const urlMatches = dataStr.matchAll(/\/files\/([^\s"',]+)/g); - for (const match of urlMatches) { - referencedUrls.add(match[1]); - } - } - } - const mediaRows = allMedia || []; - const unusedFiles = mediaRows.filter((file) => !referencedUrls.has(file.r2_key)); - if (unusedFiles.length === 0) { - return c.html(html.html` -
- No unused media files found. All files are referenced in content. -
- - `); - } - let deletedCount = 0; - const errors = []; - for (const file of unusedFiles) { - try { - await c.env.MEDIA_BUCKET.delete(file.r2_key); - const deleteStmt = db.prepare("UPDATE media SET deleted_at = ? WHERE id = ?"); - await deleteStmt.bind(Math.floor(Date.now() / 1e3), file.id).run(); - deletedCount++; - } catch (error) { - console.error(`Failed to delete ${file.filename}:`, error); - errors.push({ - filename: file.filename, - error: error instanceof Error ? error.message : "Unknown error" - }); - } - } - return c.html(html.html` -
- Successfully cleaned up ${deletedCount} unused media file${deletedCount !== 1 ? "s" : ""}. - ${errors.length > 0 ? html.html` -
Failed to delete ${errors.length} file${errors.length !== 1 ? "s" : ""}. - ` : ""} -
- - ${errors.length > 0 ? html.html` -
-

Cleanup errors:

-
    - ${errors.map((error) => html.html` -
  • ${error.filename}: ${error.error}
  • - `)} -
-
- ` : ""} - - - `); - } catch (error) { - console.error("Cleanup error:", error); - return c.html(html.html` -
- Cleanup failed: ${error instanceof Error ? error.message : "Unknown error"} -
- `); - } -}); -adminMediaRoutes.delete("/:id", async (c) => { - try { - const user = c.get("user"); - const fileId = c.req.param("id"); - const stmt = c.env.DB.prepare("SELECT * FROM media WHERE id = ? AND deleted_at IS NULL"); - const fileRecord = await stmt.bind(fileId).first(); - if (!fileRecord) { - return c.html(html.html` -
- File not found -
- `); - } - if (fileRecord.uploaded_by !== user.userId && user.role !== "admin") { - return c.html(html.html` -
- Permission denied -
- `); - } - try { - await c.env.MEDIA_BUCKET.delete(fileRecord.r2_key); - } catch (error) { - console.warn("Failed to delete from R2:", error); - } - const deleteStmt = c.env.DB.prepare("UPDATE media SET deleted_at = ? WHERE id = ?"); - await deleteStmt.bind(Math.floor(Date.now() / 1e3), fileId).run(); - return c.html(html.html` - - `); - } catch (error) { - console.error("Delete error:", error); - return c.html(html.html` -
- Delete failed: ${error instanceof Error ? error.message : "Unknown error"} -
- `); - } -}); -async function getImageDimensions2(arrayBuffer) { - const uint8Array = new Uint8Array(arrayBuffer); - if (uint8Array[0] === 255 && uint8Array[1] === 216) { - return getJPEGDimensions2(uint8Array); - } - if (uint8Array[0] === 137 && uint8Array[1] === 80 && uint8Array[2] === 78 && uint8Array[3] === 71) { - return getPNGDimensions2(uint8Array); - } - return { width: 0, height: 0 }; -} -function getJPEGDimensions2(uint8Array) { - let i = 2; - while (i < uint8Array.length - 8) { - if (uint8Array[i] === 255 && uint8Array[i + 1] === 192) { - return { - height: uint8Array[i + 5] << 8 | uint8Array[i + 6], - width: uint8Array[i + 7] << 8 | uint8Array[i + 8] - }; - } - const segmentLength = uint8Array[i + 2] << 8 | uint8Array[i + 3]; - i += 2 + segmentLength; - } - return { width: 0, height: 0 }; -} -function getPNGDimensions2(uint8Array) { - if (uint8Array.length < 24) { - return { width: 0, height: 0 }; - } - return { - width: uint8Array[16] << 24 | uint8Array[17] << 16 | uint8Array[18] << 8 | uint8Array[19], - height: uint8Array[20] << 24 | uint8Array[21] << 16 | uint8Array[22] << 8 | uint8Array[23] - }; -} -function generateMediaItemHTML(file) { - const isImage = file.isImage; - const isVideo = file.isVideo; - return ` -
-
- ${isImage ? ` - ${file.alt || file.filename} - ` : isVideo ? ` - - ` : ` -
-
- - - - ${file.filename.split(".").pop()?.toUpperCase()} -
-
- `} - -
-
- - -
-
-
- -
-

- ${file.original_name} -

-
- ${file.fileSize} - ${file.uploadedAt} -
- ${file.tags.length > 0 ? ` -
- ${file.tags.slice(0, 2).map((tag) => ` - - ${tag} - - `).join("")} - ${file.tags.length > 2 ? `+${file.tags.length - 2}` : ""} -
- ` : ""} -
-
- `; -} -function formatFileSize(bytes) { - if (bytes === 0) return "0 Bytes"; - const k = 1024; - const sizes = ["Bytes", "KB", "MB", "GB"]; - const i = Math.floor(Math.log(bytes) / Math.log(k)); - return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]; -} - -// src/templates/pages/admin-plugins-list.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderPluginsListPage(data) { - const categories = [ - { value: "content", label: "Content Management" }, - { value: "media", label: "Media" }, - { value: "editor", label: "Editors" }, - { value: "seo", label: "SEO & Analytics" }, - { value: "security", label: "Security" }, - { value: "utilities", label: "Utilities" }, - { value: "system", label: "System" }, - { value: "development", label: "Development" }, - { value: "demo", label: "Demo" } - ]; - const statuses = [ - { value: "active", label: "Active" }, - { value: "inactive", label: "Inactive" }, - { value: "uninstalled", label: "Available to Install" }, - { value: "error", label: "Error" } - ]; - const categoryCounts = {}; - categories.forEach((cat) => { - categoryCounts[cat.value] = data.plugins.filter((p) => p.category === cat.value).length; - }); - categories.sort((a, b) => (categoryCounts[b.value] || 0) - (categoryCounts[a.value] || 0)); - const statusCounts = {}; - statuses.forEach((status) => { - statusCounts[status.value] = data.plugins.filter((p) => p.status === status.value).length; - }); - statuses.sort((a, b) => (statusCounts[b.value] || 0) - (statusCounts[a.value] || 0)); - const pageContent = ` -
- -
-
-

Plugins

-

Manage and extend functionality with plugins

-
-
- - -
-
-
- - - -
-
-

- Experimental Feature -

-
-

- Plugin management is currently under active development. While functional, some features may change or have limitations. - Please report any issues you encounter on our Discord community. -

-
-
-
-
- -
- - - - -
- -
-
-
Total
-
${data.stats?.total || 0}
-
-
-
Active
-
${data.stats?.active || 0}
-
-
-
Available
-
${data.stats?.uninstalled || 0}
-
-
-
Errors
-
${data.stats?.errors || 0}
-
-
- - -
-
-
- - - -
- -
- -
- - - -
-
- - -
- ${data.plugins.map((plugin) => renderPluginCard(plugin)).join("")} -
-
-
-
- - - - - ${renderConfirmationDialog2({ - id: "uninstall-plugin-confirm", - title: "Uninstall Plugin", - message: "Are you sure you want to uninstall this plugin? This action cannot be undone.", - confirmText: "Uninstall", - cancelText: "Cancel", - iconColor: "red", - confirmClass: "bg-red-500 hover:bg-red-400", - onConfirm: "performUninstallPlugin()" - })} - - ${getConfirmationDialogScript2()} - `; - const layoutData = { - title: "Plugins", - pageTitle: "Plugin Management", - currentPath: "/admin/plugins", - user: data.user, - version: data.version, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} -function renderPluginCard(plugin) { - const statusColors = { - active: "bg-emerald-50 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 ring-emerald-600/20", - inactive: "bg-zinc-50 dark:bg-zinc-500/10 text-zinc-700 dark:text-zinc-400 ring-zinc-600/20", - error: "bg-red-50 dark:bg-red-500/10 text-red-700 dark:text-red-400 ring-red-600/20", - uninstalled: "bg-zinc-50 dark:bg-zinc-500/10 text-zinc-600 dark:text-zinc-500 ring-zinc-600/20" - }; - const statusIcons = { - active: '
', - inactive: '
', - error: '
', - uninstalled: '
' - }; - const criticalCorePlugins = ["core-auth", "core-media"]; - const canToggle = !criticalCorePlugins.includes(plugin.id); - let actionButton = ""; - if (plugin.status === "uninstalled") { - actionButton = ``; - } else { - const isActive = plugin.status === "active"; - const action = isActive ? "deactivate" : "activate"; - const bgClass = isActive ? "bg-emerald-600" : "bg-zinc-200 dark:bg-zinc-700"; - const translateClass = isActive ? "translate-x-5" : "translate-x-0"; - if (canToggle) { - actionButton = ` - - `; - } else { - actionButton = ` -
- -
- `; - } - } - return ` -
-
-
-
- ${plugin.icon || getDefaultPluginIcon(plugin.category)} -
-
-
-

${plugin.displayName}

- - ${statusIcons[plugin.status]}${plugin.status.charAt(0).toUpperCase() + plugin.status.slice(1)} - -
-

v${plugin.version} \u2022 ${plugin.author}

-
-
- -
- ${!plugin.isCore && plugin.status !== "uninstalled" ? ` - - ` : ""} -
-
- -

${plugin.description}

- -
- - ${plugin.category} - - ${plugin.isCore ? 'Core' : ""} - - ${plugin.dependencies && plugin.dependencies.map((dep) => ` - - ${dep} - - `).join("") || ""} -
- -
-
- ${actionButton} -
-
-
- `; -} -function getDefaultPluginIcon(category) { - const iconColor = "text-zinc-600 dark:text-zinc-400"; - const icons = { - "content": ` - - - - `, - "media": ` - - - - `, - "seo": ` - - - - `, - "analytics": ` - - - - `, - "ecommerce": ` - - - - `, - "email": ` - - - - `, - "workflow": ` - - - - `, - "security": ` - - - - `, - "social": ` - - - - `, - "utility": ` - - - - - ` - }; - const iconKey = category.toLowerCase(); - return icons[iconKey] || icons["utility"] || ""; -} - -// src/templates/components/auth-settings-form.template.ts -function renderAuthSettingsForm(settings) { - const fields = settings.requiredFields; - const validation = settings.validation; - const registration = settings.registration; - return ` -
- -
-

Registration Fields

-

Configure which fields are required during user registration and their minimum lengths.

- -
- ${Object.entries(fields).map(([fieldName, config]) => ` -
-
-
-

${config.label}

-

Field type: ${config.type}

-
- -
- -
-
- - -
-
- - -
-
-
- `).join("")} -
-
- - -
-

Password Requirements

-

Additional password complexity requirements.

- -
-
-
- -

Password must contain at least one uppercase letter (A-Z)

-
- -
- -
-
- -

Password must contain at least one lowercase letter (a-z)

-
- -
- -
-
- -

Password must contain at least one number (0-9)

-
- -
- -
-
- -

Password must contain at least one special character (!@#$%^&*)

-
- -
-
-
- - -
-

Registration Settings

-

General registration behavior.

- -
-
-
- -

Enable or disable public user registration

-
- -
- -
-
- -

Users must verify their email before accessing the system

-
- -
- -
- - -

Role assigned to new users upon registration

-
-
-
- - -
-

Validation Settings

-

Additional validation rules.

- -
-
-
- -

Validate that email addresses are in correct format

-
- -
- -
-
- -

Ensure usernames are unique across all users

-
- -
-
-
-
- `; -} - -// src/templates/pages/admin-plugin-settings.template.ts -function escapeHtmlAttr(value) { - return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">"); -} -function renderPluginSettingsPage(data) { - const { plugin, activity = [], user } = data; - const pageContent = ` -
- -
-
-

Plugin Settings

-

- ${plugin.description} -

-
- -
- - -
-
-
-
- ${plugin.icon || plugin.displayName.charAt(0).toUpperCase()} -
-
-

${plugin.displayName}

-
- v${plugin.version} - by ${plugin.author} - ${plugin.category} - ${plugin.downloadCount ? `${plugin.downloadCount.toLocaleString()} downloads` : ""} - ${plugin.rating ? `\u2605 ${plugin.rating}` : ""} -
-
-
- -
- ${renderStatusBadge(plugin.status)} - ${renderToggleButton(plugin)} -
-
-
- - -
- -
- - -
- -
- ${renderSettingsTab(plugin)} -
- - - - - - -
-
- - - `; - const layoutData = { - title: `${plugin.displayName} Settings`, - pageTitle: `${plugin.displayName} Settings`, - currentPath: `/admin/plugins/${plugin.id}`, - user, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayout(layoutData); -} -function renderStatusBadge(status) { - const statusColors = { - active: "bg-green-900/50 text-green-300 border-green-600/30", - inactive: "bg-gray-800/50 text-gray-400 border-gray-600/30", - error: "bg-red-900/50 text-red-300 border-red-600/30" - }; - const statusIcons = { - active: '
', - inactive: '
', - error: '
' - }; - return ` - - ${statusIcons[status] || statusIcons.inactive}${status.charAt(0).toUpperCase() + status.slice(1)} - - `; -} -function renderToggleButton(plugin) { - if (plugin.isCore) { - return 'Core Plugin'; - } - return plugin.status === "active" ? `` : ``; -} -function renderSettingsTab(plugin) { - const settings = plugin.settings || {}; - const pluginId = plugin.id || plugin.name; - const customRenderer = pluginSettingsComponents[pluginId]; - if (customRenderer) { - return ` -
- ${customRenderer(plugin, settings)} - -
- -
-
- `; - } - const isSeedDataPlugin = plugin.id === "seed-data" || plugin.name === "seed-data"; - const isAuthPlugin = plugin.id === "core-auth" || plugin.name === "core-auth"; - const isTurnstilePlugin = plugin.id === "turnstile" || plugin.name === "turnstile"; - return ` - ${isSeedDataPlugin ? ` -
-
-
-

Seed Data Generator

-

Generate realistic example data for testing and development.

-
- - - - - Open Seed Data Tool - -
-
- ` : ""} - -
- ${isAuthPlugin ? ` -

Authentication Settings

-

Configure user registration fields and validation rules.

- ` : isTurnstilePlugin ? ` -

Cloudflare Turnstile Settings

-

Configure CAPTCHA-free bot protection for your forms.

- ` : ` -

Plugin Settings

- `} - -
- ${isAuthPlugin && Object.keys(settings).length > 0 ? renderAuthSettingsForm(settings) : isTurnstilePlugin && Object.keys(settings).length > 0 ? renderTurnstileSettingsForm(settings) : Object.keys(settings).length > 0 ? renderSettingsFields(settings) : renderNoSettings(plugin)} - - ${Object.keys(settings).length > 0 ? ` -
- -
- ` : ""} -
-
- `; -} -function renderSettingsFields(settings) { - return Object.entries(settings).map(([key, value]) => { - const fieldId = `setting_${key}`; - const displayName = key.replace(/([A-Z])/g, " $1").replace(/^./, (str) => str.toUpperCase()); - if (typeof value === "boolean") { - return ` -
-
- -

Enable or disable this feature

-
- -
- `; - } else if (typeof value === "number") { - return ` -
- - -
- `; - } else { - return ` -
- - -
- `; - } - }).join(""); -} -function renderTurnstileSettingsForm(settings) { - const inputClass = "backdrop-blur-sm bg-white/10 border border-white/20 rounded-lg px-3 py-2 text-white placeholder-gray-300 focus:border-blue-400 focus:outline-none transition-colors w-full"; - const selectClass = "backdrop-blur-sm bg-zinc-800 border border-white/20 rounded-lg px-3 py-2 text-white focus:border-blue-400 focus:outline-none transition-colors w-full [&>option]:bg-zinc-800 [&>option]:text-white"; - return ` - -
-
- -

Enable or disable Turnstile verification globally

-
- -
- - -
- - -

Your Cloudflare Turnstile site key (public)

-
- - -
- - -

Your Cloudflare Turnstile secret key (private)

-
- - -
- - -

Visual appearance of the Turnstile widget

-
- - -
- - -

Size of the Turnstile challenge widget

-
- - -
- - -

Managed: Shows challenge only when needed. Non-Interactive: Always shows but doesn't require interaction. Invisible: Runs in background without UI.

-
- - -
- - -

Controls when Turnstile verification occurs. Always: Verifies immediately (pre-clearance). Execute: Verifies on form submit. Interaction Only: Only after user interaction.

-
- `; -} -function renderNoSettings(plugin) { - if (plugin.id === "seed-data" || plugin.name === "seed-data") { - return ` -
- - - -

Seed Data Generator

-

Generate realistic example data for testing and development.

- - - - - Generate Seed Data - -
- `; - } - return ` -
- - - - -

No Settings Available

-

This plugin doesn't have any configurable settings.

-
- `; -} -function renderActivityTab(activity) { - return ` -
-

Activity Log

- - ${activity.length > 0 ? ` -
- ${activity.map((item) => ` -
-
-
-
- ${item.action} - ${formatTimestamp(item.timestamp)} -
-

${item.message}

- ${item.user ? `

by ${item.user}

` : ""} -
-
- `).join("")} -
- ` : ` -
- - - -

No Activity

-

No recent activity for this plugin.

-
- `} -
- `; -} -function renderInformationTab(plugin) { - return ` -
- -
-

Plugin Details

-
-
- Name: - ${plugin.displayName} -
-
- Version: - ${plugin.version} -
-
- Author: - ${plugin.author} -
-
- Category: - ${plugin.category} -
-
- Status: - ${plugin.status} -
-
- Last Updated: - ${plugin.lastUpdated} -
-
-
- - -
-

Dependencies & Permissions

- - ${plugin.dependencies && plugin.dependencies.length > 0 ? ` -
-

Dependencies:

-
- ${plugin.dependencies.map((dep) => ` -
${dep}
- `).join("")} -
-
- ` : ""} - - ${plugin.permissions && plugin.permissions.length > 0 ? ` -
-

Permissions:

-
- ${plugin.permissions.map((perm) => ` -
${perm}
- `).join("")} -
-
- ` : ""} - - ${(!plugin.dependencies || plugin.dependencies.length === 0) && (!plugin.permissions || plugin.permissions.length === 0) ? ` -

No dependencies or special permissions required.

- ` : ""} -
-
- `; -} -function formatTimestamp(timestamp) { - const date = new Date(timestamp * 1e3); - return date.toLocaleString(); -} -var pluginSettingsComponents = { - "otp-login": renderOTPLoginSettingsContent, - "email": renderEmailSettingsContent -}; -function renderOTPLoginSettingsContent(plugin, settings) { - const siteName = settings.siteName || "SonicJS"; - const emailConfigured = settings._emailConfigured || false; - const codeLength = settings.codeLength || 6; - const codeExpiryMinutes = settings.codeExpiryMinutes || 10; - const maxAttempts = settings.maxAttempts || 3; - const rateLimitPerHour = settings.rateLimitPerHour || 5; - const allowNewUserRegistration = settings.allowNewUserRegistration || false; - return ` -
- -
-

- \u{1F4E7} Test OTP Email -

- - ${!emailConfigured ? ` -
-

- \u26A0\uFE0F Email not configured. - Configure the Email plugin - to send real emails. Dev mode will show codes in the response. -

-
- ` : ` -
-

- \u2705 Email configured. Test emails will be sent via Resend. -

-
- `} - -
-
- - -
- - -
- - - - - -
- - -
-

Code Settings

- -
-
-
- - -

Number of digits (4-8)

-
- -
- - -

How long codes remain valid

-
- -
- - -

Max verification attempts

-
- -
- - -

Max requests per email per hour

-
-
- -
- - -
-
-
- - -
-

- \u{1F441}\uFE0F Email Preview -

-

- This is how the OTP email will appear to users. The site name "${siteName}" is configured in - General Settings. -

- -
-
-

Your Login Code

-

Enter this code to sign in to ${siteName}

-
- -
-
-
- 123456 -
-
- -
-

- \u26A0\uFE0F This code expires in ${codeExpiryMinutes} minutes -

-
- -
-

- \u{1F512} Security Notice -

-

- Never share this code with anyone. ${siteName} will never ask you for this code via phone, email, or social media. -

-
-
-
-
- - -
-

\u{1F522} Features

-
    -
  • \u2713 Passwordless authentication
  • -
  • \u2713 Secure random code generation
  • -
  • \u2713 Rate limiting protection
  • -
  • \u2713 Brute force prevention
  • -
  • \u2713 Mobile-friendly UX
  • -
-
- - - -
- - - `; -} -function renderEmailSettingsContent(plugin, settings) { - const apiKey = settings.apiKey || ""; - const fromEmail = settings.fromEmail || ""; - const fromName = settings.fromName || ""; - const replyTo = settings.replyTo || ""; - const logoUrl = settings.logoUrl || ""; - return ` -
- -
-

Resend Configuration

- -
- -
- - -

- Get your API key from resend.com/api-keys -

-
- - -
- - -

Must be a verified domain in Resend

-
- - -
- - -
- - -
- - -
- - -
- - -

Logo to display in email templates

-
-
-
- - -
-

Send Test Email

-
- - -
- -
- - -
-

\u{1F4E7} Email Templates Included

-
    -
  • \u2713 Registration confirmation
  • -
  • \u2713 Email verification
  • -
  • \u2713 Password reset
  • -
  • \u2713 One-time code (2FA)
  • -
-

- Templates are code-based and can be customized by editing the plugin files. -

-
-
- - - `; -} - -// src/routes/admin-plugins.ts -var adminPluginRoutes = new hono.Hono(); -adminPluginRoutes.use("*", chunkDVQA5II3_cjs.requireAuth()); -var AVAILABLE_PLUGINS = [ - { - id: "third-party-faq", - name: "faq-plugin", - display_name: "FAQ System", - description: "Frequently Asked Questions management system with categories, search, and custom styling", - version: "2.0.0", - author: "Community Developer", - category: "content", - icon: "\u2753", - permissions: ["manage:faqs"], - dependencies: [], - is_core: false - }, - { - id: "demo-login-prefill", - name: "demo-login-plugin", - display_name: "Demo Login Prefill", - description: "Prefills login form with demo credentials (admin@sonicjs.com/sonicjs!) for easy site demonstration", - version: "1.0.0-beta.1", - author: "SonicJS", - category: "demo", - icon: "\u{1F3AF}", - permissions: [], - dependencies: [], - is_core: false - }, - { - id: "database-tools", - name: "database-tools", - display_name: "Database Tools", - description: "Database management tools including truncate, backup, and validation", - version: "1.0.0-beta.1", - author: "SonicJS Team", - category: "system", - icon: "\u{1F5C4}\uFE0F", - permissions: ["manage:database", "admin"], - dependencies: [], - is_core: false - }, - { - id: "seed-data", - name: "seed-data", - display_name: "Seed Data", - description: "Generate realistic example users and content for testing and development", - version: "1.0.0-beta.1", - author: "SonicJS Team", - category: "development", - icon: "\u{1F331}", - permissions: ["admin"], - dependencies: [], - is_core: false - }, - { - id: "quill-editor", - name: "quill-editor", - display_name: "Quill Rich Text Editor", - description: "Quill WYSIWYG editor integration for rich text editing. Lightweight, modern editor with customizable toolbars and dark mode support.", - version: "1.0.0", - author: "SonicJS Team", - category: "editor", - icon: "\u270D\uFE0F", - permissions: [], - dependencies: [], - is_core: true - }, - { - id: "tinymce-plugin", - name: "tinymce-plugin", - display_name: "TinyMCE Rich Text Editor", - description: "Powerful WYSIWYG rich text editor for content creation. Provides a full-featured editor with formatting, media embedding, and customizable toolbars for richtext fields.", - version: "1.0.0", - author: "SonicJS Team", - category: "editor", - icon: "\u{1F4DD}", - permissions: [], - dependencies: [], - is_core: false - }, - { - id: "easy-mdx", - name: "easy-mdx", - display_name: "EasyMDE Markdown Editor", - description: "Lightweight markdown editor with live preview. Provides a simple and efficient editor with markdown support for richtext fields.", - version: "1.0.0", - author: "SonicJS Team", - category: "editor", - icon: "\u{1F4DD}", - permissions: [], - dependencies: [], - is_core: false - }, - { - id: "turnstile", - name: "turnstile-plugin", - display_name: "Cloudflare Turnstile", - description: "CAPTCHA-free bot protection for forms using Cloudflare Turnstile. Provides seamless spam prevention with configurable modes, themes, and pre-clearance options.", - version: "1.0.0", - author: "SonicJS Team", - category: "security", - icon: "\u{1F6E1}\uFE0F", - permissions: [], - dependencies: [], - is_core: true - }, - { - id: "ai-search", - name: "ai-search-plugin", - display_name: "AI Search", - description: "Advanced search with Cloudflare AI Search. Full-text search, semantic search, and advanced filtering across all content collections.", - version: "1.0.0", - author: "SonicJS Team", - category: "search", - icon: "\u{1F50D}", - permissions: [], - dependencies: [], - is_core: true - } -]; -adminPluginRoutes.get("/", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - if (user?.role !== "admin") { - return c.text("Access denied", 403); - } - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - let installedPlugins = []; - let stats = { total: 0, active: 0, inactive: 0, errors: 0, uninstalled: 0 }; - try { - installedPlugins = await pluginService.getAllPlugins(); - stats = await pluginService.getPluginStats(); - } catch (error) { - console.error("Error loading plugins:", error); - } - const installedPluginIds = new Set(installedPlugins.map((p) => p.id)); - const uninstalledPlugins = AVAILABLE_PLUGINS.filter((p) => !installedPluginIds.has(p.id)); - const templatePlugins = installedPlugins.map((p) => ({ - id: p.id, - name: p.name, - displayName: p.display_name, - description: p.description, - version: p.version, - author: p.author, - status: p.status, - category: p.category, - icon: p.icon, - downloadCount: p.download_count, - rating: p.rating, - lastUpdated: formatLastUpdated(p.last_updated), - dependencies: p.dependencies, - permissions: p.permissions, - isCore: p.is_core - })); - const uninstalledTemplatePlugins = uninstalledPlugins.map((p) => ({ - id: p.id, - name: p.name, - displayName: p.display_name, - description: p.description, - version: p.version, - author: p.author, - status: "uninstalled", - category: p.category, - icon: p.icon, - downloadCount: 0, - rating: 0, - lastUpdated: "Not installed", - dependencies: p.dependencies, - permissions: p.permissions, - isCore: p.is_core - })); - const allPlugins = [...templatePlugins, ...uninstalledTemplatePlugins]; - stats.uninstalled = uninstalledPlugins.length; - stats.total = installedPlugins.length + uninstalledPlugins.length; - const pageData = { - plugins: allPlugins, - stats, - user: { - name: user?.email || "User", - email: user?.email || "", - role: user?.role || "user" - }, - version: c.get("appVersion") - }; - return c.html(renderPluginsListPage(pageData)); - } catch (error) { - console.error("Error loading plugins page:", error); - return c.text("Internal server error", 500); - } -}); -adminPluginRoutes.get("/:id", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const pluginId = c.req.param("id"); - const pluginsWithCustomPages = ["ai-search"]; - if (pluginsWithCustomPages.includes(pluginId)) { - return c.text("", 404); - } - if (user?.role !== "admin") { - return c.redirect("/admin/plugins"); - } - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - const plugin = await pluginService.getPlugin(pluginId); - if (!plugin) { - return c.text("Plugin not found", 404); - } - const activity = await pluginService.getPluginActivity(pluginId, 20); - let enrichedSettings = plugin.settings || {}; - if (pluginId === "otp-login") { - const generalSettings = await db.prepare(` - SELECT value FROM settings WHERE key = 'general' - `).first(); - let siteName = "SonicJS"; - if (generalSettings?.value) { - try { - const parsed = JSON.parse(generalSettings.value); - siteName = parsed.siteName || "SonicJS"; - } catch (e) { - } - } - const emailPlugin = await db.prepare(` - SELECT settings FROM plugins WHERE id = 'email' - `).first(); - let emailConfigured = false; - if (emailPlugin?.settings) { - try { - const emailSettings = JSON.parse(emailPlugin.settings); - emailConfigured = !!(emailSettings.apiKey && emailSettings.fromEmail && emailSettings.fromName); - } catch (e) { - } - } - enrichedSettings = { - ...enrichedSettings, - siteName, - _emailConfigured: emailConfigured - }; - } - const templatePlugin = { - id: plugin.id, - name: plugin.name, - displayName: plugin.display_name, - description: plugin.description, - version: plugin.version, - author: plugin.author, - status: plugin.status, - category: plugin.category, - icon: plugin.icon, - downloadCount: plugin.download_count, - rating: plugin.rating, - lastUpdated: formatLastUpdated(plugin.last_updated), - dependencies: plugin.dependencies, - permissions: plugin.permissions, - isCore: plugin.is_core, - settings: enrichedSettings - }; - const templateActivity = (activity || []).map((item) => ({ - id: item.id, - action: item.action, - message: item.message, - timestamp: item.timestamp, - user: item.user_email - })); - const pageData = { - plugin: templatePlugin, - activity: templateActivity, - user: { - name: user?.email || "User", - email: user?.email || "", - role: user?.role || "user" - } - }; - return c.html(renderPluginSettingsPage(pageData)); - } catch (error) { - console.error("Error getting plugin settings page:", error); - return c.text("Internal server error", 500); - } -}); -adminPluginRoutes.post("/:id/activate", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const pluginId = c.req.param("id"); - if (user?.role !== "admin") { - return c.json({ error: "Access denied" }, 403); - } - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - await pluginService.activatePlugin(pluginId); - return c.json({ success: true }); - } catch (error) { - console.error("Error activating plugin:", error); - const message = error instanceof Error ? error.message : "Failed to activate plugin"; - return c.json({ error: message }, 400); - } -}); -adminPluginRoutes.post("/:id/deactivate", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const pluginId = c.req.param("id"); - if (user?.role !== "admin") { - return c.json({ error: "Access denied" }, 403); - } - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - await pluginService.deactivatePlugin(pluginId); - return c.json({ success: true }); - } catch (error) { - console.error("Error deactivating plugin:", error); - const message = error instanceof Error ? error.message : "Failed to deactivate plugin"; - return c.json({ error: message }, 400); - } -}); -adminPluginRoutes.post("/install", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - if (user?.role !== "admin") { - return c.json({ error: "Access denied" }, 403); - } - const body = await c.req.json(); - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - if (body.name === "faq-plugin") { - const faqPlugin = await pluginService.installPlugin({ - id: "third-party-faq", - name: "faq-plugin", - display_name: "FAQ System", - description: "Frequently Asked Questions management system with categories, search, and custom styling", - version: "2.0.0", - author: "Community Developer", - category: "content", - icon: "\u2753", - permissions: ["manage:faqs"], - dependencies: [], - settings: { - enableSearch: true, - enableCategories: true, - questionsPerPage: 10 - } - }); - return c.json({ success: true, plugin: faqPlugin }); - } - if (body.name === "demo-login-plugin") { - const demoPlugin = await pluginService.installPlugin({ - id: "demo-login-prefill", - name: "demo-login-plugin", - display_name: "Demo Login Prefill", - description: "Prefills login form with demo credentials (admin@sonicjs.com/sonicjs!) for easy site demonstration", - version: "1.0.0-beta.1", - author: "SonicJS", - category: "demo", - icon: "\u{1F3AF}", - permissions: [], - dependencies: [], - settings: { - enableNotice: true, - demoEmail: "admin@sonicjs.com", - demoPassword: "sonicjs!" - } - }); - return c.json({ success: true, plugin: demoPlugin }); - } - if (body.name === "core-auth") { - const authPlugin = await pluginService.installPlugin({ - id: "core-auth", - name: "core-auth", - display_name: "Authentication System", - description: "Core authentication and user management system", - version: "1.0.0-beta.1", - author: "SonicJS Team", - category: "security", - icon: "\u{1F510}", - permissions: ["manage:users", "manage:roles", "manage:permissions"], - dependencies: [], - is_core: true, - settings: {} - }); - return c.json({ success: true, plugin: authPlugin }); - } - if (body.name === "core-media") { - const mediaPlugin = await pluginService.installPlugin({ - id: "core-media", - name: "core-media", - display_name: "Media Manager", - description: "Core media upload and management system", - version: "1.0.0-beta.1", - author: "SonicJS Team", - category: "media", - icon: "\u{1F4F8}", - permissions: ["manage:media", "upload:files"], - dependencies: [], - is_core: true, - settings: {} - }); - return c.json({ success: true, plugin: mediaPlugin }); - } - if (body.name === "core-workflow") { - const workflowPlugin = await pluginService.installPlugin({ - id: "core-workflow", - name: "core-workflow", - display_name: "Workflow Engine", - description: "Content workflow and approval system", - version: "1.0.0-beta.1", - author: "SonicJS Team", - category: "content", - icon: "\u{1F504}", - permissions: ["manage:workflows", "approve:content"], - dependencies: [], - is_core: true, - settings: {} - }); - return c.json({ success: true, plugin: workflowPlugin }); - } - if (body.name === "database-tools") { - const databaseToolsPlugin = await pluginService.installPlugin({ - id: "database-tools", - name: "database-tools", - display_name: "Database Tools", - description: "Database management tools including truncate, backup, and validation", - version: "1.0.0-beta.1", - author: "SonicJS Team", - category: "system", - icon: "\u{1F5C4}\uFE0F", - permissions: ["manage:database", "admin"], - dependencies: [], - is_core: false, - settings: { - enableTruncate: true, - enableBackup: true, - enableValidation: true, - requireConfirmation: true - } - }); - return c.json({ success: true, plugin: databaseToolsPlugin }); - } - if (body.name === "seed-data") { - const seedDataPlugin = await pluginService.installPlugin({ - id: "seed-data", - name: "seed-data", - display_name: "Seed Data", - description: "Generate realistic example users and content for testing and development", - version: "1.0.0-beta.1", - author: "SonicJS Team", - category: "development", - icon: "\u{1F331}", - permissions: ["admin"], - dependencies: [], - is_core: false, - settings: { - userCount: 20, - contentCount: 200, - defaultPassword: "password123" - } - }); - return c.json({ success: true, plugin: seedDataPlugin }); - } - if (body.name === "quill-editor") { - const quillPlugin = await pluginService.installPlugin({ - id: "quill-editor", - name: "quill-editor", - display_name: "Quill Rich Text Editor", - description: "Quill WYSIWYG editor integration for rich text editing. Lightweight, modern editor with customizable toolbars and dark mode support.", - version: "1.0.0", - author: "SonicJS Team", - category: "editor", - icon: "\u270D\uFE0F", - permissions: [], - dependencies: [], - is_core: true, - settings: { - version: "2.0.2", - defaultHeight: 300, - defaultToolbar: "full", - theme: "snow" - } - }); - return c.json({ success: true, plugin: quillPlugin }); - } - if (body.name === "tinymce-plugin") { - const tinymcePlugin2 = await pluginService.installPlugin({ - id: "tinymce-plugin", - name: "tinymce-plugin", - display_name: "TinyMCE Rich Text Editor", - description: "Powerful WYSIWYG rich text editor for content creation. Provides a full-featured editor with formatting, media embedding, and customizable toolbars for richtext fields.", - version: "1.0.0", - author: "SonicJS Team", - category: "editor", - icon: "\u{1F4DD}", - permissions: [], - dependencies: [], - is_core: false, - settings: { - apiKey: "no-api-key", - defaultHeight: 300, - defaultToolbar: "full", - skin: "oxide-dark" - } - }); - return c.json({ success: true, plugin: tinymcePlugin2 }); - } - if (body.name === "easy-mdx") { - const easyMdxPlugin2 = await pluginService.installPlugin({ - id: "easy-mdx", - name: "easy-mdx", - display_name: "EasyMDE Markdown Editor", - description: "Lightweight markdown editor with live preview. Provides a simple and efficient editor with markdown support for richtext fields.", - version: "1.0.0", - author: "SonicJS Team", - category: "editor", - icon: "\u{1F4DD}", - permissions: [], - dependencies: [], - is_core: false, - settings: { - defaultHeight: 400, - theme: "dark", - toolbar: "full", - placeholder: "Start writing your content..." - } - }); - return c.json({ success: true, plugin: easyMdxPlugin2 }); - } - if (body.name === "ai-search-plugin" || body.name === "ai-search") { - const defaultSettings = { - enabled: true, - ai_mode_enabled: true, - selected_collections: [], - dismissed_collections: [], - autocomplete_enabled: true, - cache_duration: 1, - results_limit: 20, - index_media: false - }; - const aiSearchPlugin = await pluginService.installPlugin({ - id: "ai-search", - name: "ai-search-plugin", - display_name: "AI Search", - description: "Advanced search with Cloudflare AI Search. Full-text search, semantic search, and advanced filtering across all content collections.", - version: "1.0.0", - author: "SonicJS Team", - category: "search", - icon: "\u{1F50D}", - permissions: [], - dependencies: [], - is_core: true, - settings: defaultSettings - }); - return c.json({ success: true, plugin: aiSearchPlugin }); - } - if (body.name === "turnstile-plugin") { - const turnstilePlugin = await pluginService.installPlugin({ - id: "turnstile", - name: "turnstile-plugin", - display_name: "Cloudflare Turnstile", - description: "CAPTCHA-free bot protection for forms using Cloudflare Turnstile. Provides seamless spam prevention with configurable modes, themes, and pre-clearance options.", - version: "1.0.0", - author: "SonicJS Team", - category: "security", - icon: "\u{1F6E1}\uFE0F", - permissions: [], - dependencies: [], - is_core: true, - settings: { - siteKey: "", - secretKey: "", - theme: "auto", - size: "normal", - mode: "managed", - appearance: "always", - preClearanceEnabled: false, - preClearanceLevel: "managed", - enabled: false - } - }); - return c.json({ success: true, plugin: turnstilePlugin }); - } - return c.json({ error: "Plugin not found in registry" }, 404); - } catch (error) { - console.error("Error installing plugin:", error); - const message = error instanceof Error ? error.message : "Failed to install plugin"; - return c.json({ error: message }, 400); - } -}); -adminPluginRoutes.post("/:id/uninstall", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const pluginId = c.req.param("id"); - if (user?.role !== "admin") { - return c.json({ error: "Access denied" }, 403); - } - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - await pluginService.uninstallPlugin(pluginId); - return c.json({ success: true }); - } catch (error) { - console.error("Error uninstalling plugin:", error); - const message = error instanceof Error ? error.message : "Failed to uninstall plugin"; - return c.json({ error: message }, 400); - } -}); -adminPluginRoutes.post("/:id/settings", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const pluginId = c.req.param("id"); - if (user?.role !== "admin") { - return c.json({ error: "Access denied" }, 403); - } - const settings = await c.req.json(); - const pluginService = new chunkMPT5PA6U_cjs.PluginService(db); - await pluginService.updatePluginSettings(pluginId, settings); - return c.json({ success: true }); - } catch (error) { - console.error("Error updating plugin settings:", error); - const message = error instanceof Error ? error.message : "Failed to update settings"; - return c.json({ error: message }, 400); - } -}); -function formatLastUpdated(timestamp) { - const now = Date.now() / 1e3; - const diff = now - timestamp; - if (diff < 60) return "just now"; - if (diff < 3600) return `${Math.floor(diff / 60)} minutes ago`; - if (diff < 86400) return `${Math.floor(diff / 3600)} hours ago`; - if (diff < 604800) return `${Math.floor(diff / 86400)} days ago`; - if (diff < 2592e3) return `${Math.floor(diff / 604800)} weeks ago`; - return `${Math.floor(diff / 2592e3)} months ago`; -} - -// src/templates/pages/admin-logs-list.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderLogsListPage(data) { - const { logs, pagination, filters, user } = data; - const content = ` -
-
-
-

System Logs

-

- Monitor and analyze system activity, errors, and performance metrics. -

-
- -
- - -
- -
- -
-
-
-
-
- -
-
- - - -
- -
-
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - -
- -
- - - Clear - -
-
- -
- ${pagination.totalItems} ${pagination.totalItems === 1 ? "entry" : "entries"} -
-
-
-
-
- - -
-
- - - - - - - - - - - - - ${logs.map((log) => ` - - - - - - - - - `).join("")} - -
- Level - - Category - - Message - - Source - - Time - - Actions -
- - ${log.level} - - - - ${log.category} - - -
-
${log.message}
- ${log.url ? `
${log.method} ${log.url}
` : ""} - ${log.duration ? `
${log.formattedDuration}
` : ""} -
-
- ${log.source || "-"} - - ${log.formattedDate} - - - View Details - -
-
- - ${logs.length === 0 ? ` -
- - - -

No log entries

-

No log entries found matching your criteria.

-
- ` : ""} -
- - - ${pagination.totalPages > 1 ? ` -
-
- ${pagination.currentPage > 1 ? ` - - Previous - - ` : ` - - Previous - - `} - ${pagination.currentPage < pagination.totalPages ? ` - - Next - - ` : ` - - Next - - `} -
- -
- ` : ""} -
- `; - const layoutData = { - title: "System Logs", - pageTitle: "System Logs", - currentPath: "/admin/logs", - user, - content - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} -function renderLogDetailsPage(data) { - const { log, user } = data; - const content = html.html` -
-
-
- -

Log Details

-

- Detailed information for log entry ${log.id} -

-
-
- -
-
-
-

Log Entry Information

-
- - ${log.level} - - - ${log.category} - -
-
-
- -
-
-
-
ID
-
${log.id}
-
- -
-
Timestamp
-
${log.formattedDate}
-
- -
-
Level
-
- - ${log.level} - -
-
- -
-
Category
-
- - ${log.category} - -
-
- - ${log.source ? html.html` -
-
Source
-
${log.source}
-
- ` : ""} - - ${log.userId ? html.html` -
-
User ID
-
${log.userId}
-
- ` : ""} - - ${log.sessionId ? html.html` -
-
Session ID
-
${log.sessionId}
-
- ` : ""} - - ${log.requestId ? html.html` -
-
Request ID
-
${log.requestId}
-
- ` : ""} - - ${log.ipAddress ? html.html` -
-
IP Address
-
${log.ipAddress}
-
- ` : ""} - - ${log.method && log.url ? html.html` -
-
HTTP Request
-
- ${log.method} ${log.url} - ${log.statusCode ? html.html`(${log.statusCode})` : ""} -
-
- ` : ""} - - ${log.duration ? html.html` -
-
Duration
-
${log.formattedDuration}
-
- ` : ""} - - ${log.userAgent ? html.html` -
-
User Agent
-
${log.userAgent}
-
- ` : ""} -
-
-
- - -
-
-

Message

-
-
-
- ${log.message} -
-
-
- - - ${log.tags && log.tags.length > 0 ? html.html` -
-
-

Tags

-
-
-
- ${log.tags.map((tag) => html.html` - - ${tag} - - `).join("")} -
-
-
- ` : ""} - - - ${log.data ? html.html` -
-
-

Additional Data

-
-
-
${JSON.stringify(log.data, null, 2)}
-
-
- ` : ""} - - - ${log.stackTrace ? html.html` -
-
-

Stack Trace

-
-
-
${log.stackTrace}
-
-
- ` : ""} - - -
- - ← Back to Logs - - -
- ${log.level === "error" || log.level === "fatal" ? html.html` - - ` : ""} - - -
-
-
- `; - return chunkSHCYIZAN_cjs.adminLayoutV2({ - title: `Log Details - ${log.id}`, - user, - content - }); -} -function renderLogConfigPage(data) { - const { configs, user } = data; - const content = html.html` -
-
-
- -

Log Configuration

-

- Configure logging settings for different categories and manage log retention policies. -

-
-
- -
-
- -
- - -
-
-

Log Levels Reference

-
-
-
-
- - debug - -

Detailed diagnostic information

-
-
- - info - -

General information messages

-
-
- - warn - -

Warning conditions

-
-
- - error - -

Error conditions

-
-
- - fatal - -

Critical system errors

-
-
-
-
- - -
- ${configs.map((config) => html.html` -
-
-
-

${config.category}

-
- ${config.enabled ? html.html` - - Enabled - - ` : html.html` - - Disabled - - `} -
-
-
- -
-
-
-
-
- - - - - -
-
-
- -
-
- -
- - -

Only logs at this level or higher will be stored

-
- -
- - -

Logs older than this will be deleted

-
- -
- - -

Maximum number of logs to keep for this category

-
-
- -
-
- -
-
- -
-
-
Created: ${new Date(config.createdAt).toLocaleDateString()}
-
Updated: ${new Date(config.updatedAt).toLocaleDateString()}
-
-
-
- `).join("")} -
- - -
-
-

Global Log Settings

-
-
-
-
-

Storage Information

-
-
-
-
-
Total Log Entries
-
-
-
-
-
Storage Used
-
-
-
-
-
Oldest Log
-
-
-
- -
-

Log Categories

-
-
    -
  • auth - Authentication and authorization events
  • -
  • api - API requests and responses
  • -
  • workflow - Content workflow state changes
  • -
  • plugin - Plugin-related activities
  • -
  • media - File upload and media operations
  • -
  • system - General system events
  • -
  • security - Security-related events and alerts
  • -
  • error - General error conditions
  • -
-
-
-
-
-
-
- - - `; - return chunkSHCYIZAN_cjs.adminLayoutV2({ - title: "Log Configuration", - user, - content - }); -} - -// src/routes/admin-logs.ts -var adminLogsRoutes = new hono.Hono(); -adminLogsRoutes.use("*", chunkDVQA5II3_cjs.requireAuth()); -adminLogsRoutes.get("/", async (c) => { - try { - const user = c.get("user"); - const logger = chunkVNLR35GO_cjs.getLogger(c.env.DB); - const query = c.req.query(); - const page = parseInt(query.page || "1"); - const limit = parseInt(query.limit || "50"); - const level = query.level; - const category = query.category; - const search = query.search; - const startDate = query.start_date; - const endDate = query.end_date; - const source = query.source; - const filter = { - limit, - offset: (page - 1) * limit, - sortBy: "created_at", - sortOrder: "desc" - }; - if (level) { - filter.level = level.split(","); - } - if (category) { - filter.category = category.split(","); - } - if (search) { - filter.search = search; - } - if (startDate) { - filter.startDate = new Date(startDate); - } - if (endDate) { - filter.endDate = new Date(endDate); - } - if (source) { - filter.source = source; - } - const { logs, total } = await logger.getLogs(filter); - const formattedLogs = logs.map((log) => ({ - ...log, - data: log.data ? JSON.parse(log.data) : null, - tags: log.tags ? JSON.parse(log.tags) : [], - formattedDate: new Date(log.createdAt).toLocaleString(), - formattedDuration: log.duration ? `${log.duration}ms` : null, - levelClass: getLevelClass(log.level), - categoryClass: getCategoryClass(log.category) - })); - const totalPages = Math.ceil(total / limit); - const pageData = { - logs: formattedLogs, - pagination: { - currentPage: page, - totalPages, - totalItems: total, - itemsPerPage: limit, - startItem: (page - 1) * limit + 1, - endItem: Math.min(page * limit, total), - baseUrl: "/admin/logs" - }, - filters: { - level: level || "", - category: category || "", - search: search || "", - startDate: startDate || "", - endDate: endDate || "", - source: source || "" - }, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - }; - return c.html(renderLogsListPage(pageData)); - } catch (error) { - console.error("Error fetching logs:", error); - return c.html(html.html`

Error loading logs: ${error}

`); - } -}); -adminLogsRoutes.get("/:id", async (c) => { - try { - const id = c.req.param("id"); - const user = c.get("user"); - const logger = chunkVNLR35GO_cjs.getLogger(c.env.DB); - const { logs } = await logger.getLogs({ - limit: 1, - offset: 0, - search: id - // Using search to find by ID - this is a simplification - }); - const log = logs.find((l) => l.id === id); - if (!log) { - return c.html(html.html`

Log entry not found

`); - } - const formattedLog = { - ...log, - data: log.data ? JSON.parse(log.data) : null, - tags: log.tags ? JSON.parse(log.tags) : [], - formattedDate: new Date(log.createdAt).toLocaleString(), - formattedDuration: log.duration ? `${log.duration}ms` : null, - levelClass: getLevelClass(log.level), - categoryClass: getCategoryClass(log.category) - }; - const pageData = { - log: formattedLog, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - }; - return c.html(renderLogDetailsPage(pageData)); - } catch (error) { - console.error("Error fetching log details:", error); - return c.html(html.html`

Error loading log details: ${error}

`); - } -}); -adminLogsRoutes.get("/config", async (c) => { - try { - const user = c.get("user"); - const logger = chunkVNLR35GO_cjs.getLogger(c.env.DB); - const configs = await logger.getAllConfigs(); - const pageData = { - configs, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - }; - return c.html(renderLogConfigPage(pageData)); - } catch (error) { - console.error("Error fetching log config:", error); - return c.html(html.html`

Error loading log configuration: ${error}

`); - } -}); -adminLogsRoutes.post("/config/:category", async (c) => { - try { - const category = c.req.param("category"); - const formData = await c.req.formData(); - const enabled = formData.get("enabled") === "on"; - const level = formData.get("level"); - const retention = parseInt(formData.get("retention")); - const maxSize = parseInt(formData.get("max_size")); - const logger = chunkVNLR35GO_cjs.getLogger(c.env.DB); - await logger.updateConfig(category, { - enabled, - level, - retention, - maxSize - }); - return c.html(html.html` -
- Configuration updated successfully! -
- `); - } catch (error) { - console.error("Error updating log config:", error); - return c.html(html.html` -
- Failed to update configuration. Please try again. -
- `); - } -}); -adminLogsRoutes.get("/export", async (c) => { - try { - const query = c.req.query(); - const format = query.format || "csv"; - const level = query.level; - const category = query.category; - const startDate = query.start_date; - const endDate = query.end_date; - const logger = chunkVNLR35GO_cjs.getLogger(c.env.DB); - const filter = { - limit: 1e4, - // Export up to 10k logs - offset: 0, - sortBy: "created_at", - sortOrder: "desc" - }; - if (level) { - filter.level = level.split(","); - } - if (category) { - filter.category = category.split(","); - } - if (startDate) { - filter.startDate = new Date(startDate); - } - if (endDate) { - filter.endDate = new Date(endDate); - } - const { logs } = await logger.getLogs(filter); - if (format === "json") { - return c.json(logs, 200, { - "Content-Disposition": 'attachment; filename="logs-export.json"' - }); - } else { - const headers = [ - "ID", - "Level", - "Category", - "Message", - "Source", - "User ID", - "IP Address", - "Method", - "URL", - "Status Code", - "Duration", - "Created At" - ]; - const csvRows = [headers.join(",")]; - logs.forEach((log) => { - const row = [ - log.id, - log.level, - log.category, - `"${log.message.replace(/"/g, '""')}"`, - // Escape quotes - log.source || "", - log.userId || "", - log.ipAddress || "", - log.method || "", - log.url || "", - log.statusCode || "", - log.duration || "", - new Date(log.createdAt).toISOString() - ]; - csvRows.push(row.join(",")); - }); - const csv = csvRows.join("\n"); - return new Response(csv, { - headers: { - "Content-Type": "text/csv", - "Content-Disposition": 'attachment; filename="logs-export.csv"' - } - }); - } - } catch (error) { - console.error("Error exporting logs:", error); - return c.json({ error: "Failed to export logs" }, 500); - } -}); -adminLogsRoutes.post("/cleanup", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.json({ - success: false, - error: "Unauthorized. Admin access required." - }, 403); - } - const logger = chunkVNLR35GO_cjs.getLogger(c.env.DB); - await logger.cleanupByRetention(); - return c.html(html.html` -
- Log cleanup completed successfully! -
- `); - } catch (error) { - console.error("Error cleaning up logs:", error); - return c.html(html.html` -
- Failed to clean up logs. Please try again. -
- `); - } -}); -adminLogsRoutes.post("/search", async (c) => { - try { - const formData = await c.req.formData(); - const search = formData.get("search"); - const level = formData.get("level"); - const category = formData.get("category"); - const logger = chunkVNLR35GO_cjs.getLogger(c.env.DB); - const filter = { - limit: 20, - offset: 0, - sortBy: "created_at", - sortOrder: "desc" - }; - if (search) filter.search = search; - if (level) filter.level = [level]; - if (category) filter.category = [category]; - const { logs } = await logger.getLogs(filter); - const rows = logs.map((log) => { - const formattedLog = { - ...log, - formattedDate: new Date(log.createdAt).toLocaleString(), - levelClass: getLevelClass(log.level), - categoryClass: getCategoryClass(log.category) - }; - return ` - - - - ${formattedLog.level} - - - - - ${formattedLog.category} - - - -
${formattedLog.message}
- - ${formattedLog.source || "-"} - ${formattedLog.formattedDate} - - View - - - `; - }).join(""); - return c.html(rows); - } catch (error) { - console.error("Error searching logs:", error); - return c.html(html.html`Error searching logs`); - } -}); -function getLevelClass(level) { - switch (level) { - case "debug": - return "bg-gray-100 text-gray-800"; - case "info": - return "bg-blue-100 text-blue-800"; - case "warn": - return "bg-yellow-100 text-yellow-800"; - case "error": - return "bg-red-100 text-red-800"; - case "fatal": - return "bg-purple-100 text-purple-800"; - default: - return "bg-gray-100 text-gray-800"; - } -} -function getCategoryClass(category) { - switch (category) { - case "auth": - return "bg-green-100 text-green-800"; - case "api": - return "bg-blue-100 text-blue-800"; - case "workflow": - return "bg-purple-100 text-purple-800"; - case "plugin": - return "bg-indigo-100 text-indigo-800"; - case "media": - return "bg-pink-100 text-pink-800"; - case "system": - return "bg-gray-100 text-gray-800"; - case "security": - return "bg-red-100 text-red-800"; - case "error": - return "bg-red-100 text-red-800"; - default: - return "bg-gray-100 text-gray-800"; - } -} -var adminDesignRoutes = new hono.Hono(); -adminDesignRoutes.get("/", (c) => { - const user = c.get("user"); - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - }; - return c.html(chunkSHCYIZAN_cjs.renderDesignPage(pageData)); -}); -var adminCheckboxRoutes = new hono.Hono(); -adminCheckboxRoutes.get("/", (c) => { - const user = c.get("user"); - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - }; - return c.html(chunkSHCYIZAN_cjs.renderCheckboxPage(pageData)); -}); - -// src/templates/pages/admin-testimonials-form.template.ts -function renderTestimonialsForm(data) { - const { testimonial, isEdit, errors, message, messageType } = data; - const pageTitle = isEdit ? "Edit Testimonial" : "New Testimonial"; - const pageContent = ` -
- -
-
-

${pageTitle}

-

- ${isEdit ? "Update the testimonial details below" : "Create a new customer testimonial"} -

-
- -
- - ${message ? chunkSHCYIZAN_cjs.renderAlert({ type: messageType || "info", message, dismissible: true }) : ""} - - -
-
- - -
-

Author Information

- - -
- -
- -
- ${errors?.authorName ? ` -
- ${errors.authorName.map((error) => ` -

${escapeHtml4(error)}

- `).join("")} -
- ` : ""} -
- -
- -
- -
- -
- ${errors?.authorTitle ? ` -
- ${errors.authorTitle.map((error) => ` -

${escapeHtml4(error)}

- `).join("")} -
- ` : ""} -
- - -
- -
- -
- ${errors?.authorCompany ? ` -
- ${errors.authorCompany.map((error) => ` -

${escapeHtml4(error)}

- `).join("")} -
- ` : ""} -
-
-
- - -
-

Testimonial

- - -
- -
- -

- 0/1000 characters -

-
- ${errors?.testimonialText ? ` -
- ${errors.testimonialText.map((error) => ` -

${escapeHtml4(error)}

- `).join("")} -
- ` : ""} -
- - -
- -
- -
- ${errors?.rating ? ` -
- ${errors.rating.map((error) => ` -

${escapeHtml4(error)}

- `).join("")} -
- ` : ""} -
-
- - -
- -
- -
-
- - -
-
- - -
-
-
- - -
- -
- -

Lower numbers appear first (0 = highest priority)

-
- ${errors?.sortOrder ? ` -
- ${errors.sortOrder.map((error) => ` -

${escapeHtml4(error)}

- `).join("")} -
- ` : ""} -
-
- - -
- - Cancel - - -
-
-
-
- - - `; - const layoutData = { - title: `${pageTitle} - Admin`, - pageTitle, - currentPath: isEdit ? `/admin/testimonials/${testimonial?.id}` : "/admin/testimonials/new", - user: data.user, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayout(layoutData); -} -function escapeHtml4(unsafe) { - return unsafe.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); -} - -// src/routes/admin-testimonials.ts -var testimonialSchema = zod.z.object({ - authorName: zod.z.string().min(1, "Author name is required").max(100, "Author name must be under 100 characters"), - authorTitle: zod.z.string().optional(), - authorCompany: zod.z.string().optional(), - testimonialText: zod.z.string().min(1, "Testimonial is required").max(1e3, "Testimonial must be under 1000 characters"), - rating: zod.z.string().transform((val) => val ? parseInt(val, 10) : void 0).pipe(zod.z.number().min(1).max(5).optional()), - isPublished: zod.z.string().transform((val) => val === "true"), - sortOrder: zod.z.string().transform((val) => parseInt(val, 10)).pipe(zod.z.number().min(0)) -}); -var adminTestimonialsRoutes = new hono.Hono(); -adminTestimonialsRoutes.get("/", async (c) => { - try { - const user = c.get("user"); - const { published, minRating, search, page = "1" } = c.req.query(); - const currentPage = parseInt(page, 10) || 1; - const limit = 20; - const offset = (currentPage - 1) * limit; - const db = c.env?.DB; - if (!db) { - return c.html(chunkSHCYIZAN_cjs.renderTestimonialsList({ - testimonials: [], - totalCount: 0, - currentPage: 1, - totalPages: 1, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Database not available", - messageType: "error" - })); - } - let whereClause = "WHERE 1=1"; - const params = []; - if (published !== void 0) { - whereClause += " AND isPublished = ?"; - params.push(published === "true" ? 1 : 0); - } - if (minRating) { - whereClause += " AND rating >= ?"; - params.push(parseInt(minRating, 10)); - } - if (search) { - whereClause += " AND (author_name LIKE ? OR testimonial_text LIKE ? OR author_company LIKE ?)"; - const searchTerm = `%${search}%`; - params.push(searchTerm, searchTerm, searchTerm); - } - const countQuery = `SELECT COUNT(*) as count FROM testimonials ${whereClause}`; - const { results: countResults } = await db.prepare(countQuery).bind(...params).all(); - const totalCount = countResults?.[0]?.count || 0; - const dataQuery = ` - SELECT * FROM testimonials - ${whereClause} - ORDER BY sortOrder ASC, created_at DESC - LIMIT ? OFFSET ? - `; - const { results: testimonials } = await db.prepare(dataQuery).bind(...params, limit, offset).all(); - const totalPages = Math.ceil(totalCount / limit); - return c.html(chunkSHCYIZAN_cjs.renderTestimonialsList({ - testimonials: testimonials || [], - totalCount, - currentPage, - totalPages, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - })); - } catch (error) { - console.error("Error fetching testimonials:", error); - const user = c.get("user"); - return c.html(chunkSHCYIZAN_cjs.renderTestimonialsList({ - testimonials: [], - totalCount: 0, - currentPage: 1, - totalPages: 1, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Failed to load testimonials", - messageType: "error" - })); - } -}); -adminTestimonialsRoutes.get("/new", async (c) => { - const user = c.get("user"); - return c.html(renderTestimonialsForm({ - isEdit: false, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - })); -}); -adminTestimonialsRoutes.post("/", async (c) => { - try { - const formData = await c.req.formData(); - const data = Object.fromEntries(formData.entries()); - const validatedData = testimonialSchema.parse(data); - const user = c.get("user"); - const db = c.env?.DB; - if (!db) { - return c.html(renderTestimonialsForm({ - isEdit: false, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Database not available", - messageType: "error" - })); - } - const { results } = await db.prepare(` - INSERT INTO testimonials (author_name, author_title, author_company, testimonial_text, rating, isPublished, sortOrder) - VALUES (?, ?, ?, ?, ?, ?, ?) - RETURNING * - `).bind( - validatedData.authorName, - validatedData.authorTitle || null, - validatedData.authorCompany || null, - validatedData.testimonialText, - validatedData.rating || null, - validatedData.isPublished ? 1 : 0, - validatedData.sortOrder - ).all(); - if (results && results.length > 0) { - return c.redirect("/admin/testimonials?message=Testimonial created successfully"); - } else { - return c.html(renderTestimonialsForm({ - isEdit: false, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Failed to create testimonial", - messageType: "error" - })); - } - } catch (error) { - console.error("Error creating testimonial:", error); - const user = c.get("user"); - if (error instanceof zod.z.ZodError) { - const errors = {}; - error.issues.forEach((err) => { - const field = err.path[0]; - if (!errors[field]) errors[field] = []; - errors[field].push(err.message); - }); - return c.html(renderTestimonialsForm({ - isEdit: false, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - errors, - message: "Please correct the errors below", - messageType: "error" - })); - } - return c.html(renderTestimonialsForm({ - isEdit: false, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Failed to create testimonial", - messageType: "error" - })); - } -}); -adminTestimonialsRoutes.get("/:id", async (c) => { - try { - const id = parseInt(c.req.param("id")); - const user = c.get("user"); - const db = c.env?.DB; - if (!db) { - return c.html(renderTestimonialsForm({ - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Database not available", - messageType: "error" - })); - } - const { results } = await db.prepare("SELECT * FROM testimonials WHERE id = ?").bind(id).all(); - if (!results || results.length === 0) { - return c.redirect("/admin/testimonials?message=Testimonial not found&type=error"); - } - const testimonial = results[0]; - return c.html(renderTestimonialsForm({ - testimonial: { - id: testimonial.id, - authorName: testimonial.author_name, - authorTitle: testimonial.author_title, - authorCompany: testimonial.author_company, - testimonialText: testimonial.testimonial_text, - rating: testimonial.rating, - isPublished: Boolean(testimonial.isPublished), - sortOrder: testimonial.sortOrder - }, - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - })); - } catch (error) { - console.error("Error fetching testimonial:", error); - const user = c.get("user"); - return c.html(renderTestimonialsForm({ - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Failed to load testimonial", - messageType: "error" - })); - } -}); -adminTestimonialsRoutes.put("/:id", async (c) => { - try { - const id = parseInt(c.req.param("id")); - const formData = await c.req.formData(); - const data = Object.fromEntries(formData.entries()); - const validatedData = testimonialSchema.parse(data); - const user = c.get("user"); - const db = c.env?.DB; - if (!db) { - return c.html(renderTestimonialsForm({ - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Database not available", - messageType: "error" - })); - } - const { results } = await db.prepare(` - UPDATE testimonials - SET author_name = ?, author_title = ?, author_company = ?, testimonial_text = ?, rating = ?, isPublished = ?, sortOrder = ? - WHERE id = ? - RETURNING * - `).bind( - validatedData.authorName, - validatedData.authorTitle || null, - validatedData.authorCompany || null, - validatedData.testimonialText, - validatedData.rating || null, - validatedData.isPublished ? 1 : 0, - validatedData.sortOrder, - id - ).all(); - if (results && results.length > 0) { - return c.redirect("/admin/testimonials?message=Testimonial updated successfully"); - } else { - return c.html(renderTestimonialsForm({ - testimonial: { - id, - authorName: validatedData.authorName, - authorTitle: validatedData.authorTitle, - authorCompany: validatedData.authorCompany, - testimonialText: validatedData.testimonialText, - rating: validatedData.rating, - isPublished: validatedData.isPublished, - sortOrder: validatedData.sortOrder - }, - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Testimonial not found", - messageType: "error" - })); - } - } catch (error) { - console.error("Error updating testimonial:", error); - const user = c.get("user"); - const id = parseInt(c.req.param("id")); - if (error instanceof zod.z.ZodError) { - const errors = {}; - error.issues.forEach((err) => { - const field = err.path[0]; - if (!errors[field]) errors[field] = []; - errors[field].push(err.message); - }); - return c.html(renderTestimonialsForm({ - testimonial: { - id, - authorName: "", - authorTitle: "", - authorCompany: "", - testimonialText: "", - rating: void 0, - isPublished: true, - sortOrder: 0 - }, - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - errors, - message: "Please correct the errors below", - messageType: "error" - })); - } - return c.html(renderTestimonialsForm({ - testimonial: { - id, - authorName: "", - authorTitle: "", - authorCompany: "", - testimonialText: "", - rating: void 0, - isPublished: true, - sortOrder: 0 - }, - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Failed to update testimonial", - messageType: "error" - })); - } -}); -adminTestimonialsRoutes.delete("/:id", async (c) => { - try { - const id = parseInt(c.req.param("id")); - const db = c.env?.DB; - if (!db) { - return c.json({ error: "Database not available" }, 500); - } - const { changes } = await db.prepare("DELETE FROM testimonials WHERE id = ?").bind(id).run(); - if (changes === 0) { - return c.json({ error: "Testimonial not found" }, 404); - } - return c.redirect("/admin/testimonials?message=Testimonial deleted successfully"); - } catch (error) { - console.error("Error deleting testimonial:", error); - return c.json({ error: "Failed to delete testimonial" }, 500); - } -}); -var admin_testimonials_default = adminTestimonialsRoutes; - -// src/templates/pages/admin-code-examples-form.template.ts -function renderCodeExamplesForm(data) { - const { codeExample, isEdit, errors, message, messageType } = data; - const pageTitle = isEdit ? "Edit Code Example" : "New Code Example"; - const pageContent = ` -
- -
-
-

${pageTitle}

-

- ${isEdit ? "Update the code example details below" : "Create a new code snippet or example"} -

-
- -
- - ${message ? chunkSHCYIZAN_cjs.renderAlert({ type: messageType || "info", message, dismissible: true }) : ""} - - -
-
- - -
-

Basic Information

- - -
- -
- -
- ${errors?.title ? ` -
- ${errors.title.map((error) => ` -

${escapeHtml5(error)}

- `).join("")} -
- ` : ""} -
- - -
- -
- -

- 0/500 characters -

-
- ${errors?.description ? ` -
- ${errors.description.map((error) => ` -

${escapeHtml5(error)}

- `).join("")} -
- ` : ""} -
- -
- -
- -
- -
- ${errors?.language ? ` -
- ${errors.language.map((error) => ` -

${escapeHtml5(error)}

- `).join("")} -
- ` : ""} -
- - -
- -
- -
- ${errors?.category ? ` -
- ${errors.category.map((error) => ` -

${escapeHtml5(error)}

- `).join("")} -
- ` : ""} -
- - -
- -
- -

Comma-separated tags

-
- ${errors?.tags ? ` -
- ${errors.tags.map((error) => ` -

${escapeHtml5(error)}

- `).join("")} -
- ` : ""} -
-
-
- - -
-

Code

- - -
- -
- -

- 0 characters -

-
- ${errors?.code ? ` -
- ${errors.code.map((error) => ` -

${escapeHtml5(error)}

- `).join("")} -
- ` : ""} -
-
- - -
- -
- -
-
- - -
-
- - -
-
-
- - -
- -
- -

Lower numbers appear first (0 = highest priority)

-
- ${errors?.sortOrder ? ` -
- ${errors.sortOrder.map((error) => ` -

${escapeHtml5(error)}

- `).join("")} -
- ` : ""} -
-
- - -
- - Cancel - - -
-
-
-
- - - `; - const layoutData = { - title: `${pageTitle} - Admin`, - pageTitle, - currentPath: isEdit ? `/admin/code-examples/${codeExample?.id}` : "/admin/code-examples/new", - user: data.user, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayout(layoutData); -} -function escapeHtml5(unsafe) { - return unsafe.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); -} - -// src/routes/admin-code-examples.ts -var codeExampleSchema = zod.z.object({ - title: zod.z.string().min(1, "Title is required").max(200, "Title must be under 200 characters"), - description: zod.z.string().max(500, "Description must be under 500 characters").optional(), - code: zod.z.string().min(1, "Code is required"), - language: zod.z.string().min(1, "Language is required"), - category: zod.z.string().max(50, "Category must be under 50 characters").optional(), - tags: zod.z.string().max(200, "Tags must be under 200 characters").optional(), - isPublished: zod.z.string().transform((val) => val === "true"), - sortOrder: zod.z.string().transform((val) => parseInt(val, 10)).pipe(zod.z.number().min(0)) -}); -var adminCodeExamplesRoutes = new hono.Hono(); -adminCodeExamplesRoutes.get("/", async (c) => { - try { - const user = c.get("user"); - const { published, language, search, page = "1" } = c.req.query(); - const currentPage = parseInt(page, 10) || 1; - const limit = 20; - const offset = (currentPage - 1) * limit; - const db = c.env?.DB; - if (!db) { - return c.html(chunkSHCYIZAN_cjs.renderCodeExamplesList({ - codeExamples: [], - totalCount: 0, - currentPage: 1, - totalPages: 1, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Database not available", - messageType: "error" - })); - } - let whereClause = "WHERE 1=1"; - const params = []; - if (published !== void 0) { - whereClause += " AND isPublished = ?"; - params.push(published === "true" ? 1 : 0); - } - if (language) { - whereClause += " AND language = ?"; - params.push(language); - } - if (search) { - whereClause += " AND (title LIKE ? OR description LIKE ? OR code LIKE ? OR tags LIKE ?)"; - const searchTerm = `%${search}%`; - params.push(searchTerm, searchTerm, searchTerm, searchTerm); - } - const countQuery = `SELECT COUNT(*) as count FROM code_examples ${whereClause}`; - const { results: countResults } = await db.prepare(countQuery).bind(...params).all(); - const totalCount = countResults?.[0]?.count || 0; - const dataQuery = ` - SELECT * FROM code_examples - ${whereClause} - ORDER BY sortOrder ASC, created_at DESC - LIMIT ? OFFSET ? - `; - const { results: codeExamples } = await db.prepare(dataQuery).bind(...params, limit, offset).all(); - const totalPages = Math.ceil(totalCount / limit); - return c.html(chunkSHCYIZAN_cjs.renderCodeExamplesList({ - codeExamples: codeExamples || [], - totalCount, - currentPage, - totalPages, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - })); - } catch (error) { - console.error("Error fetching code examples:", error); - const user = c.get("user"); - return c.html(chunkSHCYIZAN_cjs.renderCodeExamplesList({ - codeExamples: [], - totalCount: 0, - currentPage: 1, - totalPages: 1, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Failed to load code examples", - messageType: "error" - })); - } -}); -adminCodeExamplesRoutes.get("/new", async (c) => { - const user = c.get("user"); - return c.html(renderCodeExamplesForm({ - isEdit: false, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - })); -}); -adminCodeExamplesRoutes.post("/", async (c) => { - try { - const formData = await c.req.formData(); - const data = Object.fromEntries(formData.entries()); - const validatedData = codeExampleSchema.parse(data); - const user = c.get("user"); - const db = c.env?.DB; - if (!db) { - return c.html(renderCodeExamplesForm({ - isEdit: false, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Database not available", - messageType: "error" - })); - } - const { results } = await db.prepare(` - INSERT INTO code_examples (title, description, code, language, category, tags, isPublished, sortOrder) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - RETURNING * - `).bind( - validatedData.title, - validatedData.description || null, - validatedData.code, - validatedData.language, - validatedData.category || null, - validatedData.tags || null, - validatedData.isPublished ? 1 : 0, - validatedData.sortOrder - ).all(); - if (results && results.length > 0) { - return c.redirect("/admin/code-examples?message=Code example created successfully"); - } else { - return c.html(renderCodeExamplesForm({ - isEdit: false, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Failed to create code example", - messageType: "error" - })); - } - } catch (error) { - console.error("Error creating code example:", error); - const user = c.get("user"); - if (error instanceof zod.z.ZodError) { - const errors = {}; - error.issues.forEach((err) => { - const field = err.path[0]; - if (!errors[field]) errors[field] = []; - errors[field].push(err.message); - }); - return c.html(renderCodeExamplesForm({ - isEdit: false, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - errors, - message: "Please correct the errors below", - messageType: "error" - })); - } - return c.html(renderCodeExamplesForm({ - isEdit: false, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Failed to create code example", - messageType: "error" - })); - } -}); -adminCodeExamplesRoutes.get("/:id", async (c) => { - try { - const id = parseInt(c.req.param("id")); - const user = c.get("user"); - const db = c.env?.DB; - if (!db) { - return c.html(renderCodeExamplesForm({ - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Database not available", - messageType: "error" - })); - } - const { results } = await db.prepare("SELECT * FROM code_examples WHERE id = ?").bind(id).all(); - if (!results || results.length === 0) { - return c.redirect("/admin/code-examples?message=Code example not found&type=error"); - } - const example = results[0]; - return c.html(renderCodeExamplesForm({ - codeExample: { - id: example.id, - title: example.title, - description: example.description, - code: example.code, - language: example.language, - category: example.category, - tags: example.tags, - isPublished: Boolean(example.isPublished), - sortOrder: example.sortOrder - }, - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0 - })); - } catch (error) { - console.error("Error fetching code example:", error); - const user = c.get("user"); - return c.html(renderCodeExamplesForm({ - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Failed to load code example", - messageType: "error" - })); - } -}); -adminCodeExamplesRoutes.put("/:id", async (c) => { - try { - const id = parseInt(c.req.param("id")); - const formData = await c.req.formData(); - const data = Object.fromEntries(formData.entries()); - const validatedData = codeExampleSchema.parse(data); - const user = c.get("user"); - const db = c.env?.DB; - if (!db) { - return c.html(renderCodeExamplesForm({ - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Database not available", - messageType: "error" - })); - } - const { results } = await db.prepare(` - UPDATE code_examples - SET title = ?, description = ?, code = ?, language = ?, category = ?, tags = ?, isPublished = ?, sortOrder = ? - WHERE id = ? - RETURNING * - `).bind( - validatedData.title, - validatedData.description || null, - validatedData.code, - validatedData.language, - validatedData.category || null, - validatedData.tags || null, - validatedData.isPublished ? 1 : 0, - validatedData.sortOrder, - id - ).all(); - if (results && results.length > 0) { - return c.redirect("/admin/code-examples?message=Code example updated successfully"); - } else { - return c.html(renderCodeExamplesForm({ - codeExample: { - id, - title: validatedData.title, - description: validatedData.description, - code: validatedData.code, - language: validatedData.language, - category: validatedData.category, - tags: validatedData.tags, - isPublished: validatedData.isPublished, - sortOrder: validatedData.sortOrder - }, - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Code example not found", - messageType: "error" - })); - } - } catch (error) { - console.error("Error updating code example:", error); - const user = c.get("user"); - const id = parseInt(c.req.param("id")); - if (error instanceof zod.z.ZodError) { - const errors = {}; - error.issues.forEach((err) => { - const field = err.path[0]; - if (!errors[field]) errors[field] = []; - errors[field].push(err.message); - }); - return c.html(renderCodeExamplesForm({ - codeExample: { - id, - title: "", - description: "", - code: "", - language: "", - category: "", - tags: "", - isPublished: true, - sortOrder: 0 - }, - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - errors, - message: "Please correct the errors below", - messageType: "error" - })); - } - return c.html(renderCodeExamplesForm({ - codeExample: { - id, - title: "", - description: "", - code: "", - language: "", - category: "", - tags: "", - isPublished: true, - sortOrder: 0 - }, - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - message: "Failed to update code example", - messageType: "error" - })); - } -}); -adminCodeExamplesRoutes.delete("/:id", async (c) => { - try { - const id = parseInt(c.req.param("id")); - const db = c.env?.DB; - if (!db) { - return c.json({ error: "Database not available" }, 500); - } - const { changes } = await db.prepare("DELETE FROM code_examples WHERE id = ?").bind(id).run(); - if (changes === 0) { - return c.json({ error: "Code example not found" }, 404); - } - return c.redirect("/admin/code-examples?message=Code example deleted successfully"); - } catch (error) { - console.error("Error deleting code example:", error); - return c.json({ error: "Failed to delete code example" }, 500); - } -}); -var admin_code_examples_default = adminCodeExamplesRoutes; - -// src/templates/pages/admin-dashboard.template.ts -function renderDashboardPage(data) { - const pageContent = ` -
-
-

Dashboard

-

Welcome to your SonicJS AI admin dashboard

-
- -
- - -
- ${renderStatsCardsSkeleton()} -
- - -
- -
- ${renderAnalyticsChart()} -
- - -
- ${renderRecentActivitySkeleton()} -
-
- - -
- - ${renderQuickActions()} - - - ${renderSystemStatus()} - - -
- ${renderStorageUsage()} -
-
- - - `; - const layoutData = { - title: "Dashboard", - pageTitle: "Dashboard", - currentPath: "/admin", - user: data.user, - version: data.version, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayout(layoutData); -} -function renderStatsCards(stats) { - const cards = [ - { - title: "Total Collections", - value: stats.collections.toString(), - change: "12.5", - isPositive: true - }, - { - title: "Content Items", - value: stats.contentItems.toString(), - change: "8.2", - isPositive: true - }, - { - title: "Media Files", - value: stats.mediaFiles.toString(), - change: "15.3", - isPositive: true - }, - { - title: "Active Users", - value: stats.users.toString(), - change: "2.4", - isPositive: false - } - ]; - const cardColors = ["text-cyan-400", "text-lime-400", "text-pink-400", "text-purple-400"]; - return ` -
-

Last 30 days

-
- ${cards.map((card, index) => ` -
-
${card.title}
-
-
- ${card.value} -
-
- - ${card.isPositive ? '' : ''} - - ${card.isPositive ? "Increased" : "Decreased"} by - ${card.change}% -
-
-
- `).join("")} -
-
- `; -} -function renderStatsCardsSkeleton() { - return ` -
-
-
- ${Array(4).fill(0).map( - () => ` -
-
-
-
- ` - ).join("")} -
-
- `; -} -function renderAnalyticsChart() { - return ` -
-
-
-
-

Real-Time Analytics

-

Requests per second (live)

-
-
-
- Live -
-
-
- 0 - req/s -
-
- -
- -
- - -
-
- - - `; -} -function renderRecentActivitySkeleton() { - return ` -
-
-
-
-
-
- ${Array(3).fill(0).map(() => ` -
-
-
-
-
-
-
- `).join("")} -
-
-
- `; -} -function renderRecentActivity(activities) { - const getInitials = (user) => { - const parts = user.split(" ").filter((p) => p.length > 0); - if (parts.length >= 2) { - const first = parts[0]?.[0] || ""; - const second = parts[1]?.[0] || ""; - return (first + second).toUpperCase(); - } - return user.substring(0, 2).toUpperCase(); - }; - const getRelativeTime = (timestamp) => { - const date = new Date(timestamp); - const now = /* @__PURE__ */ new Date(); - const diffMs = now.getTime() - date.getTime(); - const diffMins = Math.floor(diffMs / 6e4); - const diffHours = Math.floor(diffMins / 60); - const diffDays = Math.floor(diffHours / 24); - if (diffMins < 1) return "just now"; - if (diffMins < 60) return `${diffMins} minute${diffMins > 1 ? "s" : ""} ago`; - if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? "s" : ""} ago`; - return `${diffDays} day${diffDays > 1 ? "s" : ""} ago`; - }; - const getColorClasses = (type) => { - switch (type) { - case "content": - return { - bgColor: "bg-lime-500/10 dark:bg-lime-400/10", - textColor: "text-lime-700 dark:text-lime-300" - }; - case "media": - return { - bgColor: "bg-cyan-500/10 dark:bg-cyan-400/10", - textColor: "text-cyan-700 dark:text-cyan-300" - }; - case "user": - return { - bgColor: "bg-pink-500/10 dark:bg-pink-400/10", - textColor: "text-pink-700 dark:text-pink-300" - }; - case "collection": - return { - bgColor: "bg-purple-500/10 dark:bg-purple-400/10", - textColor: "text-purple-700 dark:text-purple-300" - }; - default: - return { - bgColor: "bg-gray-500/10 dark:bg-gray-400/10", - textColor: "text-gray-700 dark:text-gray-300" - }; - } - }; - const formattedActivities = (activities || []).map((activity) => { - const colors = getColorClasses(activity.type); - return { - ...activity, - initials: getInitials(activity.user), - time: getRelativeTime(activity.timestamp), - ...colors - }; - }); - if (formattedActivities.length === 0) { - formattedActivities.push({ - type: "content", - description: "No recent activity", - user: "System", - time: "", - initials: "SY", - bgColor: "bg-gray-500/10 dark:bg-gray-400/10", - textColor: "text-gray-700 dark:text-gray-300", - id: "0", - action: "", - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } - return ` -
-
-
-

Recent Activity

- -
-
- -
-
    - ${formattedActivities.map( - (activity) => ` -
  • -
    - ${activity.initials} -
    -
    -

    ${activity.description}

    -

    - ${activity.user} - \xB7 - ${activity.time} -

    -
    -
  • - ` - ).join("")} -
-
-
- `; -} -function renderQuickActions() { - const actions = [ - { - title: "Create Content", - description: "Add new blog post or page", - href: "/admin/content/new", - icon: ` - - ` - }, - { - title: "Upload Media", - description: "Add images and files", - href: "/admin/media", - icon: ` - - ` - }, - { - title: "Manage Users", - description: "Add or edit user accounts", - href: "/admin/users", - icon: ` - - ` - } - ]; - return ` -
-
-

Quick Actions

-
- -
-
- ${actions.map( - (action) => ` - -
- ${action.icon} -
-
-

${action.title}

-

${action.description}

-
- - - -
- ` - ).join("")} -
-
-
- `; -} -function renderSystemStatus() { - return ` -
-
-
-

System Status

-
-
- Live -
-
-
- -
- -
- ${[ - { color: "from-blue-500/20 to-cyan-500/20", darkColor: "dark:from-blue-500/10 dark:to-cyan-500/10" }, - { color: "from-purple-500/20 to-pink-500/20", darkColor: "dark:from-purple-500/10 dark:to-pink-500/10" }, - { color: "from-amber-500/20 to-orange-500/20", darkColor: "dark:from-amber-500/10 dark:to-orange-500/10" }, - { color: "from-lime-500/20 to-emerald-500/20", darkColor: "dark:from-lime-500/10 dark:to-emerald-500/10" } - ].map((gradient, i) => ` -
-
-
-
-
-
-
-
-
-
- `).join("")} -
-
-
- - - `; -} -function renderStorageUsage(databaseSizeBytes, mediaSizeBytes) { - const formatBytes = (bytes) => { - if (bytes === 0) return "0 B"; - const k = 1024; - const sizes = ["B", "KB", "MB", "GB"]; - const i = Math.floor(Math.log(bytes) / Math.log(k)); - return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`; - }; - const dbSizeGB = databaseSizeBytes ? databaseSizeBytes / 1024 ** 3 : 0; - const dbMaxGB = 10; - const dbPercentageRaw = dbSizeGB / dbMaxGB * 100; - const dbPercentage = Math.min(Math.max(dbPercentageRaw, 0.5), 100); - const dbUsedFormatted = databaseSizeBytes ? formatBytes(databaseSizeBytes) : "Unknown"; - const mediaUsedFormatted = mediaSizeBytes ? formatBytes(mediaSizeBytes) : "0 B"; - const storageItems = [ - { - label: "Database", - used: dbUsedFormatted, - total: "10 GB", - percentage: dbPercentage, - color: dbPercentage > 80 ? "bg-red-500 dark:bg-red-400" : dbPercentage > 60 ? "bg-amber-500 dark:bg-amber-400" : "bg-cyan-500 dark:bg-cyan-400" - }, - { - label: "Media Files", - used: mediaUsedFormatted, - total: "\u221E", - percentage: 0, - color: "bg-lime-500 dark:bg-lime-400", - note: "Stored in R2" - }, - { - label: "Cache (KV)", - used: "N/A", - total: "\u221E", - percentage: 0, - color: "bg-purple-500 dark:bg-purple-400", - note: "Unlimited" - } - ]; - return ` -
-
-

Storage Usage

-
- -
-
- ${storageItems.map( - (item) => ` -
-
-
- ${item.label} - ${item.note ? `(${item.note})` : ""} -
-
${item.used} / ${item.total}
-
-
-
-
-
- ` - ).join("")} -
-
-
- `; -} - -// src/routes/admin-dashboard.ts -var VERSION = chunk5HMR2SJW_cjs.getCoreVersion(); -var router = new hono.Hono(); -router.use("*", chunkDVQA5II3_cjs.requireAuth()); -router.get("/", async (c) => { - const user = c.get("user"); - try { - const pageData = { - user: { - name: user.email.split("@")[0] || user.email, - email: user.email, - role: user.role - }, - version: VERSION - }; - return c.html(renderDashboardPage(pageData)); - } catch (error) { - console.error("Dashboard error:", error); - const pageData = { - user: { - name: user.email, - email: user.email, - role: user.role - }, - version: VERSION - }; - return c.html(renderDashboardPage(pageData)); - } -}); -router.get("/stats", async (c) => { - try { - const db = c.env.DB; - let collectionsCount = 0; - try { - const collectionsStmt = db.prepare("SELECT COUNT(*) as count FROM collections WHERE is_active = 1"); - const collectionsResult = await collectionsStmt.first(); - collectionsCount = collectionsResult?.count || 0; - } catch (error) { - console.error("Error fetching collections count:", error); - } - let contentCount = 0; - try { - const contentStmt = db.prepare("SELECT COUNT(*) as count FROM content"); - const contentResult = await contentStmt.first(); - contentCount = contentResult?.count || 0; - } catch (error) { - console.error("Error fetching content count:", error); - } - let mediaCount = 0; - let mediaSize = 0; - try { - const mediaStmt = db.prepare("SELECT COUNT(*) as count, COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL"); - const mediaResult = await mediaStmt.first(); - mediaCount = mediaResult?.count || 0; - mediaSize = mediaResult?.total_size || 0; - } catch (error) { - console.error("Error fetching media count:", error); - } - let usersCount = 0; - try { - const usersStmt = db.prepare("SELECT COUNT(*) as count FROM users WHERE is_active = 1"); - const usersResult = await usersStmt.first(); - usersCount = usersResult?.count || 0; - } catch (error) { - console.error("Error fetching users count:", error); - } - const html8 = renderStatsCards({ - collections: collectionsCount, - contentItems: contentCount, - mediaFiles: mediaCount, - users: usersCount, - mediaSize - }); - return c.html(html8); - } catch (error) { - console.error("Error fetching stats:", error); - return c.html('
Failed to load statistics
'); - } -}); -router.get("/storage", async (c) => { - try { - const db = c.env.DB; - let databaseSize = 0; - try { - const result = await db.prepare("SELECT 1").run(); - databaseSize = result?.meta?.size_after || 0; - } catch (error) { - console.error("Error fetching database size:", error); - } - let mediaSize = 0; - try { - const mediaStmt = db.prepare("SELECT COALESCE(SUM(size), 0) as total_size FROM media WHERE deleted_at IS NULL"); - const mediaResult = await mediaStmt.first(); - mediaSize = mediaResult?.total_size || 0; - } catch (error) { - console.error("Error fetching media size:", error); - } - const html8 = renderStorageUsage(databaseSize, mediaSize); - return c.html(html8); - } catch (error) { - console.error("Error fetching storage usage:", error); - return c.html('
Failed to load storage information
'); - } -}); -router.get("/recent-activity", async (c) => { - try { - const db = c.env.DB; - const limit = parseInt(c.req.query("limit") || "5"); - const activityStmt = db.prepare(` - SELECT - a.id, - a.action, - a.resource_type, - a.resource_id, - a.details, - a.created_at, - u.email, - u.first_name, - u.last_name - FROM activity_logs a - LEFT JOIN users u ON a.user_id = u.id - WHERE a.resource_type IN ('content', 'collections', 'users', 'media') - ORDER BY a.created_at DESC - LIMIT ? - `); - const { results } = await activityStmt.bind(limit).all(); - const activities = (results || []).map((row) => { - const userName = row.first_name && row.last_name ? `${row.first_name} ${row.last_name}` : row.email || "System"; - let description = ""; - if (row.action === "create") { - description = `Created new ${row.resource_type}`; - } else if (row.action === "update") { - description = `Updated ${row.resource_type}`; - } else if (row.action === "delete") { - description = `Deleted ${row.resource_type}`; - } else { - description = `${row.action} ${row.resource_type}`; - } - return { - id: row.id, - type: row.resource_type, - action: row.action, - description, - timestamp: new Date(Number(row.created_at)).toISOString(), - user: userName - }; - }); - const html8 = renderRecentActivity(activities); - return c.html(html8); - } catch (error) { - console.error("Error fetching recent activity:", error); - const html8 = renderRecentActivity([]); - return c.html(html8); - } -}); -router.get("/api/metrics", async (c) => { - return c.json({ - requestsPerSecond: chunkRCQ2HIQD_cjs.metricsTracker.getRequestsPerSecond(), - totalRequests: chunkRCQ2HIQD_cjs.metricsTracker.getTotalRequests(), - averageRPS: Number(chunkRCQ2HIQD_cjs.metricsTracker.getAverageRPS().toFixed(2)), - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -router.get("/system-status", async (c) => { - try { - const html8 = ` -
-
-
-
-
- API Status - - - -
-

Operational

-
-
- -
-
-
-
- Database - - - -
-

Connected

-
-
- -
-
-
-
- R2 Storage - - - -
-

Available

-
-
- -
-
-
-
- KV Cache - - - -
-

Ready

-
-
-
- `; - return c.html(html8); - } catch (error) { - console.error("Error fetching system status:", error); - return c.html('
Failed to load system status
'); - } -}); - -// src/templates/pages/admin-collections-list.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); - -// src/templates/components/table.template.ts -function renderTable2(data) { - const tableId = data.tableId || `table-${Math.random().toString(36).substr(2, 9)}`; - if (data.rows.length === 0) { - return ` -
-
- - - -

${data.emptyMessage || "No data available"}

-
-
- `; - } - return ` -
- ${data.title ? ` -
-

${data.title}

-
- ` : ""} -
- - - - ${data.selectable ? ` - - ` : ""} - ${data.columns.map((column, index) => { - const isFirst = index === 0 && !data.selectable; - const isLast = index === data.columns.length - 1; - return ` - - `; - }).join("")} - - - - ${data.rows.map((row, rowIndex) => { - if (!row) return ""; - const clickableClass = data.rowClickable ? "cursor-pointer" : ""; - const clickHandler = data.rowClickable && data.rowClickUrl ? `onclick="window.location.href='${data.rowClickUrl(row)}'"` : ""; - return ` - - ${data.selectable ? ` - - ` : ""} - ${data.columns.map((column, colIndex) => { - const value = row[column.key]; - const displayValue = column.render ? column.render(value, row) : value; - const stopPropagation = column.key === "actions" ? 'onclick="event.stopPropagation()"' : ""; - const isFirst = colIndex === 0 && !data.selectable; - const isLast = colIndex === data.columns.length - 1; - return ` - - `; - }).join("")} - - `; - }).join("")} - -
-
-
- - - - - -
-
-
- ${column.sortable ? ` - - ` : column.label} -
-
-
- - - - - -
-
-
- ${displayValue || ""} -
-
- - -
- `; -} - -// src/templates/pages/admin-collections-list.template.ts -function renderCollectionsListPage(data) { - const tableData = { - tableId: "collections-table", - rowClickable: true, - rowClickUrl: (collection) => `/admin/collections/${collection.id}`, - columns: [ - { - key: "name", - label: "Name", - sortable: true, - sortType: "string", - render: (_value, collection) => ` -
- - ${collection.name} - - ${collection.managed ? ` - - - - - Config - - ` : ""} -
- ` - }, - { - key: "display_name", - label: "Display Name", - sortable: true, - sortType: "string" - }, - { - key: "description", - label: "Description", - sortable: true, - sortType: "string", - render: (_value, collection) => collection.description || '-' - }, - { - key: "field_count", - label: "Fields", - sortable: true, - sortType: "number", - render: (_value, collection) => { - const count = collection.field_count || 0; - return ` -
- - ${count} ${count === 1 ? "field" : "fields"} - -
- `; - } - }, - { - key: "managed", - label: "Source", - sortable: true, - sortType: "string", - render: (_value, collection) => { - if (collection.managed) { - return ` -
- - - - Code -
- `; - } else { - return ` -
- - - - - - Database -
- `; - } - } - }, - { - key: "formattedDate", - label: "Created", - sortable: true, - sortType: "date" - }, - { - key: "actions", - label: "Content", - sortable: false, - render: (_value, collection) => { - if (!collection || !collection.id) return '-'; - return ` - - `; - } - } - ], - rows: data.collections, - emptyMessage: "No collections found." - }; - const pageContent = ` -
- -
-
-

Collections

-

Manage your content collections and their schemas

-
- -
- - -
- -
- -
-
-
-
-
-
- -
- - - -
- -
- -
- -
-
- ${data.collections.length} ${data.collections.length === 1 ? "collection" : "collections"} - -
-
-
-
-
- - -
- ${renderTable2(tableData)} -
- - - ${data.collections.length === 0 ? ` -
- - - -

No collections found

-

Get started by creating your first collection

- -
- ` : ""} -
- `; - const layoutData = { - title: "Collections", - pageTitle: "Collections", - currentPath: "/admin/collections", - user: data.user, - version: data.version, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/pages/admin-collections-form.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function getFieldTypeBadge(fieldType) { - const typeLabels = { - "text": "Text", - "slug": "URL Slug", - "richtext": "Rich Text (TinyMCE)", - "quill": "Rich Text (Quill)", - "mdxeditor": "EasyMDX", - "number": "Number", - "boolean": "Boolean", - "date": "Date", - "select": "Select", - "media": "Media", - "reference": "Reference" - }; - const typeColors = { - "text": "bg-blue-500/10 dark:bg-blue-400/10 text-blue-700 dark:text-blue-300 ring-blue-500/20 dark:ring-blue-400/20", - "slug": "bg-sky-500/10 dark:bg-sky-400/10 text-sky-700 dark:text-sky-300 ring-sky-500/20 dark:ring-sky-400/20", - "richtext": "bg-purple-500/10 dark:bg-purple-400/10 text-purple-700 dark:text-purple-300 ring-purple-500/20 dark:ring-purple-400/20", - "quill": "bg-purple-500/10 dark:bg-purple-400/10 text-purple-700 dark:text-purple-300 ring-purple-500/20 dark:ring-purple-400/20", - "mdxeditor": "bg-purple-500/10 dark:bg-purple-400/10 text-purple-700 dark:text-purple-300 ring-purple-500/20 dark:ring-purple-400/20", - "number": "bg-green-500/10 dark:bg-green-400/10 text-green-700 dark:text-green-300 ring-green-500/20 dark:ring-green-400/20", - "boolean": "bg-amber-500/10 dark:bg-amber-400/10 text-amber-700 dark:text-amber-300 ring-amber-500/20 dark:ring-amber-400/20", - "date": "bg-cyan-500/10 dark:bg-cyan-400/10 text-cyan-700 dark:text-cyan-300 ring-cyan-500/20 dark:ring-cyan-400/20", - "select": "bg-indigo-500/10 dark:bg-indigo-400/10 text-indigo-700 dark:text-indigo-300 ring-indigo-500/20 dark:ring-indigo-400/20", - "media": "bg-rose-500/10 dark:bg-rose-400/10 text-rose-700 dark:text-rose-300 ring-rose-500/20 dark:ring-rose-400/20", - "reference": "bg-teal-500/10 dark:bg-teal-400/10 text-teal-700 dark:text-teal-300 ring-teal-500/20 dark:ring-teal-400/20" - }; - const label = typeLabels[fieldType] || fieldType; - const color = typeColors[fieldType] || "bg-zinc-500/10 dark:bg-zinc-400/10 text-zinc-700 dark:text-zinc-300 ring-zinc-500/20 dark:ring-zinc-400/20"; - return `${label}`; -} -function renderCollectionFormPage(data) { - console.log("[renderCollectionFormPage] editorPlugins:", data.editorPlugins); - const isEdit = data.isEdit || !!data.id; - const title = isEdit ? "Edit Collection" : "Create New Collection"; - const subtitle = isEdit ? `Update collection: ${data.display_name}` : "Define a new content collection with custom fields and settings."; - const fieldsWithData = (data.fields || []).map((field) => ({ - ...field, - dataFieldJSON: JSON.stringify(JSON.stringify(field)) - })); - const fields = [ - { - name: "displayName", - label: "Display Name", - type: "text", - value: data.display_name || "", - placeholder: "Blog Posts", - required: true, - readonly: data.managed, - className: data.managed ? "bg-zinc-100 dark:bg-zinc-800 text-zinc-500 dark:text-zinc-400 cursor-not-allowed" : "" - }, - { - name: "name", - label: "Collection Name", - type: "text", - value: data.name || "", - placeholder: "blog_posts", - required: true, - readonly: isEdit, - helpText: isEdit ? "Collection name cannot be changed" : "Lowercase letters, numbers, and underscores only", - className: isEdit ? "bg-zinc-100 dark:bg-zinc-800 text-zinc-500 dark:text-zinc-400 cursor-not-allowed" : "" - }, - { - name: "description", - label: "Description", - type: "textarea", - value: data.description || "", - placeholder: "Description of this collection...", - rows: 3, - readonly: data.managed, - className: data.managed ? "bg-zinc-100 dark:bg-zinc-800 text-zinc-500 dark:text-zinc-400 cursor-not-allowed" : "" - } - ]; - const formData = { - id: "collection-form", - ...isEdit ? { hxPut: `/admin/collections/${data.id}`, action: `/admin/collections/${data.id}`, method: "PUT" } : { hxPost: "/admin/collections", action: "/admin/collections" }, - hxTarget: "#form-messages", - fields, - submitButtons: data.managed ? [] : [ - { - label: isEdit ? "Update Collection" : "Create Collection", - type: "submit", - className: "btn-primary" - } - ] - }; - const pageContent = ` -
- - ${data.managed ? ` -
-
- - - -
-

- Config-Managed Collection -

-
-

This collection is managed by a configuration file and cannot be edited through the admin interface.

-

- Config file: - - src/collections/${data.name}.collection.ts - -

-

- To modify this collection's schema, edit the configuration file directly in your code editor. -

-
-
-
-
- ` : ""} - - -
-
-

${title}

-

${subtitle}

-
- -
- - -
- -
-
-
- - - -
-
-

Collection Details

-

Configure your collection settings below

-
-
-
- - -
-
- ${data.error ? renderAlert2({ type: "error", message: data.error, dismissible: true }) : ""} - ${data.success ? renderAlert2({ type: "success", message: data.success, dismissible: true }) : ""} - - - - - ${chunkSHCYIZAN_cjs.renderForm(formData)} - - ${isEdit && data.managed ? ` - -
-
-

Collection Fields

-

Fields defined in the configuration file (read-only)

-
- - -
- ${fieldsWithData.map((field) => ` -
-
-
-
-
- ${field.field_label} - ${getFieldTypeBadge(field.field_type)} - ${field.is_required ? ` - - Required - - ` : ""} - ${field.is_searchable ? ` - - Searchable - - ` : ""} -
-
- ${field.field_name} -
-
-
-
-
- `).join("")} - - ${(data.fields || []).length === 0 ? ` -
- - - -

No fields defined

-

Add fields to your collection configuration file to see them here.

-
- ` : ""} -
-
- ` : ""} - - ${isEdit && !data.managed ? ` - -
-
-
-

Collection Fields

-

Define the fields that content in this collection will have

-
- -
- - -
- ${fieldsWithData.map((field) => ` -
-
-
-
- - - -
-
-
- ${field.field_label} - ${getFieldTypeBadge(field.field_type)} - ${field.is_required ? ` - - Required - - ` : ""} - ${field.is_searchable ? ` - - Searchable - - ` : ""} -
-
- Field name: ${field.field_name} -
-
-
-
- - -
-
-
- `).join("")} - - ${(data.fields || []).length === 0 ? ` -
- - - -

No fields defined

-

Add your first field to get started

-
- ` : ""} -
-
- ` : ""} - - ${!isEdit ? ` -
-
- - - -
-

- Create Collection First -

-

- After creating the collection, you'll be able to add and configure custom fields. -

-
-
-
- ` : ""} - - -
- - - - - ${data.managed ? "Back to Collections" : "Cancel"} - - - ${isEdit && !data.managed ? ` - - ` : ""} -
-
-
-
- - - - - - - - ${renderConfirmationDialog2({ - id: "delete-field-confirm", - title: "Delete Field", - message: "Are you sure you want to delete this field? This action cannot be undone.", - confirmText: "Delete", - cancelText: "Cancel", - iconColor: "red", - confirmClass: "bg-red-500 hover:bg-red-400", - onConfirm: "performDeleteField()" - })} - - ${getConfirmationDialogScript2()} - `; - const layoutData = { - title, - pageTitle: "Collections", - currentPath: "/admin/collections", - user: data.user, - version: data.version, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/routes/admin-collections.ts -var adminCollectionsRoutes = new hono.Hono(); -adminCollectionsRoutes.use("*", chunkDVQA5II3_cjs.requireAuth()); -adminCollectionsRoutes.get("/", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const url = new URL(c.req.url); - const search = url.searchParams.get("search") || ""; - let stmt; - let results; - if (search) { - stmt = db.prepare(` - SELECT id, name, display_name, description, created_at, managed, schema - FROM collections - WHERE is_active = 1 - AND (name LIKE ? OR display_name LIKE ? OR description LIKE ?) - ORDER BY created_at DESC - `); - const searchParam = `%${search}%`; - const queryResults = await stmt.bind(searchParam, searchParam, searchParam).all(); - results = queryResults.results; - } else { - stmt = db.prepare("SELECT id, name, display_name, description, created_at, managed, schema FROM collections WHERE is_active = 1 ORDER BY created_at DESC"); - const queryResults = await stmt.all(); - results = queryResults.results; - } - const fieldCountStmt = db.prepare("SELECT collection_id, COUNT(*) as count FROM content_fields GROUP BY collection_id"); - const { results: fieldCountResults } = await fieldCountStmt.all(); - const fieldCounts = new Map((fieldCountResults || []).map((row) => [String(row.collection_id), Number(row.count)])); - const collections = (results || []).filter((row) => row && row.id).map((row) => { - let fieldCount = 0; - if (row.schema) { - try { - const schema = typeof row.schema === "string" ? JSON.parse(row.schema) : row.schema; - if (schema && schema.properties) { - fieldCount = Object.keys(schema.properties).length; - } - } catch (e) { - fieldCount = fieldCounts.get(String(row.id)) || 0; - } - } else { - fieldCount = fieldCounts.get(String(row.id)) || 0; - } - return { - id: String(row.id || ""), - name: String(row.name || ""), - display_name: String(row.display_name || ""), - description: row.description ? String(row.description) : void 0, - created_at: Number(row.created_at || 0), - formattedDate: row.created_at ? new Date(Number(row.created_at)).toLocaleDateString() : "Unknown", - field_count: fieldCount, - managed: row.managed === 1 - }; - }); - const pageData = { - collections, - search, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion") - }; - return c.html(renderCollectionsListPage(pageData)); - } catch (error) { - console.error("Error fetching collections:", error); - const errorMessage = error instanceof Error ? error.message : String(error); - return c.html(html.html`

Error loading collections: ${errorMessage}

`); - } -}); -adminCollectionsRoutes.get("/new", async (c) => { - const user = c.get("user"); - const db = c.env.DB; - const [tinymceActive, quillActive, mdxeditorActive] = await Promise.all([ - isPluginActive2(db, "tinymce-plugin"), - isPluginActive2(db, "quill-editor"), - isPluginActive2(db, "easy-mdx") - ]); - console.log("[Collections /new] Editor plugins status:", { - tinymce: tinymceActive, - quill: quillActive, - easyMdx: mdxeditorActive - }); - const formData = { - isEdit: false, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion"), - editorPlugins: { - tinymce: tinymceActive, - quill: quillActive, - easyMdx: mdxeditorActive - } - }; - return c.html(renderCollectionFormPage(formData)); -}); -adminCollectionsRoutes.post("/", async (c) => { - try { - const formData = await c.req.formData(); - const name = formData.get("name"); - const displayName = formData.get("displayName"); - const description = formData.get("description"); - const isHtmx = c.req.header("HX-Request") === "true"; - if (!name || !displayName) { - const errorMsg = "Name and display name are required."; - if (isHtmx) { - return c.html(html.html` -
- ${errorMsg} -
- `); - } else { - return c.redirect("/admin/collections/new"); - } - } - if (!/^[a-z0-9_]+$/.test(name)) { - const errorMsg = "Collection name must contain only lowercase letters, numbers, and underscores."; - if (isHtmx) { - return c.html(html.html` -
- ${errorMsg} -
- `); - } else { - return c.redirect("/admin/collections/new"); - } - } - const db = c.env.DB; - const existingStmt = db.prepare("SELECT id FROM collections WHERE name = ?"); - const existing = await existingStmt.bind(name).first(); - if (existing) { - const errorMsg = "A collection with this name already exists."; - if (isHtmx) { - return c.html(html.html` -
- ${errorMsg} -
- `); - } else { - return c.redirect("/admin/collections/new"); - } - } - const basicSchema = { - type: "object", - properties: { - title: { - type: "string", - title: "Title", - required: true - }, - content: { - type: "string", - title: "Content", - format: "richtext" - }, - status: { - type: "string", - title: "Status", - enum: ["draft", "published", "archived"], - default: "draft" - } - }, - required: ["title"] - }; - const collectionId = crypto.randomUUID(); - const now = Date.now(); - const insertStmt = db.prepare(` - INSERT INTO collections (id, name, display_name, description, schema, is_active, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - `); - await insertStmt.bind( - collectionId, - name, - displayName, - description || null, - JSON.stringify(basicSchema), - 1, - // is_active - now, - now - ).run(); - if (c.env.CACHE_KV) { - try { - await c.env.CACHE_KV.delete("cache:collections:all"); - await c.env.CACHE_KV.delete(`cache:collection:${name}`); - } catch (e) { - console.error("Error clearing cache:", e); - } - } - if (isHtmx) { - return c.html(html.html` -
- Collection created successfully! Redirecting to edit mode... - -
- `); - } else { - return c.redirect(`/admin/collections/${collectionId}`); - } - } catch (error) { - console.error("Error creating collection:", error); - const isHtmx = c.req.header("HX-Request") === "true"; - if (isHtmx) { - return c.html(html.html` -
- Failed to create collection. Please try again. -
- `); - } else { - return c.redirect("/admin/collections/new"); - } - } -}); -adminCollectionsRoutes.get("/:id", async (c) => { - const db = c.env.DB; - try { - const id = c.req.param("id"); - const user = c.get("user"); - const stmt = db.prepare("SELECT * FROM collections WHERE id = ?"); - const collection = await stmt.bind(id).first(); - if (!collection) { - const [tinymceActive2, quillActive2, mdxeditorActive2] = await Promise.all([ - isPluginActive2(db, "tinymce-plugin"), - isPluginActive2(db, "quill-editor"), - isPluginActive2(db, "easy-mdx") - ]); - const formData2 = { - isEdit: true, - error: "Collection not found.", - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion"), - editorPlugins: { - tinymce: tinymceActive2, - quill: quillActive2, - easyMdx: mdxeditorActive2 - } - }; - return c.html(renderCollectionFormPage(formData2)); - } - let fields = []; - if (collection.schema) { - try { - const schema = typeof collection.schema === "string" ? JSON.parse(collection.schema) : collection.schema; - if (schema && schema.properties) { - let fieldOrder = 0; - fields = Object.entries(schema.properties).map(([fieldName, fieldConfig]) => { - let fieldType = fieldConfig.type || "string"; - if (fieldConfig.enum) { - fieldType = "select"; - } else if (fieldConfig.format === "richtext") { - fieldType = "richtext"; - } else if (fieldConfig.format === "media") { - fieldType = "media"; - } else if (fieldConfig.format === "date-time") { - fieldType = "date"; - } else if (fieldConfig.type === "slug" || fieldConfig.format === "slug") { - fieldType = "slug"; - } - return { - id: `schema-${fieldName}`, - field_name: fieldName, - field_type: fieldType, - field_label: fieldConfig.title || fieldName, - field_options: fieldConfig, - field_order: fieldOrder++, - is_required: fieldConfig.required === true || schema.required && schema.required.includes(fieldName), - is_searchable: fieldConfig.searchable === true || false - }; - }); - } - } catch (e) { - console.error("Error parsing collection schema:", e); - } - } - if (fields.length === 0) { - const fieldsStmt = db.prepare(` - SELECT * FROM content_fields - WHERE collection_id = ? - ORDER BY field_order ASC - `); - const { results: fieldsResults } = await fieldsStmt.bind(id).all(); - fields = (fieldsResults || []).map((row) => { - let fieldOptions = {}; - if (row.field_options) { - try { - fieldOptions = typeof row.field_options === "string" ? JSON.parse(row.field_options) : row.field_options; - } catch (e) { - console.error("Error parsing field_options for field:", row.field_name, e); - fieldOptions = {}; - } - } - return { - id: row.id, - field_name: row.field_name, - field_type: row.field_type, - field_label: row.field_label, - field_options: fieldOptions, - field_order: row.field_order, - is_required: row.is_required === 1, - is_searchable: row.is_searchable === 1 - }; - }); - } - const [tinymceActive, quillActive, mdxeditorActive] = await Promise.all([ - isPluginActive2(db, "tinymce-plugin"), - isPluginActive2(db, "quill-editor"), - isPluginActive2(db, "easy-mdx") - ]); - console.log("[Collections /:id] Editor plugins status:", { - tinymce: tinymceActive, - quill: quillActive, - easyMdx: mdxeditorActive - }); - const formData = { - id: collection.id, - name: collection.name, - display_name: collection.display_name, - description: collection.description, - fields, - managed: collection.managed === 1, - isEdit: true, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion"), - editorPlugins: { - tinymce: tinymceActive, - quill: quillActive, - easyMdx: mdxeditorActive - } - }; - return c.html(renderCollectionFormPage(formData)); - } catch (error) { - console.error("Error fetching collection:", error); - const user = c.get("user"); - const [tinymceActive, quillActive, mdxeditorActive] = await Promise.all([ - isPluginActive2(db, "tinymce-plugin"), - isPluginActive2(db, "quill-editor"), - isPluginActive2(db, "easy-mdx") - ]); - const formData = { - isEdit: true, - error: "Failed to load collection.", - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion"), - editorPlugins: { - tinymce: tinymceActive, - quill: quillActive, - easyMdx: mdxeditorActive - } - }; - return c.html(renderCollectionFormPage(formData)); - } -}); -adminCollectionsRoutes.put("/:id", async (c) => { - try { - const id = c.req.param("id"); - const formData = await c.req.formData(); - const displayName = formData.get("displayName"); - const description = formData.get("description"); - if (!displayName) { - return c.html(html.html` -
- Display name is required. -
- `); - } - const db = c.env.DB; - const updateStmt = db.prepare(` - UPDATE collections - SET display_name = ?, description = ?, updated_at = ? - WHERE id = ? - `); - await updateStmt.bind(displayName, description || null, Date.now(), id).run(); - return c.html(html.html` -
- Collection updated successfully! -
- `); - } catch (error) { - console.error("Error updating collection:", error); - return c.html(html.html` -
- Failed to update collection. Please try again. -
- `); - } -}); -adminCollectionsRoutes.delete("/:id", async (c) => { - try { - const id = c.req.param("id"); - const db = c.env.DB; - const contentStmt = db.prepare("SELECT COUNT(*) as count FROM content WHERE collection_id = ?"); - const contentResult = await contentStmt.bind(id).first(); - if (contentResult && contentResult.count > 0) { - return c.html(html.html` -
- Cannot delete collection: it contains ${contentResult.count} content item(s). Delete all content first. -
- `); - } - const deleteFieldsStmt = db.prepare("DELETE FROM content_fields WHERE collection_id = ?"); - await deleteFieldsStmt.bind(id).run(); - const deleteStmt = db.prepare("DELETE FROM collections WHERE id = ?"); - await deleteStmt.bind(id).run(); - return c.html(html.html` - - `); - } catch (error) { - console.error("Error deleting collection:", error); - return c.html(html.html` -
- Failed to delete collection. Please try again. -
- `); - } -}); -adminCollectionsRoutes.post("/:id/fields", async (c) => { - try { - const collectionId = c.req.param("id"); - const formData = await c.req.formData(); - const fieldName = formData.get("field_name"); - const fieldType = formData.get("field_type"); - const fieldLabel = formData.get("field_label"); - const isRequired = formData.get("is_required") === "1"; - const isSearchable = formData.get("is_searchable") === "1"; - const fieldOptions = formData.get("field_options") || "{}"; - if (!fieldName || !fieldType || !fieldLabel) { - return c.json({ success: false, error: "Field name, type, and label are required." }); - } - if (!/^[a-z0-9_]+$/.test(fieldName)) { - return c.json({ success: false, error: "Field name must contain only lowercase letters, numbers, and underscores." }); - } - const db = c.env.DB; - const getCollectionStmt = db.prepare("SELECT * FROM collections WHERE id = ?"); - const collection = await getCollectionStmt.bind(collectionId).first(); - if (!collection) { - return c.json({ success: false, error: "Collection not found." }); - } - let schema = collection.schema ? typeof collection.schema === "string" ? JSON.parse(collection.schema) : collection.schema : null; - if (schema && schema.properties && schema.properties[fieldName]) { - return c.json({ success: false, error: "A field with this name already exists." }); - } - const existingStmt = db.prepare("SELECT id FROM content_fields WHERE collection_id = ? AND field_name = ?"); - const existing = await existingStmt.bind(collectionId, fieldName).first(); - if (existing) { - return c.json({ success: false, error: "A field with this name already exists." }); - } - let parsedOptions = {}; - try { - parsedOptions = fieldOptions ? JSON.parse(fieldOptions) : {}; - } catch (e) { - console.error("Error parsing field options:", e); - } - if (schema) { - if (!schema.properties) { - schema.properties = {}; - } - if (!schema.required) { - schema.required = []; - } - const fieldConfig = { - type: fieldType === "number" ? "number" : fieldType === "boolean" ? "boolean" : "string", - title: fieldLabel, - searchable: isSearchable, - ...parsedOptions - }; - if (fieldType === "richtext") { - fieldConfig.format = "richtext"; - } else if (fieldType === "date") { - fieldConfig.format = "date-time"; - } else if (fieldType === "select") { - fieldConfig.enum = parsedOptions.options || []; - } else if (fieldType === "media") { - fieldConfig.format = "media"; - } else if (fieldType === "slug") { - fieldConfig.type = "slug"; - fieldConfig.format = "slug"; - } else if (fieldType === "quill") { - fieldConfig.type = "quill"; - } else if (fieldType === "mdxeditor") { - fieldConfig.type = "mdxeditor"; - } else if (fieldType === "reference") { - fieldConfig.type = "reference"; - } - schema.properties[fieldName] = fieldConfig; - if (isRequired && !schema.required.includes(fieldName)) { - schema.required.push(fieldName); - } - const updateSchemaStmt = db.prepare(` - UPDATE collections - SET schema = ?, updated_at = ? - WHERE id = ? - `); - await updateSchemaStmt.bind(JSON.stringify(schema), Date.now(), collectionId).run(); - console.log("[Add Field] Added field to schema:", fieldName, fieldConfig); - return c.json({ success: true, fieldId: `schema-${fieldName}` }); - } - const orderStmt = db.prepare("SELECT MAX(field_order) as max_order FROM content_fields WHERE collection_id = ?"); - const orderResult = await orderStmt.bind(collectionId).first(); - const nextOrder = (orderResult?.max_order || 0) + 1; - const fieldId = crypto.randomUUID(); - const now = Date.now(); - const insertStmt = db.prepare(` - INSERT INTO content_fields ( - id, collection_id, field_name, field_type, field_label, - field_options, field_order, is_required, is_searchable, - created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await insertStmt.bind( - fieldId, - collectionId, - fieldName, - fieldType, - fieldLabel, - fieldOptions, - nextOrder, - isRequired ? 1 : 0, - isSearchable ? 1 : 0, - now, - now - ).run(); - return c.json({ success: true, fieldId }); - } catch (error) { - console.error("Error adding field:", error); - return c.json({ success: false, error: "Failed to add field." }); - } -}); -adminCollectionsRoutes.put("/:collectionId/fields/:fieldId", async (c) => { - try { - const fieldId = c.req.param("fieldId"); - const collectionId = c.req.param("collectionId"); - const formData = await c.req.formData(); - const fieldLabel = formData.get("field_label"); - const fieldType = formData.get("field_type"); - const isRequiredValues = formData.getAll("is_required"); - const isSearchableValues = formData.getAll("is_searchable"); - const isRequired = isRequiredValues[isRequiredValues.length - 1] === "1"; - const isSearchable = isSearchableValues[isSearchableValues.length - 1] === "1"; - const fieldOptions = formData.get("field_options") || "{}"; - console.log("[Field Update] Field ID:", fieldId); - console.log("[Field Update] Form data received:", { - field_label: fieldLabel, - field_type: fieldType, - is_required: formData.get("is_required"), - is_searchable: formData.get("is_searchable"), - field_options: fieldOptions - }); - if (!fieldLabel) { - return c.json({ success: false, error: "Field label is required." }); - } - const db = c.env.DB; - if (fieldId.startsWith("schema-")) { - const fieldName = fieldId.replace("schema-", ""); - console.log("[Field Update] Updating schema field:", fieldName); - const getCollectionStmt = db.prepare("SELECT * FROM collections WHERE id = ?"); - const collection = await getCollectionStmt.bind(collectionId).first(); - if (!collection) { - return c.json({ success: false, error: "Collection not found." }); - } - let schema = typeof collection.schema === "string" ? JSON.parse(collection.schema) : collection.schema; - if (!schema) { - schema = { type: "object", properties: {}, required: [] }; - } - if (!schema.properties) { - schema.properties = {}; - } - if (!schema.required) { - schema.required = []; - } - if (schema.properties[fieldName]) { - let parsedFieldOptions = {}; - try { - parsedFieldOptions = JSON.parse(fieldOptions); - } catch (e) { - console.error("[Field Update] Error parsing field options:", e); - } - const updatedFieldConfig = { - ...schema.properties[fieldName], - ...parsedFieldOptions, - type: fieldType, - title: fieldLabel, - searchable: isSearchable - }; - if (isRequired) { - updatedFieldConfig.required = true; - } else { - delete updatedFieldConfig.required; - } - schema.properties[fieldName] = updatedFieldConfig; - const requiredIndex = schema.required.indexOf(fieldName); - console.log("[Field Update] Required field handling:", { - fieldName, - isRequired, - currentRequiredArray: schema.required, - requiredIndex - }); - if (isRequired && requiredIndex === -1) { - schema.required.push(fieldName); - console.log("[Field Update] Added field to required array"); - } else if (!isRequired && requiredIndex !== -1) { - schema.required.splice(requiredIndex, 1); - console.log("[Field Update] Removed field from required array"); - } - console.log("[Field Update] Final required array:", schema.required); - console.log("[Field Update] Final field config:", schema.properties[fieldName]); - } - const updateCollectionStmt = db.prepare(` - UPDATE collections - SET schema = ?, updated_at = ? - WHERE id = ? - `); - const result2 = await updateCollectionStmt.bind(JSON.stringify(schema), Date.now(), collectionId).run(); - console.log("[Field Update] Schema update result:", { - success: result2.success, - changes: result2.meta?.changes - }); - return c.json({ success: true }); - } - const updateStmt = db.prepare(` - UPDATE content_fields - SET field_label = ?, field_type = ?, field_options = ?, is_required = ?, is_searchable = ?, updated_at = ? - WHERE id = ? - `); - const result = await updateStmt.bind(fieldLabel, fieldType, fieldOptions, isRequired ? 1 : 0, isSearchable ? 1 : 0, Date.now(), fieldId).run(); - console.log("[Field Update] Update result:", { - success: result.success, - meta: result.meta, - changes: result.meta?.changes, - last_row_id: result.meta?.last_row_id - }); - const verifyStmt = db.prepare("SELECT * FROM content_fields WHERE id = ?"); - const verifyResult = await verifyStmt.bind(fieldId).first(); - console.log("[Field Update] Verification - field after update:", verifyResult); - console.log("[Field Update] Successfully updated field with type:", fieldType); - return c.json({ success: true }); - } catch (error) { - console.error("Error updating field:", error); - return c.json({ success: false, error: "Failed to update field." }); - } -}); -adminCollectionsRoutes.delete("/:collectionId/fields/:fieldId", async (c) => { - try { - const fieldId = c.req.param("fieldId"); - const collectionId = c.req.param("collectionId"); - const db = c.env.DB; - if (fieldId.startsWith("schema-")) { - const fieldName = fieldId.replace("schema-", ""); - const getCollectionStmt = db.prepare("SELECT * FROM collections WHERE id = ?"); - const collection = await getCollectionStmt.bind(collectionId).first(); - if (!collection) { - return c.json({ success: false, error: "Collection not found." }); - } - let schema = typeof collection.schema === "string" ? JSON.parse(collection.schema) : collection.schema; - if (!schema || !schema.properties) { - return c.json({ success: false, error: "Field not found in schema." }); - } - if (schema.properties[fieldName]) { - delete schema.properties[fieldName]; - if (schema.required && Array.isArray(schema.required)) { - const requiredIndex = schema.required.indexOf(fieldName); - if (requiredIndex !== -1) { - schema.required.splice(requiredIndex, 1); - } - } - const updateCollectionStmt = db.prepare(` - UPDATE collections - SET schema = ?, updated_at = ? - WHERE id = ? - `); - await updateCollectionStmt.bind(JSON.stringify(schema), Date.now(), collectionId).run(); - console.log("[Delete Field] Removed field from schema:", fieldName); - return c.json({ success: true }); - } else { - return c.json({ success: false, error: "Field not found in schema." }); - } - } - const deleteStmt = db.prepare("DELETE FROM content_fields WHERE id = ?"); - await deleteStmt.bind(fieldId).run(); - return c.json({ success: true }); - } catch (error) { - console.error("Error deleting field:", error); - return c.json({ success: false, error: "Failed to delete field." }); - } -}); -adminCollectionsRoutes.post("/:collectionId/fields/reorder", async (c) => { - try { - const body = await c.req.json(); - const fieldIds = body.fieldIds; - if (!Array.isArray(fieldIds)) { - return c.json({ success: false, error: "Invalid field order data." }); - } - const db = c.env.DB; - for (let i = 0; i < fieldIds.length; i++) { - const updateStmt = db.prepare("UPDATE content_fields SET field_order = ?, updated_at = ? WHERE id = ?"); - await updateStmt.bind(i + 1, Date.now(), fieldIds[i]).run(); - } - return c.json({ success: true }); - } catch (error) { - console.error("Error reordering fields:", error); - return c.json({ success: false, error: "Failed to reorder fields." }); - } -}); - -// src/templates/pages/admin-settings.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderSettingsPage(data) { - const activeTab = data.activeTab || "general"; - const pageContent = ` -
- -
-
-

Settings

-

Manage your application settings and preferences

-
-
- - -
-
- -
-
- - -
-
- ${renderTabContent(activeTab, data.settings)} -
-
-
- - - - - ${renderConfirmationDialog2({ - id: "run-migrations-confirm", - title: "Run Migrations", - message: "Are you sure you want to run pending migrations? This action cannot be undone.", - confirmText: "Run Migrations", - cancelText: "Cancel", - iconColor: "blue", - confirmClass: "bg-blue-500 hover:bg-blue-400", - onConfirm: "performRunMigrations()" - })} - - ${getConfirmationDialogScript2()} - `; - const layoutData = { - title: "Settings", - pageTitle: "Settings", - currentPath: "/admin/settings", - user: data.user, - version: data.version, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} -function renderTabButton(tabId, label, iconPath, activeTab) { - const isActive = activeTab === tabId; - const baseClasses = "flex items-center space-x-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 whitespace-nowrap no-underline"; - const activeClasses = isActive ? "border-zinc-950 dark:border-white text-zinc-950 dark:text-white" : "border-transparent text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-300 hover:border-zinc-300 dark:hover:border-zinc-700"; - return ` - - - - - ${label} - - `; -} -function renderTabContent(activeTab, settings) { - switch (activeTab) { - case "general": - return renderGeneralSettings(settings?.general); - case "appearance": - return renderAppearanceSettings(settings?.appearance); - case "security": - return renderSecuritySettings(settings?.security); - case "notifications": - return renderNotificationSettings(settings?.notifications); - case "storage": - return renderStorageSettings(settings?.storage); - case "migrations": - return renderMigrationSettings(settings?.migrations); - case "database-tools": - return renderDatabaseToolsSettings(settings?.databaseTools); - default: - return renderGeneralSettings(settings?.general); - } -} -function renderGeneralSettings(settings) { - return ` -
-
-

General Settings

-

Configure basic application settings and preferences.

-
- -
-
-
- - -
- -
- - -
- -
- - -
-
- -
-
- - -
- -
- - -
- -
-
-
- - - - - -
-
-
- -
-
-
-
- - -
- -
-
- `; -} -function renderAppearanceSettings(settings) { - return ` -
- -
-
- - - -
-

Work in Progress

-

- This settings section is currently under development and provided for reference and design feedback only. Changes made here will not be saved. -

-
-
-
- -
-

Appearance Settings

-

Customize the look and feel of your application.

-
- -
-
-
- -
- - - -
-
- -
- -
- - -
-
- -
- - -
-
- -
-
- - -
- -
- - -
-
-
- - -
- -
-
- `; -} -function renderSecuritySettings(settings) { - return ` -
- -
-
- - - -
-

Work in Progress

-

- This settings section is currently under development and provided for reference and design feedback only. Changes made here will not be saved. -

-
-
-
- -
-

Security Settings

-

Configure security and authentication settings.

-
- -
-
-
-
-
- - - - - -
-
-
- -
-
- -
- - -
- -
- -
-
-
-
- - - - - -
-
-
- -
-
-
-
-
- - - - - -
-
-
- -
-
-
-
-
- - - - - -
-
-
- -
-
-
-
-
- -
-
- - -
- -
- - -

Leave empty to allow all IPs

-
-
-
- - -
- -
-
- `; -} -function renderNotificationSettings(settings) { - return ` -
- -
-
- - - -
-

Work in Progress

-

- This settings section is currently under development and provided for reference and design feedback only. Changes made here will not be saved. -

-
-
-
- -
-

Notification Settings

-

Configure how and when you receive notifications.

-
- -
-
-
-

Email Notifications

-
-
-
-
- - - - - -
-
-
- -
-
- -
-
-
- - - - - -
-
-
- -
-
- -
-
-
- - - - - -
-
-
- -
-
- -
-
-
- - - - - -
-
-
- -
-
-
-
-
- -
-
- - -
- -
-
- - - -
-
Notification Preferences
-

- Critical system alerts will always be sent immediately regardless of your frequency setting. -

-
-
-
-
-
- - -
- -
-
- `; -} -function renderStorageSettings(settings) { - return ` -
- -
-
- - - -
-

Work in Progress

-

- This settings section is currently under development and provided for reference and design feedback only. Changes made here will not be saved. -

-
-
-
- -
-

Storage Settings

-

Configure file storage and backup settings.

-
- -
-
-
- - -
- -
- - -
- -
- - -
-
- -
-
- - -
- -
- - -
- -
-
- - - -
-
Storage Status
-

- Current usage: 2.4 GB / 10 GB available -

-
-
-
-
-
- - -
- -
-
- `; -} -function renderMigrationSettings(settings) { - return ` -
-
-

Database Migrations

-

View and manage database migrations to keep your schema up to date.

-
- - -
-
-
-
-

Total Migrations

-

${settings?.totalMigrations || "0"}

-
- - - -
-
- -
-
-
-

Applied

-

${settings?.appliedMigrations || "0"}

-
- - - -
-
- -
-
-
-

Pending

-

${settings?.pendingMigrations || "0"}

-
- - - -
-
-
- - -
- - - - - -
- - -
-
-

Migration History

-

List of all available database migrations

-
- -
-
- - - -

Loading migration status...

-
-
-
-
- - - `; -} -function renderDatabaseToolsSettings(settings) { - return ` -
-
-

Database Tools

-

Manage database operations including backup, restore, and maintenance.

-
- - -
-
-
-
-

Total Tables

-

${settings?.totalTables || "0"}

-
-
- - - -
-
-
- -
-
-
-

Total Rows

-

${settings?.totalRows?.toLocaleString() || "0"}

-
-
- - - -
-
-
-
- - -
- -
-

Safe Operations

-
- - - - - -
-
-
- - -
-
-

Database Tables

-

Click on a table to view its data

-
- -
-
- - - -

Loading database statistics...

-
-
-
- - -
-
- - - -
-

Danger Zone

-

- These operations are destructive and cannot be undone. - Your admin account will be preserved, but all other data will be permanently deleted. -

-
- -
-
-
-
-
- `; -} - -// src/routes/admin-settings.ts -var adminSettingsRoutes = new hono.Hono(); -adminSettingsRoutes.use("*", chunkDVQA5II3_cjs.requireAuth()); -function getMockSettings(user) { - return { - general: { - siteName: "SonicJS AI", - siteDescription: "A modern headless CMS powered by AI", - adminEmail: user?.email || "admin@example.com", - timezone: "UTC", - language: "en", - maintenanceMode: false - }, - appearance: { - theme: "dark", - primaryColor: "#465FFF", - logoUrl: "", - favicon: "", - customCSS: "" - }, - security: { - twoFactorEnabled: false, - sessionTimeout: 30, - passwordRequirements: { - minLength: 8, - requireUppercase: true, - requireNumbers: true, - requireSymbols: false - }, - ipWhitelist: [] - }, - notifications: { - emailNotifications: true, - contentUpdates: true, - systemAlerts: true, - userRegistrations: false, - emailFrequency: "immediate" - }, - storage: { - maxFileSize: 10, - allowedFileTypes: ["jpg", "jpeg", "png", "gif", "pdf", "docx"], - storageProvider: "cloudflare", - backupFrequency: "daily", - retentionPeriod: 30 - }, - migrations: { - totalMigrations: 0, - appliedMigrations: 0, - pendingMigrations: 0, - lastApplied: void 0, - migrations: [] - }, - databaseTools: { - totalTables: 0, - totalRows: 0, - lastBackup: void 0, - databaseSize: "0 MB", - tables: [] - } - }; -} -adminSettingsRoutes.get("/", (c) => { - return c.redirect("/admin/settings/general"); -}); -adminSettingsRoutes.get("/general", async (c) => { - const user = c.get("user"); - const db = c.env.DB; - const settingsService = new chunkVNLR35GO_cjs.SettingsService(db); - const generalSettings = await settingsService.getGeneralSettings(user?.email); - const mockSettings = getMockSettings(user); - mockSettings.general = generalSettings; - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - settings: mockSettings, - activeTab: "general", - version: c.get("appVersion") - }; - return c.html(renderSettingsPage(pageData)); -}); -adminSettingsRoutes.get("/appearance", (c) => { - const user = c.get("user"); - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - settings: getMockSettings(user), - activeTab: "appearance", - version: c.get("appVersion") - }; - return c.html(renderSettingsPage(pageData)); -}); -adminSettingsRoutes.get("/security", (c) => { - const user = c.get("user"); - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - settings: getMockSettings(user), - activeTab: "security", - version: c.get("appVersion") - }; - return c.html(renderSettingsPage(pageData)); -}); -adminSettingsRoutes.get("/notifications", (c) => { - const user = c.get("user"); - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - settings: getMockSettings(user), - activeTab: "notifications", - version: c.get("appVersion") - }; - return c.html(renderSettingsPage(pageData)); -}); -adminSettingsRoutes.get("/storage", (c) => { - const user = c.get("user"); - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - settings: getMockSettings(user), - activeTab: "storage", - version: c.get("appVersion") - }; - return c.html(renderSettingsPage(pageData)); -}); -adminSettingsRoutes.get("/migrations", (c) => { - const user = c.get("user"); - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - settings: getMockSettings(user), - activeTab: "migrations", - version: c.get("appVersion") - }; - return c.html(renderSettingsPage(pageData)); -}); -adminSettingsRoutes.get("/database-tools", (c) => { - const user = c.get("user"); - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - settings: getMockSettings(user), - activeTab: "database-tools", - version: c.get("appVersion") - }; - return c.html(renderSettingsPage(pageData)); -}); -adminSettingsRoutes.get("/api/migrations/status", async (c) => { - try { - const db = c.env.DB; - const migrationService = new chunkFQSMNIY2_cjs.MigrationService(db); - const status = await migrationService.getMigrationStatus(); - return c.json({ - success: true, - data: status - }); - } catch (error) { - console.error("Error fetching migration status:", error); - return c.json({ - success: false, - error: "Failed to fetch migration status" - }, 500); - } -}); -adminSettingsRoutes.post("/api/migrations/run", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.json({ - success: false, - error: "Unauthorized. Admin access required." - }, 403); - } - const db = c.env.DB; - const migrationService = new chunkFQSMNIY2_cjs.MigrationService(db); - const result = await migrationService.runPendingMigrations(); - return c.json({ - success: result.success, - message: result.message, - applied: result.applied - }); - } catch (error) { - console.error("Error running migrations:", error); - return c.json({ - success: false, - error: "Failed to run migrations" - }, 500); - } -}); -adminSettingsRoutes.get("/api/migrations/validate", async (c) => { - try { - const db = c.env.DB; - const migrationService = new chunkFQSMNIY2_cjs.MigrationService(db); - const validation = await migrationService.validateSchema(); - return c.json({ - success: true, - data: validation - }); - } catch (error) { - console.error("Error validating schema:", error); - return c.json({ - success: false, - error: "Failed to validate schema" - }, 500); - } -}); -adminSettingsRoutes.get("/api/database-tools/stats", async (c) => { - try { - const db = c.env.DB; - const tablesQuery = await db.prepare(` - SELECT name FROM sqlite_master - WHERE type='table' - AND name NOT LIKE 'sqlite_%' - AND name NOT LIKE '_cf_%' - ORDER BY name - `).all(); - const tables = tablesQuery.results || []; - let totalRows = 0; - const tableStats = await Promise.all( - tables.map(async (table) => { - try { - const countResult = await db.prepare(`SELECT COUNT(*) as count FROM ${table.name}`).first(); - const rowCount = countResult?.count || 0; - totalRows += rowCount; - return { - name: table.name, - rowCount - }; - } catch (error) { - console.error(`Error counting rows in ${table.name}:`, error); - return { - name: table.name, - rowCount: 0 - }; - } - }) - ); - const estimatedSizeBytes = totalRows * 1024; - const databaseSizeMB = (estimatedSizeBytes / (1024 * 1024)).toFixed(2); - return c.json({ - success: true, - data: { - totalTables: tables.length, - totalRows, - databaseSize: `${databaseSizeMB} MB (estimated)`, - tables: tableStats - } - }); - } catch (error) { - console.error("Error fetching database stats:", error); - return c.json({ - success: false, - error: "Failed to fetch database statistics" - }, 500); - } -}); -adminSettingsRoutes.get("/api/database-tools/validate", async (c) => { - try { - const db = c.env.DB; - const integrityResult = await db.prepare("PRAGMA integrity_check").first(); - const isValid = integrityResult?.integrity_check === "ok"; - return c.json({ - success: true, - data: { - valid: isValid, - message: isValid ? "Database integrity check passed" : "Database integrity check failed" - } - }); - } catch (error) { - console.error("Error validating database:", error); - return c.json({ - success: false, - error: "Failed to validate database" - }, 500); - } -}); -adminSettingsRoutes.post("/api/database-tools/backup", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.json({ - success: false, - error: "Unauthorized. Admin access required." - }, 403); - } - return c.json({ - success: true, - message: "Database backup feature coming soon. Use Cloudflare Dashboard for backups." - }); - } catch (error) { - console.error("Error creating backup:", error); - return c.json({ - success: false, - error: "Failed to create backup" - }, 500); - } -}); -adminSettingsRoutes.post("/api/database-tools/truncate", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.json({ - success: false, - error: "Unauthorized. Admin access required." - }, 403); - } - const body = await c.req.json(); - const tablesToTruncate = body.tables || []; - if (!Array.isArray(tablesToTruncate) || tablesToTruncate.length === 0) { - return c.json({ - success: false, - error: "No tables specified for truncation" - }, 400); - } - const db = c.env.DB; - const results = []; - for (const tableName of tablesToTruncate) { - try { - await db.prepare(`DELETE FROM ${tableName}`).run(); - results.push({ table: tableName, success: true }); - } catch (error) { - console.error(`Error truncating ${tableName}:`, error); - results.push({ table: tableName, success: false, error: String(error) }); - } - } - return c.json({ - success: true, - message: `Truncated ${results.filter((r) => r.success).length} of ${tablesToTruncate.length} tables`, - results - }); - } catch (error) { - console.error("Error truncating tables:", error); - return c.json({ - success: false, - error: "Failed to truncate tables" - }, 500); - } -}); -adminSettingsRoutes.post("/general", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.json({ - success: false, - error: "Unauthorized. Admin access required." - }, 403); - } - const formData = await c.req.formData(); - const db = c.env.DB; - const settingsService = new chunkVNLR35GO_cjs.SettingsService(db); - const settings = { - siteName: formData.get("siteName"), - siteDescription: formData.get("siteDescription"), - adminEmail: formData.get("adminEmail"), - timezone: formData.get("timezone"), - language: formData.get("language"), - maintenanceMode: formData.get("maintenanceMode") === "true" - }; - if (!settings.siteName || !settings.siteDescription) { - return c.json({ - success: false, - error: "Site name and description are required" - }, 400); - } - const success = await settingsService.saveGeneralSettings(settings); - if (success) { - return c.json({ - success: true, - message: "General settings saved successfully!" - }); - } else { - return c.json({ - success: false, - error: "Failed to save settings" - }, 500); - } - } catch (error) { - console.error("Error saving general settings:", error); - return c.json({ - success: false, - error: "Failed to save settings. Please try again." - }, 500); - } -}); -adminSettingsRoutes.post("/", async (c) => { - return c.redirect("/admin/settings/general"); -}); - -// src/templates/pages/admin-forms-list.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderFormsListPage(data) { - const tableData = { - tableId: "forms-table", - rowClickable: true, - rowClickUrl: (form) => `/admin/forms/${form.id}/builder`, - columns: [ - { - key: "name", - label: "Name", - sortable: true, - sortType: "string", - render: (_value, form) => ` -
- - ${form.name} - -
- ` - }, - { - key: "display_name", - label: "Display Name", - sortable: true, - sortType: "string" - }, - { - key: "category", - label: "Category", - sortable: true, - sortType: "string", - render: (_value, form) => { - const categoryColors = { - "contact": "bg-blue-50 dark:bg-blue-500/10 text-blue-700 dark:text-blue-300 ring-blue-700/10 dark:ring-blue-400/20", - "survey": "bg-purple-50 dark:bg-purple-500/10 text-purple-700 dark:text-purple-300 ring-purple-700/10 dark:ring-purple-400/20", - "registration": "bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-300 ring-green-700/10 dark:ring-green-400/20", - "feedback": "bg-orange-50 dark:bg-orange-500/10 text-orange-700 dark:text-orange-300 ring-orange-700/10 dark:ring-orange-400/20", - "general": "bg-gray-50 dark:bg-gray-500/10 text-gray-700 dark:text-gray-300 ring-gray-700/10 dark:ring-gray-400/20" - }; - const colorClass = categoryColors[form.category] || categoryColors["general"]; - return ` - - ${form.category || "general"} - - `; - } - }, - { - key: "submission_count", - label: "Submissions", - sortable: true, - sortType: "number", - render: (_value, form) => { - const count = form.submission_count || 0; - return ` -
- - ${count} - -
- `; - } - }, - { - key: "is_active", - label: "Status", - sortable: true, - sortType: "string", - render: (_value, form) => { - if (form.is_active) { - return ` - - Active - - `; - } else { - return ` - - Inactive - - `; - } - } - }, - { - key: "formattedDate", - label: "Created", - sortable: true, - sortType: "date" - }, - { - key: "actions", - label: "Actions", - sortable: false, - render: (_value, form) => { - if (!form || !form.id) return '-'; - return ` - - `; - } - } - ], - rows: data.forms, - emptyMessage: "No forms found. Create your first form to get started!" - }; - const pageContent = ` -
- -
-
-

Forms

-

Create and manage forms with the visual form builder

-
- -
- - -
-
-
-
- - - -
-
-
-
Total Forms
-
${data.forms.length}
-
-
-
-
- -
-
-
- - - -
-
-
-
Active Forms
-
${data.forms.filter((f) => f.is_active).length}
-
-
-
-
- -
-
-
- - - -
-
-
-
Total Submissions
-
${data.forms.reduce((sum, f) => sum + (f.submission_count || 0), 0)}
-
-
-
-
-
- - -
-
-
- -
-
- -
- - ${data.search || data.category ? ` - - Clear - - ` : ""} -
-
- - -
- ${renderTable2(tableData)} -
-
- `; - const layoutData = { - title: "Forms", - content: pageContent, - user: data.user, - version: data.version - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/pages/admin-forms-builder.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function getTurnstileComponentScript() { - return ` - (function() { - 'use strict'; - - if (!window.Formio || !window.Formio.Components) { - console.error('Form.io library not loaded'); - return; - } - - const FieldComponent = Formio.Components.components.field; - - class TurnstileComponent extends FieldComponent { - static schema(...extend) { - return FieldComponent.schema({ - type: 'turnstile', - label: 'Turnstile Verification', - key: 'turnstile', - input: true, - persistent: false, - protected: true, - unique: false, - hidden: false, - clearOnHide: true, - tableView: false, - validate: { - required: false - }, - siteKey: '', - theme: 'auto', - size: 'normal', - action: '', - appearance: 'always', - errorMessage: 'Please complete the security verification' - }, ...extend); - } - - static get builderInfo() { - return { - title: 'Turnstile', - group: 'premium', - icon: 'fa fa-shield-alt', - weight: 120, - documentation: '/admin/forms/docs#turnstile', - schema: TurnstileComponent.schema() - }; - } - - constructor(component, options, data) { - super(component, options, data); - this.widgetId = null; - this.scriptLoaded = false; - } - - init() { - super.init(); - // Only load script if NOT in builder/edit mode - if (!this.options.editMode && !this.options.builder && !this.builderMode) { - this.loadTurnstileScript(); - } - } - - loadTurnstileScript() { - // Extra safety: never load in builder - if (this.options.editMode || this.options.builder || this.builderMode) { - console.log('Turnstile: Skipping script load in builder mode'); - return Promise.resolve(); - } - - if (window.turnstile) { - this.scriptLoaded = true; - return Promise.resolve(); - } - - if (this.scriptPromise) { - return this.scriptPromise; - } - - console.log('Turnstile: Loading script for form mode'); - this.scriptPromise = new Promise((resolve, reject) => { - const script = document.createElement('script'); - script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js'; - script.async = true; - script.defer = true; - script.onload = () => { - this.scriptLoaded = true; - resolve(); - }; - script.onerror = () => reject(new Error('Failed to load Turnstile')); - document.head.appendChild(script); - }); - - return this.scriptPromise; - } - - render() { - return super.render(\` -
-
- \${this.component.description ? \`
\${this.component.description}
\` : ''} -
- \`); - } - - attach(element) { - this.loadRefs(element, { - turnstileContainer: 'single', - turnstileWidget: 'single' - }); - - const superAttach = super.attach(element); - - // Check if we're in builder mode or form mode - if (this.options.editMode || this.options.builder) { - // Builder mode - show placeholder only - this.renderPlaceholder(); - } else { - // Form mode - render actual widget - this.loadTurnstileScript() - .then(() => this.renderWidget()) - .catch(err => { - console.error('Failed to load Turnstile:', err); - if (this.refs.turnstileWidget) { - this.refs.turnstileWidget.innerHTML = \` -
- Error: Failed to load security verification -
- \`; - } - }); - } - - return superAttach; - } - - renderPlaceholder() { - if (!this.refs.turnstileWidget) { - return; - } - - this.refs.turnstileWidget.innerHTML = \` -
-
\u{1F6E1}\uFE0F
-
Turnstile Verification
-
CAPTCHA-free bot protection by Cloudflare
-
Widget will appear here on the live form
-
- \`; - } - - renderWidget() { - if (!this.refs.turnstileWidget || !window.turnstile) { - return; - } - - this.refs.turnstileWidget.innerHTML = ''; - - const siteKey = this.component.siteKey || - (this.root && this.root.options && this.root.options.turnstileSiteKey) || - ''; - - if (!siteKey) { - this.refs.turnstileWidget.innerHTML = \` -
- \u26A0\uFE0F Configuration Required: Turnstile site key not configured. - Please enable the Turnstile plugin in Settings \u2192 Plugins. -
- \`; - return; - } - - try { - const self = this; - this.widgetId = window.turnstile.render(this.refs.turnstileWidget, { - sitekey: siteKey, - theme: this.component.theme || 'auto', - size: this.component.size || 'normal', - action: this.component.action || '', - appearance: this.component.appearance || 'always', - callback: function(token) { - self.updateValue(token); - self.triggerChange(); - }, - 'error-callback': function() { - self.updateValue(null); - self.setCustomValidity(self.component.errorMessage || 'Security verification failed'); - }, - 'expired-callback': function() { - self.updateValue(null); - self.setCustomValidity('Security verification expired. Please verify again.'); - }, - 'timeout-callback': function() { - self.updateValue(null); - self.setCustomValidity('Security verification timed out. Please try again.'); - } - }); - } catch (err) { - console.error('Failed to render Turnstile widget:', err); - this.refs.turnstileWidget.innerHTML = \` -
- Error: Failed to render security verification -
- \`; - } - } - - detach() { - if (this.widgetId !== null && window.turnstile) { - try { - window.turnstile.remove(this.widgetId); - this.widgetId = null; - } catch (err) { - console.error('Failed to remove Turnstile widget:', err); - } - } - return super.detach(); - } - - getValue() { - if (this.widgetId !== null && window.turnstile) { - return window.turnstile.getResponse(this.widgetId); - } - return this.dataValue; - } - - setValue(value, flags) { - const changed = super.setValue(value, flags); - return changed; - } - - getValueAsString(value) { - return value ? '\u2705 Verified' : '\u274C Not Verified'; - } - - isEmpty(value) { - return !value; - } - - updateValue(value, flags) { - const changed = super.updateValue(value, flags); - - if (value) { - this.setCustomValidity(''); - } - - return changed; - } - - checkValidity(data, dirty, row) { - const result = super.checkValidity(data, dirty, row); - - if (this.component.validate && this.component.validate.required) { - const value = this.getValue(); - if (!value) { - this.setCustomValidity(this.component.errorMessage || 'Please complete the security verification'); - return false; - } - } - - return result; - } - } - - Formio.Components.addComponent('turnstile', TurnstileComponent); - console.log('\u2705 Turnstile component registered with Form.io'); - window.TurnstileComponent = TurnstileComponent; - })(); - `; -} -function renderFormBuilderPage(data) { - const formioSchema = data.formio_schema || { components: [] }; - const googleMapsApiKey = data.google_maps_api_key || ""; - const turnstileSiteKey = data.turnstile_site_key || ""; - const pageContent = ` - - -
- -
-
-
- - - - - -
-

- Form Builder: ${data.display_name} -

-

- - ${data.name} - -

-
-
- - -
- - - - - - - - - View Public Form - - - - - - - View Submissions - -
-
-
- - -
- -
- - -
- -
- - -
- - -
-
- - - - -

Loading Form Builder...

-
-
- - - - - - -
- - - - - - - - - - - - - - - `; - const layoutData = { - title: `Form Builder: ${data.display_name}`, - content: pageContent, - user: data.user, - version: data.version - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/templates/pages/admin-forms-create.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderFormCreatePage(data) { - const pageContent = ` -
- -
-
- - - - - -
-

Create New Form

-

Enter basic information to create your form. You'll be able to add fields in the builder.

-
-
-
- - - ${data.error ? ` -
-
- - - -

${data.error}

-
-
- ` : ""} - - ${data.success ? ` -
-
- - - -

${data.success}

-
-
- ` : ""} - - -
-
- -
- -
- - -

- Lowercase letters, numbers, and underscores only. Used in URLs and API. -

-
- - -
- - -

- Human-readable name shown in the admin interface. -

-
- - -
- - -
- - -
- - -

- Helps organize forms in the admin panel. -

-
-
- - -
- - Cancel - - -
-
-
- - -
-
- - - -
-

What happens next?

-
-

After creating your form, you'll be taken to the Form Builder where you can:

-
    -
  • Drag and drop fields onto your form
  • -
  • Configure field properties and validation
  • -
  • Add conditional logic
  • -
  • Preview your form in real-time
  • -
  • Publish when ready
  • -
-
-
-
-
-
- - - `; - const layoutData = { - title: "Create Form", - content: pageContent, - user: data.user, - version: data.version - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/routes/admin-forms.ts -var adminFormsRoutes = new hono.Hono(); -adminFormsRoutes.use("*", chunkDVQA5II3_cjs.requireAuth()); -adminFormsRoutes.get("/", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const search = c.req.query("search") || ""; - const category = c.req.query("category") || ""; - let query = "SELECT * FROM forms WHERE 1=1"; - const params = []; - if (search) { - query += " AND (name LIKE ? OR display_name LIKE ?)"; - params.push(`%${search}%`, `%${search}%`); - } - if (category) { - query += " AND category = ?"; - params.push(category); - } - query += " ORDER BY created_at DESC"; - const result = await db.prepare(query).bind(...params).all(); - const forms = result.results.map((form) => ({ - ...form, - formattedDate: new Date(form.created_at).toLocaleDateString("en-US", { - year: "numeric", - month: "short", - day: "numeric" - }) - })); - const pageData = { - forms, - search, - category, - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion") - }; - return c.html(renderFormsListPage(pageData)); - } catch (error) { - console.error("Error listing forms:", error); - return c.html("

Error loading forms

", 500); - } -}); -adminFormsRoutes.get("/new", async (c) => { - try { - const user = c.get("user"); - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion") - }; - return c.html(renderFormCreatePage(pageData)); - } catch (error) { - console.error("Error showing create form page:", error); - return c.html("

Error loading form

", 500); - } -}); -adminFormsRoutes.get("/docs", async (c) => { - try { - const user = c.get("user"); - const { renderFormsDocsPage } = await import('./templates.cjs'); - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion") - }; - return c.html(renderFormsDocsPage(pageData)); - } catch (error) { - console.error("Error showing forms docs page:", error); - return c.html("

Error loading documentation

", 500); - } -}); -adminFormsRoutes.get("/examples", async (c) => { - try { - const user = c.get("user"); - const { renderFormsExamplesPage } = await import('./templates.cjs'); - const pageData = { - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion") - }; - return c.html(renderFormsExamplesPage(pageData)); - } catch (error) { - console.error("Error showing forms examples page:", error); - return c.html("

Error loading examples

", 500); - } -}); -adminFormsRoutes.post("/", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const body = await c.req.parseBody(); - const name = body.name; - const displayName = body.displayName; - const description = body.description || ""; - const category = body.category || "general"; - if (!name || !displayName) { - return c.json({ error: "Name and display name are required" }, 400); - } - if (!/^[a-z0-9_]+$/.test(name)) { - return c.json({ - error: "Form name must contain only lowercase letters, numbers, and underscores" - }, 400); - } - const existing = await db.prepare("SELECT id FROM forms WHERE name = ?").bind(name).first(); - if (existing) { - return c.json({ error: "A form with this name already exists" }, 400); - } - const formId = crypto.randomUUID(); - const now = Date.now(); - const emptySchema = { components: [] }; - await db.prepare(` - INSERT INTO forms ( - id, name, display_name, description, category, - formio_schema, settings, is_active, is_public, - created_by, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).bind( - formId, - name, - displayName, - description, - category, - JSON.stringify(emptySchema), - JSON.stringify({ - submitButtonText: "Submit", - successMessage: "Thank you for your submission!", - requireAuth: false, - emailNotifications: false - }), - 1, - // is_active - 1, - // is_public - user?.userId || null, - now, - now - ).run(); - return c.redirect(`/admin/forms/${formId}/builder`); - } catch (error) { - console.error("Error creating form:", error); - return c.json({ error: "Failed to create form" }, 500); - } -}); -adminFormsRoutes.get("/:id/builder", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const formId = c.req.param("id"); - const googleMapsApiKey = c.env.GOOGLE_MAPS_API_KEY || ""; - const form = await db.prepare("SELECT * FROM forms WHERE id = ?").bind(formId).first(); - if (!form) { - return c.html("

Form not found

", 404); - } - const turnstileService = new chunk6FHNRRJ3_cjs.TurnstileService(db); - const turnstileSettings = await turnstileService.getSettings(); - const pageData = { - id: form.id, - name: form.name, - display_name: form.display_name, - description: form.description, - category: form.category, - formio_schema: form.formio_schema ? JSON.parse(form.formio_schema) : { components: [] }, - settings: form.settings ? JSON.parse(form.settings) : {}, - is_active: Boolean(form.is_active), - is_public: Boolean(form.is_public), - google_maps_api_key: googleMapsApiKey, - turnstile_site_key: turnstileSettings?.siteKey || "", - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion") - }; - return c.html(renderFormBuilderPage(pageData)); - } catch (error) { - console.error("Error showing form builder:", error); - return c.html("

Error loading form builder

", 500); - } -}); -adminFormsRoutes.put("/:id", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const formId = c.req.param("id"); - const body = await c.req.json(); - const form = await db.prepare("SELECT id FROM forms WHERE id = ?").bind(formId).first(); - if (!form) { - return c.json({ error: "Form not found" }, 404); - } - const now = Date.now(); - await db.prepare(` - UPDATE forms - SET formio_schema = ?, - updated_by = ?, - updated_at = ? - WHERE id = ? - `).bind( - JSON.stringify(body.formio_schema), - user?.userId || null, - now, - formId - ).run(); - return c.json({ success: true, message: "Form saved successfully" }); - } catch (error) { - console.error("Error updating form:", error); - return c.json({ error: "Failed to save form" }, 500); - } -}); -adminFormsRoutes.delete("/:id", async (c) => { - try { - const db = c.env.DB; - const formId = c.req.param("id"); - const form = await db.prepare("SELECT id, submission_count FROM forms WHERE id = ?").bind(formId).first(); - if (!form) { - return c.json({ error: "Form not found" }, 404); - } - const submissionCount = form.submission_count || 0; - if (submissionCount > 0) { - return c.json({ - error: `Cannot delete form with ${submissionCount} submissions. Archive it instead.` - }, 400); - } - await db.prepare("DELETE FROM forms WHERE id = ?").bind(formId).run(); - return c.json({ success: true, message: "Form deleted successfully" }); - } catch (error) { - console.error("Error deleting form:", error); - return c.json({ error: "Failed to delete form" }, 500); - } -}); -adminFormsRoutes.get("/:id/submissions", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const formId = c.req.param("id"); - const form = await db.prepare("SELECT * FROM forms WHERE id = ?").bind(formId).first(); - if (!form) { - return c.html("

Form not found

", 404); - } - const submissions = await db.prepare( - "SELECT * FROM form_submissions WHERE form_id = ? ORDER BY submitted_at DESC" - ).bind(formId).all(); - const html8 = ` - - - - Submissions - ${form.display_name} - - - - \u2190 Back to Forms -

Submissions: ${form.display_name}

-

Total submissions: ${submissions.results.length}

- ${submissions.results.length > 0 ? ` - - - - - - - - - - ${submissions.results.map((sub) => ` - - - - - - `).join("")} - -
IDSubmittedData
${sub.id.substring(0, 8)}${new Date(sub.submitted_at).toLocaleString()}
${JSON.stringify(JSON.parse(sub.submission_data), null, 2)}
- ` : "

No submissions yet.

"} - - - `; - return c.html(html8); - } catch (error) { - console.error("Error loading submissions:", error); - return c.html("

Error loading submissions

", 500); - } -}); -var publicFormsRoutes = new hono.Hono(); -publicFormsRoutes.get("/:identifier/turnstile-config", async (c) => { - try { - const db = c.env.DB; - const identifier = c.req.param("identifier"); - const form = await db.prepare( - "SELECT id, turnstile_enabled, turnstile_settings FROM forms WHERE (id = ? OR name = ?) AND is_active = 1" - ).bind(identifier, identifier).first(); - if (!form) { - return c.json({ error: "Form not found" }, 404); - } - const turnstileService = new chunk6FHNRRJ3_cjs.TurnstileService(db); - const globalSettings = await turnstileService.getSettings(); - const formSettings = form.turnstile_settings ? JSON.parse(form.turnstile_settings) : { inherit: true }; - const enabled = form.turnstile_enabled === 1 || formSettings.inherit && globalSettings?.enabled; - if (!enabled || !globalSettings) { - return c.json({ enabled: false }); - } - return c.json({ - enabled: true, - siteKey: formSettings.siteKey || globalSettings.siteKey, - theme: formSettings.theme || globalSettings.theme || "auto", - size: formSettings.size || globalSettings.size || "normal", - mode: formSettings.mode || globalSettings.mode || "managed", - appearance: formSettings.appearance || globalSettings.appearance || "always" - }); - } catch (error) { - console.error("Error fetching Turnstile config:", error); - return c.json({ error: "Failed to fetch config" }, 500); - } -}); -publicFormsRoutes.get("/:identifier/schema", async (c) => { - try { - const db = c.env.DB; - const identifier = c.req.param("identifier"); - const form = await db.prepare( - "SELECT id, name, display_name, description, category, formio_schema, settings, is_active, is_public FROM forms WHERE (id = ? OR name = ?) AND is_active = 1 AND is_public = 1" - ).bind(identifier, identifier).first(); - if (!form) { - return c.json({ error: "Form not found" }, 404); - } - const formioSchema = form.formio_schema ? JSON.parse(form.formio_schema) : { components: [] }; - const settings = form.settings ? JSON.parse(form.settings) : {}; - return c.json({ - id: form.id, - name: form.name, - displayName: form.display_name, - description: form.description, - category: form.category, - schema: formioSchema, - settings, - submitUrl: `/api/forms/${form.id}/submit` - }); - } catch (error) { - console.error("Error fetching form schema:", error); - return c.json({ error: "Failed to fetch form schema" }, 500); - } -}); -publicFormsRoutes.get("/:name", async (c) => { - try { - const db = c.env.DB; - const formName = c.req.param("name"); - const googleMapsApiKey = c.env.GOOGLE_MAPS_API_KEY || ""; - const form = await db.prepare( - "SELECT * FROM forms WHERE name = ? AND is_active = 1 AND is_public = 1" - ).bind(formName).first(); - if (!form) { - return c.html("

Form not found

This form does not exist or is not publicly available.

", 404); - } - const formioSchema = form.formio_schema ? JSON.parse(form.formio_schema) : { components: [] }; - const settings = form.settings ? JSON.parse(form.settings) : {}; - const html8 = ` - - - - - - ${form.display_name} - - - - - - - -
-

${form.display_name}

- ${form.description ? `

${form.description}

` : ""} - -
- -
-
-
- - - - - - - - - - - `; - return c.html(html8); - } catch (error) { - console.error("Error rendering form:", error); - return c.html("

Error loading form

", 500); - } -}); -publicFormsRoutes.post("/:identifier/submit", async (c) => { - try { - const db = c.env.DB; - const identifier = c.req.param("identifier"); - const body = await c.req.json(); - const form = await db.prepare( - "SELECT * FROM forms WHERE (id = ? OR name = ?) AND is_active = 1" - ).bind(identifier, identifier).first(); - if (!form) { - return c.json({ error: "Form not found" }, 404); - } - const turnstileEnabled = form.turnstile_enabled === 1; - const turnstileSettings = form.turnstile_settings ? JSON.parse(form.turnstile_settings) : { inherit: true }; - if (turnstileEnabled || turnstileSettings.inherit) { - const turnstileService = new chunk6FHNRRJ3_cjs.TurnstileService(db); - const globalEnabled = await turnstileService.isEnabled(); - if (globalEnabled || turnstileEnabled) { - const turnstileToken = body.data?.turnstile || body.turnstile; - if (!turnstileToken) { - return c.json({ - error: "Turnstile verification required. Please complete the security check.", - code: "TURNSTILE_MISSING" - }, 400); - } - const clientIp = c.req.header("cf-connecting-ip"); - const verification = await turnstileService.verifyToken(turnstileToken, clientIp); - if (!verification.success) { - return c.json({ - error: verification.error || "Security verification failed. Please try again.", - code: "TURNSTILE_INVALID" - }, 403); - } - if (body.data?.turnstile) { - delete body.data.turnstile; - } - } - } - const submissionId = crypto.randomUUID(); - const now = Date.now(); - await db.prepare(` - INSERT INTO form_submissions ( - id, form_id, submission_data, user_id, ip_address, user_agent, - submitted_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) - `).bind( - submissionId, - form.id, - JSON.stringify(body.data), - null, - // user_id (for authenticated users) - c.req.header("cf-connecting-ip") || null, - c.req.header("user-agent") || null, - now, - now - ).run(); - await db.prepare(` - UPDATE forms - SET submission_count = submission_count + 1, - updated_at = ? - WHERE id = ? - `).bind(now, form.id).run(); - return c.json({ - success: true, - submissionId, - message: "Form submitted successfully" - }); - } catch (error) { - console.error("Error submitting form:", error); - return c.json({ error: "Failed to submit form" }, 500); - } -}); -var public_forms_default = publicFormsRoutes; - -// src/templates/pages/admin-api-reference.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderAPIReferencePage(data) { - const endpointsByCategory = data.endpoints.reduce((acc, endpoint) => { - if (!acc[endpoint.category]) { - acc[endpoint.category] = []; - } - acc[endpoint.category].push(endpoint); - return acc; - }, {}); - const categoryInfo = { - "Auth": { - title: "Authentication", - description: "User authentication and authorization endpoints", - icon: "\u{1F510}" - }, - "Content": { - title: "Content Management", - description: "Content creation, retrieval, and management", - icon: "\u{1F4DD}" - }, - "Media": { - title: "Media Management", - description: "File upload, storage, and media operations", - icon: "\u{1F5BC}\uFE0F" - }, - "Admin": { - title: "Admin Interface", - description: "Administrative panel and management features", - icon: "\u2699\uFE0F" - }, - "System": { - title: "System", - description: "Health checks and system information", - icon: "\u{1F527}" - } - }; - const pageContent = ` -
- -
-
-

API Reference

-

Complete documentation of all available API endpoints

-
- -
- - -
-
-
Total Endpoints
-
- ${data.endpoints.length} -
-
-
-
Public Endpoints
-
- ${data.endpoints.filter((e) => !e.authentication).length} -
-
-
-
Protected Endpoints
-
- ${data.endpoints.filter((e) => e.authentication).length} -
-
-
-
Categories
-
- ${Object.keys(endpointsByCategory).length} -
-
-
- - -
-
-
-
- -
-
- - - -
- -
-
-
- -
- - -
-
-
- -
- - -
-
-
-
-
- - -
- ${Object.entries(endpointsByCategory).map(([category, endpoints]) => { - const info = categoryInfo[category] || { title: category, description: "", icon: "\u{1F4CB}" }; - return ` -
-
- -
-
- ${info.icon} -
-

${info.title}

-

${info.description}

-
-
- - ${endpoints.length} endpoint${endpoints.length !== 1 ? "s" : ""} - -
-
-
- - -
- ${endpoints.map((endpoint) => ` -
-
- - ${endpoint.method} - -
-
- ${endpoint.path} - ${endpoint.authentication ? ` - - - - - Auth - - ` : ` - - - - - Public - - `} -
-

${endpoint.description}

-
-
-
- `).join("")} -
-
-
- `; - }).join("")} -
- - - -
- - - - - `; - const layoutData = { - title: "API Reference", - pageTitle: "API Reference", - currentPath: "/admin/api-reference", - user: data.user, - version: data.version, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} - -// src/routes/admin-api-reference.ts -var VERSION2 = chunk5HMR2SJW_cjs.getCoreVersion(); -var router2 = new hono.Hono(); -router2.use("*", chunkDVQA5II3_cjs.requireAuth()); -var apiEndpoints = [ - // Auth endpoints - { - method: "POST", - path: "/auth/login", - description: "Authenticate user with email and password", - authentication: false, - category: "Auth" - }, - { - method: "POST", - path: "/auth/register", - description: "Register a new user account", - authentication: false, - category: "Auth" - }, - { - method: "POST", - path: "/auth/logout", - description: "Log out the current user and invalidate session", - authentication: true, - category: "Auth" - }, - { - method: "GET", - path: "/auth/me", - description: "Get current authenticated user information", - authentication: true, - category: "Auth" - }, - { - method: "POST", - path: "/auth/refresh", - description: "Refresh authentication token", - authentication: true, - category: "Auth" - }, - // Content endpoints - { - method: "GET", - path: "/api/collections", - description: "List all available collections", - authentication: false, - category: "Content" - }, - { - method: "GET", - path: "/api/collections/:collection/content", - description: "Get all content items from a specific collection", - authentication: false, - category: "Content" - }, - { - method: "GET", - path: "/api/content/:id", - description: "Get a specific content item by ID", - authentication: false, - category: "Content" - }, - { - method: "POST", - path: "/api/content", - description: "Create a new content item", - authentication: true, - category: "Content" - }, - { - method: "PUT", - path: "/api/content/:id", - description: "Update an existing content item", - authentication: true, - category: "Content" - }, - { - method: "DELETE", - path: "/api/content/:id", - description: "Delete a content item", - authentication: true, - category: "Content" - }, - // Media endpoints - { - method: "GET", - path: "/api/media", - description: "List all media files with pagination", - authentication: false, - category: "Media" - }, - { - method: "GET", - path: "/api/media/:id", - description: "Get a specific media file by ID", - authentication: false, - category: "Media" - }, - { - method: "POST", - path: "/api/media/upload", - description: "Upload a new media file to R2 storage", - authentication: true, - category: "Media" - }, - { - method: "DELETE", - path: "/api/media/:id", - description: "Delete a media file from storage", - authentication: true, - category: "Media" - }, - // Admin endpoints - { - method: "GET", - path: "/admin/api/stats", - description: "Get dashboard statistics (collections, content, media, users)", - authentication: true, - category: "Admin" - }, - { - method: "GET", - path: "/admin/api/storage", - description: "Get storage usage information", - authentication: true, - category: "Admin" - }, - { - method: "GET", - path: "/admin/api/activity", - description: "Get recent activity logs", - authentication: true, - category: "Admin" - }, - { - method: "GET", - path: "/admin/api/collections", - description: "List all collections with field counts", - authentication: true, - category: "Admin" - }, - { - method: "POST", - path: "/admin/api/collections", - description: "Create a new collection", - authentication: true, - category: "Admin" - }, - { - method: "PATCH", - path: "/admin/api/collections/:id", - description: "Update an existing collection", - authentication: true, - category: "Admin" - }, - { - method: "DELETE", - path: "/admin/api/collections/:id", - description: "Delete a collection (must be empty)", - authentication: true, - category: "Admin" - }, - { - method: "GET", - path: "/admin/api/migrations/status", - description: "Get database migration status", - authentication: true, - category: "Admin" - }, - { - method: "POST", - path: "/admin/api/migrations/run", - description: "Run pending database migrations", - authentication: true, - category: "Admin" - }, - // System endpoints - { - method: "GET", - path: "/health", - description: "Health check endpoint for monitoring", - authentication: false, - category: "System" - }, - { - method: "GET", - path: "/api/health", - description: "API health check with schema information", - authentication: false, - category: "System" - }, - { - method: "GET", - path: "/api", - description: "API root - returns API information and OpenAPI spec", - authentication: false, - category: "System" - } -]; -router2.get("/", async (c) => { - const user = c.get("user"); - try { - const pageData = { - endpoints: apiEndpoints, - user: user ? { - name: user.email.split("@")[0] || user.email, - email: user.email, - role: user.role - } : void 0, - version: VERSION2 - }; - return c.html(renderAPIReferencePage(pageData)); - } catch (error) { - console.error("API Reference page error:", error); - const pageData = { - endpoints: [], - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: VERSION2 - }; - return c.html(renderAPIReferencePage(pageData)); - } -}); - -// src/routes/index.ts -var ROUTES_INFO = { - message: "Core routes available", - available: [ - "apiRoutes", - "apiContentCrudRoutes", - "apiMediaRoutes", - "apiSystemRoutes", - "adminApiRoutes", - "authRoutes", - "testCleanupRoutes", - "adminContentRoutes", - "adminUsersRoutes", - "adminMediaRoutes", - "adminPluginRoutes", - "adminLogsRoutes", - "adminDesignRoutes", - "adminCheckboxRoutes", - "adminTestimonialsRoutes", - "adminCodeExamplesRoutes", - "adminDashboardRoutes", - "adminCollectionsRoutes", - "adminSettingsRoutes", - "adminFormsRoutes", - "publicFormsRoutes", - "adminApiReferenceRoutes" - ], - status: "Core package routes ready", - reference: "https://github.com/sonicjs/sonicjs" -}; - -exports.ROUTES_INFO = ROUTES_INFO; -exports.adminCheckboxRoutes = adminCheckboxRoutes; -exports.adminCollectionsRoutes = adminCollectionsRoutes; -exports.adminDesignRoutes = adminDesignRoutes; -exports.adminFormsRoutes = adminFormsRoutes; -exports.adminLogsRoutes = adminLogsRoutes; -exports.adminMediaRoutes = adminMediaRoutes; -exports.adminPluginRoutes = adminPluginRoutes; -exports.adminSettingsRoutes = adminSettingsRoutes; -exports.admin_api_default = admin_api_default; -exports.admin_code_examples_default = admin_code_examples_default; -exports.admin_content_default = admin_content_default; -exports.admin_testimonials_default = admin_testimonials_default; -exports.api_content_crud_default = api_content_crud_default; -exports.api_default = api_default; -exports.api_media_default = api_media_default; -exports.api_system_default = api_system_default; -exports.auth_default = auth_default; -exports.getConfirmationDialogScript = getConfirmationDialogScript2; -exports.public_forms_default = public_forms_default; -exports.renderConfirmationDialog = renderConfirmationDialog2; -exports.router = router; -exports.router2 = router2; -exports.test_cleanup_default = test_cleanup_default; -exports.userRoutes = userRoutes; -//# sourceMappingURL=chunk-VAPDSKKV.cjs.map -//# sourceMappingURL=chunk-VAPDSKKV.cjs.map \ No newline at end of file diff --git a/packages/core/dist/chunk-VNLR35GO.cjs b/packages/core/dist/chunk-VNLR35GO.cjs deleted file mode 100644 index 77d097352..000000000 --- a/packages/core/dist/chunk-VNLR35GO.cjs +++ /dev/null @@ -1,1510 +0,0 @@ -'use strict'; - -var chunkP3XDZL6Q_cjs = require('./chunk-P3XDZL6Q.cjs'); -var chunkIGJUBJBW_cjs = require('./chunk-IGJUBJBW.cjs'); -var sqliteCore = require('drizzle-orm/sqlite-core'); -var v4 = require('zod/v4'); -var drizzleOrm = require('drizzle-orm'); -var d1 = require('drizzle-orm/d1'); - -// src/db/schema.ts -var schema_exports = {}; -chunkIGJUBJBW_cjs.__export(schema_exports, { - apiTokens: () => apiTokens, - collections: () => collections, - content: () => content, - contentVersions: () => contentVersions, - formFiles: () => formFiles, - formSubmissions: () => formSubmissions, - forms: () => forms, - insertCollectionSchema: () => insertCollectionSchema, - insertContentSchema: () => insertContentSchema, - insertFormFileSchema: () => insertFormFileSchema, - insertFormSchema: () => insertFormSchema, - insertFormSubmissionSchema: () => insertFormSubmissionSchema, - insertLogConfigSchema: () => insertLogConfigSchema, - insertMediaSchema: () => insertMediaSchema, - insertPluginActivityLogSchema: () => insertPluginActivityLogSchema, - insertPluginAssetSchema: () => insertPluginAssetSchema, - insertPluginHookSchema: () => insertPluginHookSchema, - insertPluginRouteSchema: () => insertPluginRouteSchema, - insertPluginSchema: () => insertPluginSchema, - insertSystemLogSchema: () => insertSystemLogSchema, - insertUserSchema: () => insertUserSchema, - insertWorkflowHistorySchema: () => insertWorkflowHistorySchema, - logConfig: () => logConfig, - media: () => media, - pluginActivityLog: () => pluginActivityLog, - pluginAssets: () => pluginAssets, - pluginHooks: () => pluginHooks, - pluginRoutes: () => pluginRoutes, - plugins: () => plugins, - selectCollectionSchema: () => selectCollectionSchema, - selectContentSchema: () => selectContentSchema, - selectFormFileSchema: () => selectFormFileSchema, - selectFormSchema: () => selectFormSchema, - selectFormSubmissionSchema: () => selectFormSubmissionSchema, - selectLogConfigSchema: () => selectLogConfigSchema, - selectMediaSchema: () => selectMediaSchema, - selectPluginActivityLogSchema: () => selectPluginActivityLogSchema, - selectPluginAssetSchema: () => selectPluginAssetSchema, - selectPluginHookSchema: () => selectPluginHookSchema, - selectPluginRouteSchema: () => selectPluginRouteSchema, - selectPluginSchema: () => selectPluginSchema, - selectSystemLogSchema: () => selectSystemLogSchema, - selectUserSchema: () => selectUserSchema, - selectWorkflowHistorySchema: () => selectWorkflowHistorySchema, - systemLogs: () => systemLogs, - users: () => users, - workflowHistory: () => workflowHistory -}); -var CONSTANTS = { - INT8_MIN: -128, - INT8_MAX: 127, - INT8_UNSIGNED_MAX: 255, - INT16_MIN: -32768, - INT16_MAX: 32767, - INT16_UNSIGNED_MAX: 65535, - INT24_MIN: -8388608, - INT24_MAX: 8388607, - INT24_UNSIGNED_MAX: 16777215, - INT32_MIN: -2147483648, - INT32_MAX: 2147483647, - INT32_UNSIGNED_MAX: 4294967295, - INT48_MIN: -140737488355328, - INT48_MAX: 140737488355327, - INT48_UNSIGNED_MAX: 281474976710655, - INT64_MIN: -9223372036854775808n, - INT64_MAX: 9223372036854775807n, - INT64_UNSIGNED_MAX: 18446744073709551615n -}; -function isColumnType(column, columnTypes) { - return columnTypes.includes(column.columnType); -} -function isWithEnum(column) { - return "enumValues" in column && Array.isArray(column.enumValues) && column.enumValues.length > 0; -} -var isPgEnum = isWithEnum; -var literalSchema = v4.z.union([v4.z.string(), v4.z.number(), v4.z.boolean(), v4.z.null()]); -var jsonSchema = v4.z.union([ - literalSchema, - v4.z.record(v4.z.string(), v4.z.any()), - v4.z.array(v4.z.any()) -]); -var bufferSchema = v4.z.custom((v) => v instanceof Buffer); -function columnToSchema(column, factory) { - const z$1 = v4.z; - const coerce = {}; - let schema; - if (isWithEnum(column)) { - schema = column.enumValues.length ? z$1.enum(column.enumValues) : z$1.string(); - } - if (!schema) { - if (isColumnType(column, ["PgGeometry", "PgPointTuple"])) { - schema = z$1.tuple([z$1.number(), z$1.number()]); - } else if (isColumnType(column, ["PgGeometryObject", "PgPointObject"])) { - schema = z$1.object({ x: z$1.number(), y: z$1.number() }); - } else if (isColumnType(column, ["PgHalfVector", "PgVector"])) { - schema = z$1.array(z$1.number()); - schema = column.dimensions ? schema.length(column.dimensions) : schema; - } else if (isColumnType(column, ["PgLine"])) { - schema = z$1.tuple([z$1.number(), z$1.number(), z$1.number()]); - } else if (isColumnType(column, ["PgLineABC"])) { - schema = z$1.object({ - a: z$1.number(), - b: z$1.number(), - c: z$1.number() - }); - } else if (isColumnType(column, ["PgArray"])) { - schema = z$1.array(columnToSchema(column.baseColumn)); - schema = column.size ? schema.length(column.size) : schema; - } else if (column.dataType === "array") { - schema = z$1.array(z$1.any()); - } else if (column.dataType === "number") { - schema = numberColumnToSchema(column, z$1, coerce); - } else if (column.dataType === "bigint") { - schema = bigintColumnToSchema(column, z$1, coerce); - } else if (column.dataType === "boolean") { - schema = coerce === true || coerce.boolean ? z$1.coerce.boolean() : z$1.boolean(); - } else if (column.dataType === "date") { - schema = coerce === true || coerce.date ? z$1.coerce.date() : z$1.date(); - } else if (column.dataType === "string") { - schema = stringColumnToSchema(column, z$1, coerce); - } else if (column.dataType === "json") { - schema = jsonSchema; - } else if (column.dataType === "custom") { - schema = z$1.any(); - } else if (column.dataType === "buffer") { - schema = bufferSchema; - } - } - if (!schema) { - schema = z$1.any(); - } - return schema; -} -function numberColumnToSchema(column, z2, coerce) { - let unsigned = column.getSQLType().includes("unsigned"); - let min; - let max; - let integer2 = false; - if (isColumnType(column, ["MySqlTinyInt", "SingleStoreTinyInt"])) { - min = unsigned ? 0 : CONSTANTS.INT8_MIN; - max = unsigned ? CONSTANTS.INT8_UNSIGNED_MAX : CONSTANTS.INT8_MAX; - integer2 = true; - } else if (isColumnType(column, [ - "PgSmallInt", - "PgSmallSerial", - "MySqlSmallInt", - "SingleStoreSmallInt" - ])) { - min = unsigned ? 0 : CONSTANTS.INT16_MIN; - max = unsigned ? CONSTANTS.INT16_UNSIGNED_MAX : CONSTANTS.INT16_MAX; - integer2 = true; - } else if (isColumnType(column, [ - "PgReal", - "MySqlFloat", - "MySqlMediumInt", - "SingleStoreMediumInt", - "SingleStoreFloat" - ])) { - min = unsigned ? 0 : CONSTANTS.INT24_MIN; - max = unsigned ? CONSTANTS.INT24_UNSIGNED_MAX : CONSTANTS.INT24_MAX; - integer2 = isColumnType(column, ["MySqlMediumInt", "SingleStoreMediumInt"]); - } else if (isColumnType(column, [ - "PgInteger", - "PgSerial", - "MySqlInt", - "SingleStoreInt" - ])) { - min = unsigned ? 0 : CONSTANTS.INT32_MIN; - max = unsigned ? CONSTANTS.INT32_UNSIGNED_MAX : CONSTANTS.INT32_MAX; - integer2 = true; - } else if (isColumnType(column, [ - "PgDoublePrecision", - "MySqlReal", - "MySqlDouble", - "SingleStoreReal", - "SingleStoreDouble", - "SQLiteReal" - ])) { - min = unsigned ? 0 : CONSTANTS.INT48_MIN; - max = unsigned ? CONSTANTS.INT48_UNSIGNED_MAX : CONSTANTS.INT48_MAX; - } else if (isColumnType(column, [ - "PgBigInt53", - "PgBigSerial53", - "MySqlBigInt53", - "MySqlSerial", - "SingleStoreBigInt53", - "SingleStoreSerial", - "SQLiteInteger" - ])) { - unsigned = unsigned || isColumnType(column, ["MySqlSerial", "SingleStoreSerial"]); - min = unsigned ? 0 : Number.MIN_SAFE_INTEGER; - max = Number.MAX_SAFE_INTEGER; - integer2 = true; - } else if (isColumnType(column, ["MySqlYear", "SingleStoreYear"])) { - min = 1901; - max = 2155; - integer2 = true; - } else { - min = Number.MIN_SAFE_INTEGER; - max = Number.MAX_SAFE_INTEGER; - } - let schema = coerce === true || coerce?.number ? integer2 ? z2.coerce.number() : z2.coerce.number().int() : integer2 ? z2.int() : z2.number(); - schema = schema.gte(min).lte(max); - return schema; -} -function bigintColumnToSchema(column, z2, coerce) { - const unsigned = column.getSQLType().includes("unsigned"); - const min = unsigned ? 0n : CONSTANTS.INT64_MIN; - const max = unsigned ? CONSTANTS.INT64_UNSIGNED_MAX : CONSTANTS.INT64_MAX; - const schema = coerce === true || coerce?.bigint ? z2.coerce.bigint() : z2.bigint(); - return schema.gte(min).lte(max); -} -function stringColumnToSchema(column, z2, coerce) { - if (isColumnType(column, ["PgUUID"])) { - return z2.uuid(); - } - let max; - let regex; - let fixed = false; - if (isColumnType(column, ["PgVarchar", "SQLiteText"])) { - max = column.length; - } else if (isColumnType(column, ["MySqlVarChar", "SingleStoreVarChar"])) { - max = column.length ?? CONSTANTS.INT16_UNSIGNED_MAX; - } else if (isColumnType(column, ["MySqlText", "SingleStoreText"])) { - if (column.textType === "longtext") { - max = CONSTANTS.INT32_UNSIGNED_MAX; - } else if (column.textType === "mediumtext") { - max = CONSTANTS.INT24_UNSIGNED_MAX; - } else if (column.textType === "text") { - max = CONSTANTS.INT16_UNSIGNED_MAX; - } else { - max = CONSTANTS.INT8_UNSIGNED_MAX; - } - } - if (isColumnType(column, [ - "PgChar", - "MySqlChar", - "SingleStoreChar" - ])) { - max = column.length; - fixed = true; - } - if (isColumnType(column, ["PgBinaryVector"])) { - regex = /^[01]+$/; - max = column.dimensions; - } - let schema = coerce === true || coerce?.string ? z2.coerce.string() : z2.string(); - schema = regex ? schema.regex(regex) : schema; - return max && fixed ? schema.length(max) : max ? schema.max(max) : schema; -} -function getColumns(tableLike) { - return drizzleOrm.isTable(tableLike) ? drizzleOrm.getTableColumns(tableLike) : drizzleOrm.getViewSelectedFields(tableLike); -} -function handleColumns(columns, refinements, conditions, factory) { - const columnSchemas = {}; - for (const [key, selected] of Object.entries(columns)) { - if (!drizzleOrm.is(selected, drizzleOrm.Column) && !drizzleOrm.is(selected, drizzleOrm.SQL) && !drizzleOrm.is(selected, drizzleOrm.SQL.Aliased) && typeof selected === "object") { - const columns2 = drizzleOrm.isTable(selected) || drizzleOrm.isView(selected) ? getColumns(selected) : selected; - columnSchemas[key] = handleColumns(columns2, refinements[key] ?? {}, conditions); - continue; - } - const refinement = refinements[key]; - if (refinement !== void 0 && typeof refinement !== "function") { - columnSchemas[key] = refinement; - continue; - } - const column = drizzleOrm.is(selected, drizzleOrm.Column) ? selected : void 0; - const schema = column ? columnToSchema(column) : v4.z.any(); - const refined = typeof refinement === "function" ? refinement(schema) : schema; - if (conditions.never(column)) { - continue; - } else { - columnSchemas[key] = refined; - } - if (column) { - if (conditions.nullable(column)) { - columnSchemas[key] = columnSchemas[key].nullable(); - } - if (conditions.optional(column)) { - columnSchemas[key] = columnSchemas[key].optional(); - } - } - } - return v4.z.object(columnSchemas); -} -function handleEnum(enum_, factory) { - const zod = v4.z; - return zod.enum(enum_.enumValues); -} -var selectConditions = { - never: () => false, - optional: () => false, - nullable: (column) => !column.notNull -}; -var insertConditions = { - never: (column) => column?.generated?.type === "always" || column?.generatedIdentity?.type === "always", - optional: (column) => !column.notNull || column.notNull && column.hasDefault, - nullable: (column) => !column.notNull -}; -var createSelectSchema = (entity, refine) => { - if (isPgEnum(entity)) { - return handleEnum(entity); - } - const columns = getColumns(entity); - return handleColumns(columns, {}, selectConditions); -}; -var createInsertSchema = (entity, refine) => { - const columns = getColumns(entity); - return handleColumns(columns, refine ?? {}, insertConditions); -}; - -// src/db/schema.ts -var users = sqliteCore.sqliteTable("users", { - id: sqliteCore.text("id").primaryKey(), - email: sqliteCore.text("email").notNull().unique(), - username: sqliteCore.text("username").notNull().unique(), - firstName: sqliteCore.text("first_name").notNull(), - lastName: sqliteCore.text("last_name").notNull(), - passwordHash: sqliteCore.text("password_hash"), - // Hashed password, nullable for OAuth users - role: sqliteCore.text("role").notNull().default("viewer"), - // 'admin', 'editor', 'author', 'viewer' - avatar: sqliteCore.text("avatar"), - isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true), - lastLoginAt: sqliteCore.integer("last_login_at"), - createdAt: sqliteCore.integer("created_at").notNull(), - updatedAt: sqliteCore.integer("updated_at").notNull() -}); -var collections = sqliteCore.sqliteTable("collections", { - id: sqliteCore.text("id").primaryKey(), - name: sqliteCore.text("name").notNull().unique(), - displayName: sqliteCore.text("display_name").notNull(), - description: sqliteCore.text("description"), - schema: sqliteCore.text("schema", { mode: "json" }).notNull(), - // JSON schema definition - isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true), - managed: sqliteCore.integer("managed", { mode: "boolean" }).notNull().default(false), - // Config-managed collections cannot be edited in UI - createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()), - updatedAt: sqliteCore.integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()) -}); -var content = sqliteCore.sqliteTable("content", { - id: sqliteCore.text("id").primaryKey(), - collectionId: sqliteCore.text("collection_id").notNull().references(() => collections.id), - slug: sqliteCore.text("slug").notNull(), - title: sqliteCore.text("title").notNull(), - data: sqliteCore.text("data", { mode: "json" }).notNull(), - // JSON content data - status: sqliteCore.text("status").notNull().default("draft"), - // 'draft', 'published', 'archived' - publishedAt: sqliteCore.integer("published_at", { mode: "timestamp" }), - authorId: sqliteCore.text("author_id").notNull().references(() => users.id), - createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()), - updatedAt: sqliteCore.integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()) -}); -var contentVersions = sqliteCore.sqliteTable("content_versions", { - id: sqliteCore.text("id").primaryKey(), - contentId: sqliteCore.text("content_id").notNull().references(() => content.id), - version: sqliteCore.integer("version").notNull(), - data: sqliteCore.text("data", { mode: "json" }).notNull(), - authorId: sqliteCore.text("author_id").notNull().references(() => users.id), - createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()) -}); -var media = sqliteCore.sqliteTable("media", { - id: sqliteCore.text("id").primaryKey(), - filename: sqliteCore.text("filename").notNull(), - originalName: sqliteCore.text("original_name").notNull(), - mimeType: sqliteCore.text("mime_type").notNull(), - size: sqliteCore.integer("size").notNull(), - width: sqliteCore.integer("width"), - height: sqliteCore.integer("height"), - folder: sqliteCore.text("folder").notNull().default("uploads"), - r2Key: sqliteCore.text("r2_key").notNull(), - // R2 storage key - publicUrl: sqliteCore.text("public_url").notNull(), - // CDN URL - thumbnailUrl: sqliteCore.text("thumbnail_url"), - alt: sqliteCore.text("alt"), - caption: sqliteCore.text("caption"), - tags: sqliteCore.text("tags", { mode: "json" }), - // JSON array of tags - uploadedBy: sqliteCore.text("uploaded_by").notNull().references(() => users.id), - uploadedAt: sqliteCore.integer("uploaded_at").notNull(), - updatedAt: sqliteCore.integer("updated_at"), - publishedAt: sqliteCore.integer("published_at"), - scheduledAt: sqliteCore.integer("scheduled_at"), - archivedAt: sqliteCore.integer("archived_at"), - deletedAt: sqliteCore.integer("deleted_at") -}); -var apiTokens = sqliteCore.sqliteTable("api_tokens", { - id: sqliteCore.text("id").primaryKey(), - name: sqliteCore.text("name").notNull(), - token: sqliteCore.text("token").notNull().unique(), - userId: sqliteCore.text("user_id").notNull().references(() => users.id), - permissions: sqliteCore.text("permissions", { mode: "json" }).notNull(), - // Array of permissions - expiresAt: sqliteCore.integer("expires_at", { mode: "timestamp" }), - lastUsedAt: sqliteCore.integer("last_used_at", { mode: "timestamp" }), - createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()) -}); -var workflowHistory = sqliteCore.sqliteTable("workflow_history", { - id: sqliteCore.text("id").primaryKey(), - contentId: sqliteCore.text("content_id").notNull().references(() => content.id), - action: sqliteCore.text("action").notNull(), - fromStatus: sqliteCore.text("from_status").notNull(), - toStatus: sqliteCore.text("to_status").notNull(), - userId: sqliteCore.text("user_id").notNull().references(() => users.id), - comment: sqliteCore.text("comment"), - createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()) -}); -var plugins = sqliteCore.sqliteTable("plugins", { - id: sqliteCore.text("id").primaryKey(), - name: sqliteCore.text("name").notNull().unique(), - displayName: sqliteCore.text("display_name").notNull(), - description: sqliteCore.text("description"), - version: sqliteCore.text("version").notNull(), - author: sqliteCore.text("author").notNull(), - category: sqliteCore.text("category").notNull(), - icon: sqliteCore.text("icon"), - status: sqliteCore.text("status").notNull().default("inactive"), - // 'active', 'inactive', 'error' - isCore: sqliteCore.integer("is_core", { mode: "boolean" }).notNull().default(false), - settings: sqliteCore.text("settings", { mode: "json" }), - permissions: sqliteCore.text("permissions", { mode: "json" }), - dependencies: sqliteCore.text("dependencies", { mode: "json" }), - downloadCount: sqliteCore.integer("download_count").notNull().default(0), - rating: sqliteCore.integer("rating").notNull().default(0), - installedAt: sqliteCore.integer("installed_at").notNull(), - activatedAt: sqliteCore.integer("activated_at"), - lastUpdated: sqliteCore.integer("last_updated").notNull(), - errorMessage: sqliteCore.text("error_message"), - createdAt: sqliteCore.integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3)), - updatedAt: sqliteCore.integer("updated_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3)) -}); -var pluginHooks = sqliteCore.sqliteTable("plugin_hooks", { - id: sqliteCore.text("id").primaryKey(), - pluginId: sqliteCore.text("plugin_id").notNull().references(() => plugins.id), - hookName: sqliteCore.text("hook_name").notNull(), - handlerName: sqliteCore.text("handler_name").notNull(), - priority: sqliteCore.integer("priority").notNull().default(10), - isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true), - createdAt: sqliteCore.integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3)) -}); -var pluginRoutes = sqliteCore.sqliteTable("plugin_routes", { - id: sqliteCore.text("id").primaryKey(), - pluginId: sqliteCore.text("plugin_id").notNull().references(() => plugins.id), - path: sqliteCore.text("path").notNull(), - method: sqliteCore.text("method").notNull(), - handlerName: sqliteCore.text("handler_name").notNull(), - middleware: sqliteCore.text("middleware", { mode: "json" }), - isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true), - createdAt: sqliteCore.integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3)) -}); -var pluginAssets = sqliteCore.sqliteTable("plugin_assets", { - id: sqliteCore.text("id").primaryKey(), - pluginId: sqliteCore.text("plugin_id").notNull().references(() => plugins.id), - assetType: sqliteCore.text("asset_type").notNull(), - // 'css', 'js', 'image', 'font' - assetPath: sqliteCore.text("asset_path").notNull(), - loadOrder: sqliteCore.integer("load_order").notNull().default(100), - loadLocation: sqliteCore.text("load_location").notNull().default("footer"), - // 'header', 'footer' - isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true), - createdAt: sqliteCore.integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3)) -}); -var pluginActivityLog = sqliteCore.sqliteTable("plugin_activity_log", { - id: sqliteCore.text("id").primaryKey(), - pluginId: sqliteCore.text("plugin_id").notNull().references(() => plugins.id), - action: sqliteCore.text("action").notNull(), - userId: sqliteCore.text("user_id"), - details: sqliteCore.text("details", { mode: "json" }), - timestamp: sqliteCore.integer("timestamp").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3)) -}); -var insertUserSchema = createInsertSchema(users, { - email: (schema) => schema.email(), - firstName: (schema) => schema.min(1), - lastName: (schema) => schema.min(1), - username: (schema) => schema.min(3) -}); -var selectUserSchema = createSelectSchema(users); -var insertCollectionSchema = createInsertSchema(collections, { - name: (schema) => schema.min(1).regex(/^[a-z0-9_]+$/, "Collection name must be lowercase with underscores"), - displayName: (schema) => schema.min(1) -}); -var selectCollectionSchema = createSelectSchema(collections); -var insertContentSchema = createInsertSchema(content, { - slug: (schema) => schema.min(1).regex(/^[a-zA-Z0-9_-]+$/, "Slug must contain only letters, numbers, underscores, and hyphens"), - title: (schema) => schema.min(1), - status: (schema) => schema -}); -var selectContentSchema = createSelectSchema(content); -var insertMediaSchema = createInsertSchema(media, { - filename: (schema) => schema.min(1), - originalName: (schema) => schema.min(1), - mimeType: (schema) => schema.min(1), - size: (schema) => schema.positive(), - r2Key: (schema) => schema.min(1), - publicUrl: (schema) => schema.url(), - folder: (schema) => schema.min(1) -}); -var selectMediaSchema = createSelectSchema(media); -var insertWorkflowHistorySchema = createInsertSchema(workflowHistory, { - action: (schema) => schema.min(1), - fromStatus: (schema) => schema.min(1), - toStatus: (schema) => schema.min(1) -}); -var selectWorkflowHistorySchema = createSelectSchema(workflowHistory); -var insertPluginSchema = createInsertSchema(plugins, { - name: (schema) => schema.min(1), - displayName: (schema) => schema.min(1), - version: (schema) => schema.min(1), - author: (schema) => schema.min(1), - category: (schema) => schema.min(1) -}); -var selectPluginSchema = createSelectSchema(plugins); -var insertPluginHookSchema = createInsertSchema(pluginHooks, { - hookName: (schema) => schema.min(1), - handlerName: (schema) => schema.min(1) -}); -var selectPluginHookSchema = createSelectSchema(pluginHooks); -var insertPluginRouteSchema = createInsertSchema(pluginRoutes, { - path: (schema) => schema.min(1), - method: (schema) => schema.min(1), - handlerName: (schema) => schema.min(1) -}); -var selectPluginRouteSchema = createSelectSchema(pluginRoutes); -var insertPluginAssetSchema = createInsertSchema(pluginAssets, { - assetType: (schema) => schema.min(1), - assetPath: (schema) => schema.min(1) -}); -var selectPluginAssetSchema = createSelectSchema(pluginAssets); -var insertPluginActivityLogSchema = createInsertSchema(pluginActivityLog, { - action: (schema) => schema.min(1) -}); -var selectPluginActivityLogSchema = createSelectSchema(pluginActivityLog); -var systemLogs = sqliteCore.sqliteTable("system_logs", { - id: sqliteCore.text("id").primaryKey(), - level: sqliteCore.text("level").notNull(), - // 'debug', 'info', 'warn', 'error', 'fatal' - category: sqliteCore.text("category").notNull(), - // 'auth', 'api', 'workflow', 'plugin', 'media', 'system', etc. - message: sqliteCore.text("message").notNull(), - data: sqliteCore.text("data", { mode: "json" }), - // Additional structured data - userId: sqliteCore.text("user_id").references(() => users.id), - sessionId: sqliteCore.text("session_id"), - requestId: sqliteCore.text("request_id"), - ipAddress: sqliteCore.text("ip_address"), - userAgent: sqliteCore.text("user_agent"), - method: sqliteCore.text("method"), - // HTTP method for API logs - url: sqliteCore.text("url"), - // Request URL for API logs - statusCode: sqliteCore.integer("status_code"), - // HTTP status code for API logs - duration: sqliteCore.integer("duration"), - // Request duration in milliseconds - stackTrace: sqliteCore.text("stack_trace"), - // Error stack trace for error logs - tags: sqliteCore.text("tags", { mode: "json" }), - // Array of tags for categorization - source: sqliteCore.text("source"), - // Source component/module that generated the log - createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()) -}); -var logConfig = sqliteCore.sqliteTable("log_config", { - id: sqliteCore.text("id").primaryKey(), - category: sqliteCore.text("category").notNull().unique(), - enabled: sqliteCore.integer("enabled", { mode: "boolean" }).notNull().default(true), - level: sqliteCore.text("level").notNull().default("info"), - // minimum log level to store - retention: sqliteCore.integer("retention").notNull().default(30), - // days to keep logs - maxSize: sqliteCore.integer("max_size").default(1e4), - // max number of logs per category - createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()), - updatedAt: sqliteCore.integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()) -}); -var insertSystemLogSchema = createInsertSchema(systemLogs, { - level: (schema) => schema.min(1), - category: (schema) => schema.min(1), - message: (schema) => schema.min(1) -}); -var selectSystemLogSchema = createSelectSchema(systemLogs); -var insertLogConfigSchema = createInsertSchema(logConfig, { - category: (schema) => schema.min(1), - level: (schema) => schema.min(1) -}); -var selectLogConfigSchema = createSelectSchema(logConfig); -var forms = sqliteCore.sqliteTable("forms", { - id: sqliteCore.text("id").primaryKey(), - name: sqliteCore.text("name").notNull().unique(), - // Machine name (e.g., "contact-form") - displayName: sqliteCore.text("display_name").notNull(), - // Human name (e.g., "Contact Form") - description: sqliteCore.text("description"), - category: sqliteCore.text("category").notNull().default("general"), - // contact, survey, registration, etc. - // Form.io schema (JSON) - formioSchema: sqliteCore.text("formio_schema", { mode: "json" }).notNull(), - // Complete Form.io JSON schema - // Settings (JSON) - settings: sqliteCore.text("settings", { mode: "json" }), - // emailNotifications, successMessage, etc. - // Status & Management - isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true), - isPublic: sqliteCore.integer("is_public", { mode: "boolean" }).notNull().default(true), - managed: sqliteCore.integer("managed", { mode: "boolean" }).notNull().default(false), - // Metadata - icon: sqliteCore.text("icon"), - color: sqliteCore.text("color"), - tags: sqliteCore.text("tags", { mode: "json" }), - // JSON array - // Stats - submissionCount: sqliteCore.integer("submission_count").notNull().default(0), - viewCount: sqliteCore.integer("view_count").notNull().default(0), - // Ownership - createdBy: sqliteCore.text("created_by").references(() => users.id), - updatedBy: sqliteCore.text("updated_by").references(() => users.id), - // Timestamps - createdAt: sqliteCore.integer("created_at").notNull(), - updatedAt: sqliteCore.integer("updated_at").notNull() -}); -var formSubmissions = sqliteCore.sqliteTable("form_submissions", { - id: sqliteCore.text("id").primaryKey(), - formId: sqliteCore.text("form_id").notNull().references(() => forms.id, { onDelete: "cascade" }), - // Submission data - submissionData: sqliteCore.text("submission_data", { mode: "json" }).notNull(), - // The actual form data - // Submission metadata - status: sqliteCore.text("status").notNull().default("pending"), - // pending, reviewed, approved, rejected, spam - submissionNumber: sqliteCore.integer("submission_number"), - // User information - userId: sqliteCore.text("user_id").references(() => users.id), - userEmail: sqliteCore.text("user_email"), - // Tracking - ipAddress: sqliteCore.text("ip_address"), - userAgent: sqliteCore.text("user_agent"), - referrer: sqliteCore.text("referrer"), - utmSource: sqliteCore.text("utm_source"), - utmMedium: sqliteCore.text("utm_medium"), - utmCampaign: sqliteCore.text("utm_campaign"), - // Review/Processing - reviewedBy: sqliteCore.text("reviewed_by").references(() => users.id), - reviewedAt: sqliteCore.integer("reviewed_at"), - reviewNotes: sqliteCore.text("review_notes"), - // Flags - isSpam: sqliteCore.integer("is_spam", { mode: "boolean" }).notNull().default(false), - isArchived: sqliteCore.integer("is_archived", { mode: "boolean" }).notNull().default(false), - // Timestamps - submittedAt: sqliteCore.integer("submitted_at").notNull(), - updatedAt: sqliteCore.integer("updated_at").notNull() -}); -var formFiles = sqliteCore.sqliteTable("form_files", { - id: sqliteCore.text("id").primaryKey(), - submissionId: sqliteCore.text("submission_id").notNull().references(() => formSubmissions.id, { onDelete: "cascade" }), - mediaId: sqliteCore.text("media_id").notNull().references(() => media.id, { onDelete: "cascade" }), - fieldName: sqliteCore.text("field_name").notNull(), - // Form field that uploaded this file - uploadedAt: sqliteCore.integer("uploaded_at").notNull() -}); -var insertFormSchema = createInsertSchema(forms); -var selectFormSchema = createSelectSchema(forms); -var insertFormSubmissionSchema = createInsertSchema(formSubmissions); -var selectFormSubmissionSchema = createSelectSchema(formSubmissions); -var insertFormFileSchema = createInsertSchema(formFiles); -var selectFormFileSchema = createSelectSchema(formFiles); -var Logger = class { - db; - enabled = true; - configCache = /* @__PURE__ */ new Map(); - lastConfigRefresh = 0; - configRefreshInterval = 6e4; - // 1 minute - constructor(database) { - this.db = d1.drizzle(database); - } - /** - * Log a debug message - */ - async debug(category, message, data, context) { - return this.log("debug", category, message, data, context); - } - /** - * Log an info message - */ - async info(category, message, data, context) { - return this.log("info", category, message, data, context); - } - /** - * Log a warning message - */ - async warn(category, message, data, context) { - return this.log("warn", category, message, data, context); - } - /** - * Log an error message - */ - async error(category, message, error, context) { - const errorData = error instanceof Error ? { - name: error.name, - message: error.message, - stack: error.stack - } : error; - return this.log("error", category, message, errorData, { - ...context, - stackTrace: error instanceof Error ? error.stack : void 0 - }); - } - /** - * Log a fatal message - */ - async fatal(category, message, error, context) { - const errorData = error instanceof Error ? { - name: error.name, - message: error.message, - stack: error.stack - } : error; - return this.log("fatal", category, message, errorData, { - ...context, - stackTrace: error instanceof Error ? error.stack : void 0 - }); - } - /** - * Log an API request - */ - async logRequest(method, url, statusCode, duration, context) { - const level = statusCode >= 500 ? "error" : statusCode >= 400 ? "warn" : "info"; - return this.log(level, "api", `${method} ${url} - ${statusCode}`, { - method, - url, - statusCode, - duration - }, { - ...context, - method, - url, - statusCode, - duration - }); - } - /** - * Log an authentication event - */ - async logAuth(action, userId, success = true, context) { - const level = success ? "info" : "warn"; - return this.log(level, "auth", `Authentication ${action}: ${success ? "success" : "failed"}`, { - action, - success, - userId - }, { - ...context, - userId, - tags: ["authentication", action] - }); - } - /** - * Log a security event - */ - async logSecurity(event, severity, context) { - const level = severity === "critical" ? "fatal" : severity === "high" ? "error" : "warn"; - return this.log(level, "security", `Security event: ${event}`, { - event, - severity - }, { - ...context, - tags: ["security", severity] - }); - } - /** - * Core logging method - */ - async log(level, category, message, data, context) { - if (!this.enabled) return; - try { - const config = await this.getConfig(category); - if (!config || !config.enabled || !this.shouldLog(level, config.level)) { - return; - } - const logEntry = { - id: crypto.randomUUID(), - level, - category, - message, - data: data ? JSON.stringify(data) : null, - userId: context?.userId || null, - sessionId: context?.sessionId || null, - requestId: context?.requestId || null, - ipAddress: context?.ipAddress || null, - userAgent: context?.userAgent || null, - method: context?.method || null, - url: context?.url || null, - statusCode: context?.statusCode || null, - duration: context?.duration || null, - stackTrace: context?.stackTrace || null, - tags: context?.tags ? JSON.stringify(context.tags) : null, - source: context?.source || null, - createdAt: /* @__PURE__ */ new Date() - }; - await this.db.insert(systemLogs).values(logEntry); - if (config.maxSize) { - await this.cleanupCategory(category, config.maxSize); - } - } catch (error) { - console.error("Logger error:", error); - } - } - /** - * Get logs with filtering and pagination - */ - async getLogs(filter = {}) { - try { - const conditions = []; - if (filter.level && filter.level.length > 0) { - conditions.push(drizzleOrm.inArray(systemLogs.level, filter.level)); - } - if (filter.category && filter.category.length > 0) { - conditions.push(drizzleOrm.inArray(systemLogs.category, filter.category)); - } - if (filter.userId) { - conditions.push(drizzleOrm.eq(systemLogs.userId, filter.userId)); - } - if (filter.source) { - conditions.push(drizzleOrm.eq(systemLogs.source, filter.source)); - } - if (filter.search) { - conditions.push( - drizzleOrm.like(systemLogs.message, `%${filter.search}%`) - ); - } - if (filter.startDate) { - conditions.push(drizzleOrm.gte(systemLogs.createdAt, filter.startDate)); - } - if (filter.endDate) { - conditions.push(drizzleOrm.lte(systemLogs.createdAt, filter.endDate)); - } - const whereClause = conditions.length > 0 ? drizzleOrm.and(...conditions) : void 0; - const totalResult = await this.db.select({ count: drizzleOrm.count() }).from(systemLogs).where(whereClause); - const total = totalResult[0]?.count || 0; - const sortColumn = filter.sortBy === "level" ? systemLogs.level : filter.sortBy === "category" ? systemLogs.category : systemLogs.createdAt; - const sortFn = filter.sortOrder === "asc" ? drizzleOrm.asc : drizzleOrm.desc; - const logs = await this.db.select().from(systemLogs).where(whereClause).orderBy(sortFn(sortColumn)).limit(filter.limit || 50).offset(filter.offset || 0); - return { logs, total }; - } catch (error) { - console.error("Error getting logs:", error); - return { logs: [], total: 0 }; - } - } - /** - * Get log configuration for a category - */ - async getConfig(category) { - try { - const now = Date.now(); - if (this.configCache.has(category) && now - this.lastConfigRefresh < this.configRefreshInterval) { - return this.configCache.get(category) || null; - } - const configs = await this.db.select().from(logConfig).where(drizzleOrm.eq(logConfig.category, category)); - const config = configs[0] || null; - if (config) { - this.configCache.set(category, config); - this.lastConfigRefresh = now; - } - return config; - } catch (error) { - console.error("Error getting log config:", error); - return null; - } - } - /** - * Update log configuration - */ - async updateConfig(category, updates) { - try { - await this.db.update(logConfig).set({ - ...updates, - updatedAt: /* @__PURE__ */ new Date() - }).where(drizzleOrm.eq(logConfig.category, category)); - this.configCache.delete(category); - } catch (error) { - console.error("Error updating log config:", error); - } - } - /** - * Get all log configurations - */ - async getAllConfigs() { - try { - return await this.db.select().from(logConfig); - } catch (error) { - console.error("Error getting log configs:", error); - return []; - } - } - /** - * Clean up old logs for a category - */ - async cleanupCategory(category, maxSize) { - try { - const countResult = await this.db.select({ count: drizzleOrm.count() }).from(systemLogs).where(drizzleOrm.eq(systemLogs.category, category)); - const currentCount = countResult[0]?.count || 0; - if (currentCount > maxSize) { - const cutoffLogs = await this.db.select({ createdAt: systemLogs.createdAt }).from(systemLogs).where(drizzleOrm.eq(systemLogs.category, category)).orderBy(drizzleOrm.desc(systemLogs.createdAt)).limit(1).offset(maxSize - 1); - if (cutoffLogs[0]) { - await this.db.delete(systemLogs).where( - drizzleOrm.and( - drizzleOrm.eq(systemLogs.category, category), - drizzleOrm.lte(systemLogs.createdAt, cutoffLogs[0].createdAt) - ) - ); - } - } - } catch (error) { - console.error("Error cleaning up logs:", error); - } - } - /** - * Clean up logs based on retention policy - */ - async cleanupByRetention() { - try { - const configs = await this.getAllConfigs(); - for (const config of configs) { - if (config.retention > 0) { - const cutoffDate = /* @__PURE__ */ new Date(); - cutoffDate.setDate(cutoffDate.getDate() - config.retention); - await this.db.delete(systemLogs).where( - drizzleOrm.and( - drizzleOrm.eq(systemLogs.category, config.category), - drizzleOrm.lte(systemLogs.createdAt, cutoffDate) - ) - ); - } - } - } catch (error) { - console.error("Error cleaning up logs by retention:", error); - } - } - /** - * Check if a log level should be recorded based on configuration - */ - shouldLog(level, configLevel) { - const levels = ["debug", "info", "warn", "error", "fatal"]; - const levelIndex = levels.indexOf(level); - const configLevelIndex = levels.indexOf(configLevel); - return levelIndex >= configLevelIndex; - } - /** - * Enable or disable logging - */ - setEnabled(enabled) { - this.enabled = enabled; - } - /** - * Check if logging is enabled - */ - isEnabled() { - return this.enabled; - } -}; -var loggerInstance = null; -function getLogger(database) { - if (!loggerInstance && database) { - loggerInstance = new Logger(database); - } - if (!loggerInstance) { - throw new Error("Logger not initialized. Call getLogger with a database instance first."); - } - return loggerInstance; -} -function initLogger(database) { - loggerInstance = new Logger(database); - return loggerInstance; -} - -// src/services/cache.ts -var CacheService = class { - config; - memoryCache = /* @__PURE__ */ new Map(); - constructor(config) { - this.config = config; - } - /** - * Generate cache key with prefix - */ - generateKey(type, identifier) { - const parts = [this.config.keyPrefix, type]; - if (identifier) { - parts.push(identifier); - } - return parts.join(":"); - } - /** - * Get value from cache - */ - async get(key) { - const cached = this.memoryCache.get(key); - if (!cached) { - return null; - } - if (Date.now() > cached.expires) { - this.memoryCache.delete(key); - return null; - } - return cached.value; - } - /** - * Get value from cache with source information - */ - async getWithSource(key) { - const cached = this.memoryCache.get(key); - if (!cached) { - return { - hit: false, - data: null, - source: "none" - }; - } - if (Date.now() > cached.expires) { - this.memoryCache.delete(key); - return { - hit: false, - data: null, - source: "expired" - }; - } - return { - hit: true, - data: cached.value, - source: "memory", - ttl: (cached.expires - Date.now()) / 1e3 - // TTL in seconds - }; - } - /** - * Set value in cache - */ - async set(key, value, ttl) { - const expires = Date.now() + (ttl || this.config.ttl) * 1e3; - this.memoryCache.set(key, { value, expires }); - } - /** - * Delete specific key from cache - */ - async delete(key) { - this.memoryCache.delete(key); - } - /** - * Invalidate cache keys matching a pattern - * For memory cache, we do simple string matching - */ - async invalidate(pattern) { - const regexPattern = pattern.replace(/\*/g, ".*").replace(/\?/g, "."); - const regex = new RegExp(`^${regexPattern}$`); - for (const key of this.memoryCache.keys()) { - if (regex.test(key)) { - this.memoryCache.delete(key); - } - } - } - /** - * Clear all cache - */ - async clear() { - this.memoryCache.clear(); - } - /** - * Get value from cache or set it using a callback - */ - async getOrSet(key, callback, ttl) { - const cached = await this.get(key); - if (cached !== null) { - return cached; - } - const value = await callback(); - await this.set(key, value, ttl); - return value; - } -}; -var CACHE_CONFIGS = { - api: { - ttl: 300, - // 5 minutes - keyPrefix: "api" - }, - user: { - ttl: 600, - // 10 minutes - keyPrefix: "user" - }, - content: { - ttl: 300, - // 5 minutes - keyPrefix: "content" - }, - collection: { - ttl: 600, - // 10 minutes - keyPrefix: "collection" - } -}; -function getCacheService(config) { - return new CacheService(config); -} - -// src/services/settings.ts -var SettingsService = class { - constructor(db) { - this.db = db; - } - /** - * Get a setting value by category and key - */ - async getSetting(category, key) { - try { - const result = await this.db.prepare("SELECT value FROM settings WHERE category = ? AND key = ?").bind(category, key).first(); - if (!result) { - return null; - } - return JSON.parse(result.value); - } catch (error) { - console.error(`Error getting setting ${category}.${key}:`, error); - return null; - } - } - /** - * Get all settings for a category - */ - async getCategorySettings(category) { - try { - const { results } = await this.db.prepare("SELECT key, value FROM settings WHERE category = ?").bind(category).all(); - const settings = {}; - for (const row of results || []) { - const r = row; - settings[r.key] = JSON.parse(r.value); - } - return settings; - } catch (error) { - console.error(`Error getting category settings for ${category}:`, error); - return {}; - } - } - /** - * Set a setting value - */ - async setSetting(category, key, value) { - try { - const now = Date.now(); - const jsonValue = JSON.stringify(value); - await this.db.prepare(` - INSERT INTO settings (id, category, key, value, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?) - ON CONFLICT(category, key) DO UPDATE SET - value = excluded.value, - updated_at = excluded.updated_at - `).bind(crypto.randomUUID(), category, key, jsonValue, now, now).run(); - return true; - } catch (error) { - console.error(`Error setting ${category}.${key}:`, error); - return false; - } - } - /** - * Set multiple settings at once - */ - async setMultipleSettings(category, settings) { - try { - const now = Date.now(); - for (const [key, value] of Object.entries(settings)) { - const jsonValue = JSON.stringify(value); - await this.db.prepare(` - INSERT INTO settings (id, category, key, value, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?) - ON CONFLICT(category, key) DO UPDATE SET - value = excluded.value, - updated_at = excluded.updated_at - `).bind(crypto.randomUUID(), category, key, jsonValue, now, now).run(); - } - return true; - } catch (error) { - console.error(`Error setting multiple settings for ${category}:`, error); - return false; - } - } - /** - * Get general settings with defaults - */ - async getGeneralSettings(userEmail) { - const settings = await this.getCategorySettings("general"); - return { - siteName: settings.siteName || "SonicJS AI", - siteDescription: settings.siteDescription || "A modern headless CMS powered by AI", - adminEmail: settings.adminEmail || userEmail || "admin@example.com", - timezone: settings.timezone || "UTC", - language: settings.language || "en", - maintenanceMode: settings.maintenanceMode || false - }; - } - /** - * Save general settings - */ - async saveGeneralSettings(settings) { - const settingsToSave = {}; - if (settings.siteName !== void 0) settingsToSave.siteName = settings.siteName; - if (settings.siteDescription !== void 0) settingsToSave.siteDescription = settings.siteDescription; - if (settings.adminEmail !== void 0) settingsToSave.adminEmail = settings.adminEmail; - if (settings.timezone !== void 0) settingsToSave.timezone = settings.timezone; - if (settings.language !== void 0) settingsToSave.language = settings.language; - if (settings.maintenanceMode !== void 0) settingsToSave.maintenanceMode = settings.maintenanceMode; - return await this.setMultipleSettings("general", settingsToSave); - } -}; - -// src/services/telemetry-service.ts -var TelemetryService = class { - config; - identity = null; - enabled = true; - eventQueue = []; - isInitialized = false; - constructor(config) { - this.config = { - ...chunkP3XDZL6Q_cjs.getTelemetryConfig(), - ...config - }; - this.enabled = this.config.enabled; - } - /** - * Initialize the telemetry service - */ - async initialize(identity) { - if (!this.enabled) { - if (this.config.debug) { - console.log("[Telemetry] Disabled via configuration"); - } - return; - } - try { - this.identity = identity; - if (this.config.debug) { - console.log("[Telemetry] Initialized with installation ID:", identity.installationId); - } - this.isInitialized = true; - await this.flushQueue(); - } catch (error) { - if (this.config.debug) { - console.error("[Telemetry] Initialization failed:", error); - } - this.enabled = false; - } - } - /** - * Track a telemetry event - */ - async track(event, properties) { - if (!this.enabled) return; - try { - const sanitizedProps = this.sanitizeProperties(properties); - const enrichedProps = { - ...sanitizedProps, - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - version: this.getVersion() - }; - if (!this.isInitialized) { - this.eventQueue.push({ event, properties: enrichedProps }); - if (this.config.debug) { - console.log("[Telemetry] Queued event:", event, enrichedProps); - } - return; - } - if (this.identity && this.config.host) { - const payload = { - data: { - installation_id: this.identity.installationId, - event_type: event, - properties: enrichedProps, - timestamp: enrichedProps.timestamp - } - }; - fetch(`${this.config.host}/v1/events`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload) - }).catch(() => { - }); - if (this.config.debug) { - console.log("[Telemetry] Tracked event:", event, enrichedProps); - } - } else if (this.config.debug) { - console.log("[Telemetry] Event (no endpoint):", event, enrichedProps); - } - } catch (error) { - if (this.config.debug) { - console.error("[Telemetry] Failed to track event:", error); - } - } - } - /** - * Track installation started - */ - async trackInstallationStarted(properties) { - await this.track("installation_started", properties); - } - /** - * Track installation completed - */ - async trackInstallationCompleted(properties) { - await this.track("installation_completed", properties); - } - /** - * Track installation failed - */ - async trackInstallationFailed(error, properties) { - await this.track("installation_failed", { - ...properties, - errorType: chunkP3XDZL6Q_cjs.sanitizeErrorMessage(error) - }); - } - /** - * Track dev server started - */ - async trackDevServerStarted(properties) { - await this.track("dev_server_started", properties); - } - /** - * Track page view in admin UI - */ - async trackPageView(route, properties) { - await this.track("page_viewed", { - ...properties, - route: chunkP3XDZL6Q_cjs.sanitizeRoute(route) - }); - } - /** - * Track error (sanitized) - */ - async trackError(error, properties) { - await this.track("error_occurred", { - ...properties, - errorType: chunkP3XDZL6Q_cjs.sanitizeErrorMessage(error) - }); - } - /** - * Track plugin activation - */ - async trackPluginActivated(properties) { - await this.track("plugin_activated", properties); - } - /** - * Track migration run - */ - async trackMigrationRun(properties) { - await this.track("migration_run", properties); - } - /** - * Flush queued events - */ - async flushQueue() { - if (this.eventQueue.length === 0) return; - const queue = [...this.eventQueue]; - this.eventQueue = []; - for (const { event, properties } of queue) { - await this.track(event, properties); - } - } - /** - * Sanitize properties to ensure no PII - */ - sanitizeProperties(properties) { - if (!properties) return {}; - const sanitized = {}; - for (const [key, value] of Object.entries(properties)) { - if (value === void 0) continue; - if (key === "route" && typeof value === "string") { - sanitized[key] = chunkP3XDZL6Q_cjs.sanitizeRoute(value); - continue; - } - if (key.toLowerCase().includes("error") && typeof value === "string") { - sanitized[key] = chunkP3XDZL6Q_cjs.sanitizeErrorMessage(value); - continue; - } - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - sanitized[key] = value; - } - } - return sanitized; - } - /** - * Get SonicJS version - */ - getVersion() { - try { - if (typeof process !== "undefined" && process.env) { - return process.env.SONICJS_VERSION || "2.0.0"; - } - return "2.0.0"; - } catch { - return "unknown"; - } - } - /** - * Shutdown the telemetry service (no-op for fetch-based telemetry) - */ - async shutdown() { - } - /** - * Enable telemetry - */ - enable() { - this.enabled = true; - } - /** - * Disable telemetry - */ - disable() { - this.enabled = false; - } - /** - * Check if telemetry is enabled - */ - isEnabled() { - return this.enabled; - } -}; -var telemetryInstance = null; -function getTelemetryService(config) { - if (!telemetryInstance) { - telemetryInstance = new TelemetryService(config); - } - return telemetryInstance; -} -async function initTelemetry(identity, config) { - const service = getTelemetryService(config); - await service.initialize(identity); - return service; -} -function createInstallationIdentity(projectName) { - const installationId = chunkP3XDZL6Q_cjs.generateInstallationId(); - const identity = { installationId }; - if (projectName) { - identity.projectId = chunkP3XDZL6Q_cjs.generateProjectId(projectName); - } - return identity; -} - -exports.CACHE_CONFIGS = CACHE_CONFIGS; -exports.CacheService = CacheService; -exports.Logger = Logger; -exports.SettingsService = SettingsService; -exports.TelemetryService = TelemetryService; -exports.apiTokens = apiTokens; -exports.collections = collections; -exports.content = content; -exports.contentVersions = contentVersions; -exports.createInstallationIdentity = createInstallationIdentity; -exports.getCacheService = getCacheService; -exports.getLogger = getLogger; -exports.getTelemetryService = getTelemetryService; -exports.initLogger = initLogger; -exports.initTelemetry = initTelemetry; -exports.insertCollectionSchema = insertCollectionSchema; -exports.insertContentSchema = insertContentSchema; -exports.insertLogConfigSchema = insertLogConfigSchema; -exports.insertMediaSchema = insertMediaSchema; -exports.insertPluginActivityLogSchema = insertPluginActivityLogSchema; -exports.insertPluginAssetSchema = insertPluginAssetSchema; -exports.insertPluginHookSchema = insertPluginHookSchema; -exports.insertPluginRouteSchema = insertPluginRouteSchema; -exports.insertPluginSchema = insertPluginSchema; -exports.insertSystemLogSchema = insertSystemLogSchema; -exports.insertUserSchema = insertUserSchema; -exports.insertWorkflowHistorySchema = insertWorkflowHistorySchema; -exports.logConfig = logConfig; -exports.media = media; -exports.pluginActivityLog = pluginActivityLog; -exports.pluginAssets = pluginAssets; -exports.pluginHooks = pluginHooks; -exports.pluginRoutes = pluginRoutes; -exports.plugins = plugins; -exports.schema_exports = schema_exports; -exports.selectCollectionSchema = selectCollectionSchema; -exports.selectContentSchema = selectContentSchema; -exports.selectLogConfigSchema = selectLogConfigSchema; -exports.selectMediaSchema = selectMediaSchema; -exports.selectPluginActivityLogSchema = selectPluginActivityLogSchema; -exports.selectPluginAssetSchema = selectPluginAssetSchema; -exports.selectPluginHookSchema = selectPluginHookSchema; -exports.selectPluginRouteSchema = selectPluginRouteSchema; -exports.selectPluginSchema = selectPluginSchema; -exports.selectSystemLogSchema = selectSystemLogSchema; -exports.selectUserSchema = selectUserSchema; -exports.selectWorkflowHistorySchema = selectWorkflowHistorySchema; -exports.systemLogs = systemLogs; -exports.users = users; -exports.workflowHistory = workflowHistory; -//# sourceMappingURL=chunk-VNLR35GO.cjs.map -//# sourceMappingURL=chunk-VNLR35GO.cjs.map \ No newline at end of file diff --git a/packages/core/dist/collection-config-BF95LgQb.d.cts b/packages/core/dist/collection-config-BF95LgQb.d.cts deleted file mode 100644 index 879f85a09..000000000 --- a/packages/core/dist/collection-config-BF95LgQb.d.cts +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Collection Configuration Types - * - * These types define the structure for collection configuration files. - * Collections can be defined in TypeScript/JSON files and synced to the database. - */ -type FieldType = 'string' | 'number' | 'boolean' | 'date' | 'datetime' | 'email' | 'url' | 'richtext' | 'markdown' | 'json' | 'array' | 'object' | 'reference' | 'media' | 'select' | 'multiselect' | 'checkbox' | 'radio' | 'textarea' | 'slug' | 'color' | 'file'; -interface BlockDefinition { - label?: string; - description?: string; - properties: Record; -} -type BlockDefinitions = Record; -interface FieldConfig { - type: FieldType; - title?: string; - description?: string; - required?: boolean; - default?: any; - placeholder?: string; - helpText?: string; - min?: number; - max?: number; - minLength?: number; - maxLength?: number; - pattern?: string; - enum?: string[]; - enumLabels?: string[]; - collection?: string | string[]; - items?: FieldConfig; - properties?: Record; - blocks?: BlockDefinitions; - discriminator?: string; - format?: string; - widget?: string; - dependsOn?: string; - showWhen?: any; -} -interface CollectionSchema { - type: 'object'; - properties: Record; - required?: string[]; -} -interface CollectionConfig { - /** - * Unique machine name for the collection (lowercase, underscores) - * e.g., 'blog_posts', 'products', 'team_members' - */ - name: string; - /** - * Human-readable display name - * e.g., 'Blog Posts', 'Products', 'Team Members' - */ - displayName: string; - /** - * Optional description of the collection - */ - description?: string; - /** - * JSON schema definition for the collection's content structure - */ - schema: CollectionSchema; - /** - * If true, this collection is managed by config files and cannot be edited in the UI - * Default: true for config-based collections - */ - managed?: boolean; - /** - * If true, the collection is active and available for use - * Default: true - */ - isActive?: boolean; - /** - * Optional icon name for the collection (used in admin UI) - */ - icon?: string; - /** - * Optional color for the collection (hex code) - */ - color?: string; - /** - * Optional default sort field - */ - defaultSort?: string; - /** - * Optional default sort order - */ - defaultSortOrder?: 'asc' | 'desc'; - /** - * Optional fields to show in list view - */ - listFields?: string[]; - /** - * Optional search fields - */ - searchFields?: string[]; - /** - * Optional metadata - */ - metadata?: Record; -} -interface CollectionConfigModule { - default: CollectionConfig; -} -/** - * Result of syncing a collection - */ -interface CollectionSyncResult { - name: string; - status: 'created' | 'updated' | 'unchanged' | 'error'; - message?: string; - error?: string; -} - -export type { BlockDefinition as B, CollectionSchema as C, FieldType as F, FieldConfig as a, BlockDefinitions as b, CollectionConfig as c, CollectionConfigModule as d, CollectionSyncResult as e }; diff --git a/packages/core/dist/collection-config-BF95LgQb.d.ts b/packages/core/dist/collection-config-BF95LgQb.d.ts deleted file mode 100644 index 879f85a09..000000000 --- a/packages/core/dist/collection-config-BF95LgQb.d.ts +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Collection Configuration Types - * - * These types define the structure for collection configuration files. - * Collections can be defined in TypeScript/JSON files and synced to the database. - */ -type FieldType = 'string' | 'number' | 'boolean' | 'date' | 'datetime' | 'email' | 'url' | 'richtext' | 'markdown' | 'json' | 'array' | 'object' | 'reference' | 'media' | 'select' | 'multiselect' | 'checkbox' | 'radio' | 'textarea' | 'slug' | 'color' | 'file'; -interface BlockDefinition { - label?: string; - description?: string; - properties: Record; -} -type BlockDefinitions = Record; -interface FieldConfig { - type: FieldType; - title?: string; - description?: string; - required?: boolean; - default?: any; - placeholder?: string; - helpText?: string; - min?: number; - max?: number; - minLength?: number; - maxLength?: number; - pattern?: string; - enum?: string[]; - enumLabels?: string[]; - collection?: string | string[]; - items?: FieldConfig; - properties?: Record; - blocks?: BlockDefinitions; - discriminator?: string; - format?: string; - widget?: string; - dependsOn?: string; - showWhen?: any; -} -interface CollectionSchema { - type: 'object'; - properties: Record; - required?: string[]; -} -interface CollectionConfig { - /** - * Unique machine name for the collection (lowercase, underscores) - * e.g., 'blog_posts', 'products', 'team_members' - */ - name: string; - /** - * Human-readable display name - * e.g., 'Blog Posts', 'Products', 'Team Members' - */ - displayName: string; - /** - * Optional description of the collection - */ - description?: string; - /** - * JSON schema definition for the collection's content structure - */ - schema: CollectionSchema; - /** - * If true, this collection is managed by config files and cannot be edited in the UI - * Default: true for config-based collections - */ - managed?: boolean; - /** - * If true, the collection is active and available for use - * Default: true - */ - isActive?: boolean; - /** - * Optional icon name for the collection (used in admin UI) - */ - icon?: string; - /** - * Optional color for the collection (hex code) - */ - color?: string; - /** - * Optional default sort field - */ - defaultSort?: string; - /** - * Optional default sort order - */ - defaultSortOrder?: 'asc' | 'desc'; - /** - * Optional fields to show in list view - */ - listFields?: string[]; - /** - * Optional search fields - */ - searchFields?: string[]; - /** - * Optional metadata - */ - metadata?: Record; -} -interface CollectionConfigModule { - default: CollectionConfig; -} -/** - * Result of syncing a collection - */ -interface CollectionSyncResult { - name: string; - status: 'created' | 'updated' | 'unchanged' | 'error'; - message?: string; - error?: string; -} - -export type { BlockDefinition as B, CollectionSchema as C, FieldType as F, FieldConfig as a, BlockDefinitions as b, CollectionConfig as c, CollectionConfigModule as d, CollectionSyncResult as e }; diff --git a/packages/core/dist/filter-bar.template-By4jeiw_.d.cts b/packages/core/dist/filter-bar.template-By4jeiw_.d.cts deleted file mode 100644 index 780e5584e..000000000 --- a/packages/core/dist/filter-bar.template-By4jeiw_.d.cts +++ /dev/null @@ -1,140 +0,0 @@ -interface FormField { - name: string; - label: string; - type: 'text' | 'email' | 'textarea' | 'select' | 'checkbox' | 'rich_text' | 'number' | 'date' | 'multi_select' | 'file'; - value?: any; - placeholder?: string; - required?: boolean; - readonly?: boolean; - helpText?: string; - options?: Array<{ - value: string; - label: string; - selected?: boolean; - }>; - rows?: number; - className?: string; - validation?: { - min?: number; - max?: number; - pattern?: string; - }; -} -interface FormData { - id?: string; - action?: string; - method?: string; - hxPost?: string; - hxPut?: string; - hxTarget?: string; - fields: FormField[]; - submitButtons: Array<{ - label: string; - type?: 'submit' | 'button'; - value?: string; - name?: string; - className?: string; - onclick?: string; - }>; - title?: string; - description?: string; - className?: string; -} -declare function renderForm(data: FormData): string; -declare function renderFormField(field: FormField): string; - -interface TableColumn { - key: string; - label: string; - sortable?: boolean; - className?: string; - sortType?: 'string' | 'number' | 'date' | 'boolean'; - render?: (value: any, row: any) => string; -} -interface TableData { - columns: TableColumn[]; - rows: T[]; - selectable?: boolean; - className?: string; - emptyMessage?: string; - tableId?: string; - title?: string; - rowClickable?: boolean; - rowClickUrl?: (row: T) => string; -} -declare function renderTable(data: TableData): string; - -interface PaginationData { - currentPage: number; - totalPages: number; - totalItems: number; - itemsPerPage: number; - startItem: number; - endItem: number; - baseUrl: string; - queryParams?: Record; - showPageNumbers?: boolean; - maxPageNumbers?: number; - showPageSizeSelector?: boolean; - pageSizeOptions?: number[]; -} -declare function renderPagination(data: PaginationData): string; - -type AlertType = 'success' | 'error' | 'warning' | 'info'; -interface AlertData { - type: AlertType; - title?: string; - message: string; - dismissible?: boolean; - className?: string; - icon?: boolean; -} -declare function renderAlert(data: AlertData): string; - -interface ConfirmationDialogOptions { - id: string; - title: string; - message: string; - confirmText?: string; - cancelText?: string; - confirmClass?: string; - iconColor?: 'red' | 'yellow' | 'blue'; - onConfirm?: string; -} -declare function renderConfirmationDialog(options: ConfirmationDialogOptions): string; -/** - * Helper function to show a confirmation dialog programmatically - * Usage in templates: Add this script and call showConfirmDialog() - */ -declare function getConfirmationDialogScript(): string; - -interface FilterOption { - value: string; - label: string; - selected?: boolean; - color?: string; -} -interface Filter { - name: string; - label: string; - options: FilterOption[]; -} -interface FilterBarData { - filters: Filter[]; - actions?: Array<{ - label: string; - className?: string; - onclick?: string; - hxGet?: string; - hxTarget?: string; - }>; - bulkActions?: Array<{ - label: string; - value: string; - icon?: string; - className?: string; - }>; -} -declare function renderFilterBar(data: FilterBarData): string; - -export { type AlertData as A, type ConfirmationDialogOptions as C, type FormField as F, type PaginationData as P, type TableColumn as T, renderFormField as a, renderTable as b, renderPagination as c, renderAlert as d, renderConfirmationDialog as e, renderFilterBar as f, getConfirmationDialogScript as g, type FormData as h, type TableData as i, type FilterBarData as j, type Filter as k, type FilterOption as l, renderForm as r }; diff --git a/packages/core/dist/filter-bar.template-By4jeiw_.d.ts b/packages/core/dist/filter-bar.template-By4jeiw_.d.ts deleted file mode 100644 index 780e5584e..000000000 --- a/packages/core/dist/filter-bar.template-By4jeiw_.d.ts +++ /dev/null @@ -1,140 +0,0 @@ -interface FormField { - name: string; - label: string; - type: 'text' | 'email' | 'textarea' | 'select' | 'checkbox' | 'rich_text' | 'number' | 'date' | 'multi_select' | 'file'; - value?: any; - placeholder?: string; - required?: boolean; - readonly?: boolean; - helpText?: string; - options?: Array<{ - value: string; - label: string; - selected?: boolean; - }>; - rows?: number; - className?: string; - validation?: { - min?: number; - max?: number; - pattern?: string; - }; -} -interface FormData { - id?: string; - action?: string; - method?: string; - hxPost?: string; - hxPut?: string; - hxTarget?: string; - fields: FormField[]; - submitButtons: Array<{ - label: string; - type?: 'submit' | 'button'; - value?: string; - name?: string; - className?: string; - onclick?: string; - }>; - title?: string; - description?: string; - className?: string; -} -declare function renderForm(data: FormData): string; -declare function renderFormField(field: FormField): string; - -interface TableColumn { - key: string; - label: string; - sortable?: boolean; - className?: string; - sortType?: 'string' | 'number' | 'date' | 'boolean'; - render?: (value: any, row: any) => string; -} -interface TableData { - columns: TableColumn[]; - rows: T[]; - selectable?: boolean; - className?: string; - emptyMessage?: string; - tableId?: string; - title?: string; - rowClickable?: boolean; - rowClickUrl?: (row: T) => string; -} -declare function renderTable(data: TableData): string; - -interface PaginationData { - currentPage: number; - totalPages: number; - totalItems: number; - itemsPerPage: number; - startItem: number; - endItem: number; - baseUrl: string; - queryParams?: Record; - showPageNumbers?: boolean; - maxPageNumbers?: number; - showPageSizeSelector?: boolean; - pageSizeOptions?: number[]; -} -declare function renderPagination(data: PaginationData): string; - -type AlertType = 'success' | 'error' | 'warning' | 'info'; -interface AlertData { - type: AlertType; - title?: string; - message: string; - dismissible?: boolean; - className?: string; - icon?: boolean; -} -declare function renderAlert(data: AlertData): string; - -interface ConfirmationDialogOptions { - id: string; - title: string; - message: string; - confirmText?: string; - cancelText?: string; - confirmClass?: string; - iconColor?: 'red' | 'yellow' | 'blue'; - onConfirm?: string; -} -declare function renderConfirmationDialog(options: ConfirmationDialogOptions): string; -/** - * Helper function to show a confirmation dialog programmatically - * Usage in templates: Add this script and call showConfirmDialog() - */ -declare function getConfirmationDialogScript(): string; - -interface FilterOption { - value: string; - label: string; - selected?: boolean; - color?: string; -} -interface Filter { - name: string; - label: string; - options: FilterOption[]; -} -interface FilterBarData { - filters: Filter[]; - actions?: Array<{ - label: string; - className?: string; - onclick?: string; - hxGet?: string; - hxTarget?: string; - }>; - bulkActions?: Array<{ - label: string; - value: string; - icon?: string; - className?: string; - }>; -} -declare function renderFilterBar(data: FilterBarData): string; - -export { type AlertData as A, type ConfirmationDialogOptions as C, type FormField as F, type PaginationData as P, type TableColumn as T, renderFormField as a, renderTable as b, renderPagination as c, renderAlert as d, renderConfirmationDialog as e, renderFilterBar as f, getConfirmationDialogScript as g, type FormData as h, type TableData as i, type FilterBarData as j, type Filter as k, type FilterOption as l, renderForm as r }; diff --git a/packages/core/dist/index.cjs b/packages/core/dist/index.cjs deleted file mode 100644 index f2d10fe36..000000000 --- a/packages/core/dist/index.cjs +++ /dev/null @@ -1,6610 +0,0 @@ -'use strict'; - -var chunkVAPDSKKV_cjs = require('./chunk-VAPDSKKV.cjs'); -var chunkVNLR35GO_cjs = require('./chunk-VNLR35GO.cjs'); -var chunkDVQA5II3_cjs = require('./chunk-DVQA5II3.cjs'); -var chunkMPT5PA6U_cjs = require('./chunk-MPT5PA6U.cjs'); -var chunkFQSMNIY2_cjs = require('./chunk-FQSMNIY2.cjs'); -var chunkS6K2H2TS_cjs = require('./chunk-S6K2H2TS.cjs'); -var chunkSHCYIZAN_cjs = require('./chunk-SHCYIZAN.cjs'); -var chunkMNFY6DWY_cjs = require('./chunk-MNFY6DWY.cjs'); -var chunk6FHNRRJ3_cjs = require('./chunk-6FHNRRJ3.cjs'); -var chunk5HMR2SJW_cjs = require('./chunk-5HMR2SJW.cjs'); -require('./chunk-P3XDZL6Q.cjs'); -var chunkRCQ2HIQD_cjs = require('./chunk-RCQ2HIQD.cjs'); -var chunkKYGRJCZM_cjs = require('./chunk-KYGRJCZM.cjs'); -require('./chunk-IGJUBJBW.cjs'); -var hono = require('hono'); -var cookie = require('hono/cookie'); -var zod = require('zod'); -var d1 = require('drizzle-orm/d1'); - -// src/plugins/core-plugins/database-tools-plugin/services/database-service.ts -var DatabaseToolsService = class { - constructor(db) { - this.db = db; - } - /** - * Get database statistics - */ - async getDatabaseStats() { - const tables = await this.getTables(); - const stats = { - tables: [], - totalRows: 0 - }; - for (const tableName of tables) { - try { - const result = await this.db.prepare(`SELECT COUNT(*) as count FROM ${tableName}`).first(); - const rowCount = result?.count || 0; - stats.tables.push({ - name: tableName, - rowCount - }); - stats.totalRows += rowCount; - } catch (error) { - console.warn(`Could not count rows in table ${tableName}:`, error); - } - } - return stats; - } - /** - * Get all tables in the database - */ - async getTables() { - const result = await this.db.prepare(` - SELECT name FROM sqlite_master - WHERE type='table' - AND name NOT LIKE 'sqlite_%' - ORDER BY name - `).all(); - return result.results?.map((row) => row.name) || []; - } - /** - * Truncate all data except admin user - */ - async truncateAllData(adminEmail) { - const errors = []; - const tablesCleared = []; - let adminUserPreserved = false; - try { - const adminUser = await this.db.prepare( - "SELECT * FROM users WHERE email = ? AND role = ?" - ).bind(adminEmail, "admin").first(); - if (!adminUser) { - return { - success: false, - message: "Admin user not found. Operation cancelled for safety.", - tablesCleared: [], - adminUserPreserved: false, - errors: ["Admin user not found"] - }; - } - const tablesToTruncate = [ - "content", - "content_versions", - "content_workflow_status", - "collections", - "media", - "sessions", - "notifications", - "api_tokens", - "workflow_history", - "scheduled_content", - "faqs", - "faq_categories", - "plugins", - "plugin_settings", - "email_templates", - "email_themes" - ]; - const existingTables = await this.getTables(); - const tablesToClear = tablesToTruncate.filter( - (table) => existingTables.includes(table) - ); - for (const tableName of tablesToClear) { - try { - await this.db.prepare(`DELETE FROM ${tableName}`).run(); - tablesCleared.push(tableName); - } catch (error) { - errors.push(`Failed to clear table ${tableName}: ${error}`); - console.error(`Error clearing table ${tableName}:`, error); - } - } - try { - await this.db.prepare("DELETE FROM users WHERE email != ? OR role != ?").bind(adminEmail, "admin").run(); - const verifyAdmin = await this.db.prepare( - "SELECT id FROM users WHERE email = ? AND role = ?" - ).bind(adminEmail, "admin").first(); - adminUserPreserved = !!verifyAdmin; - tablesCleared.push("users (non-admin)"); - } catch (error) { - errors.push(`Failed to clear non-admin users: ${error}`); - console.error("Error clearing non-admin users:", error); - } - try { - await this.db.prepare("DELETE FROM sqlite_sequence").run(); - } catch (error) { - } - const message = errors.length > 0 ? `Truncation completed with ${errors.length} errors. ${tablesCleared.length} tables cleared.` : `Successfully truncated database. ${tablesCleared.length} tables cleared.`; - return { - success: errors.length === 0, - message, - tablesCleared, - adminUserPreserved, - errors: errors.length > 0 ? errors : void 0 - }; - } catch (error) { - return { - success: false, - message: `Database truncation failed: ${error}`, - tablesCleared, - adminUserPreserved, - errors: [String(error)] - }; - } - } - /** - * Create a backup of current data (simplified version) - */ - async createBackup() { - try { - const backupId = `backup_${Date.now()}`; - const stats = await this.getDatabaseStats(); - console.log(`Backup ${backupId} created with ${stats.totalRows} total rows`); - return { - success: true, - message: `Backup created successfully (${stats.totalRows} rows)`, - backupId - }; - } catch (error) { - return { - success: false, - message: `Backup failed: ${error}` - }; - } - } - /** - * Get table data with optional pagination and sorting - */ - async getTableData(tableName, limit = 100, offset = 0, sortColumn, sortDirection = "asc") { - try { - const tables = await this.getTables(); - if (!tables.includes(tableName)) { - throw new Error(`Table ${tableName} not found`); - } - const pragmaResult = await this.db.prepare(`PRAGMA table_info(${tableName})`).all(); - const columns = pragmaResult.results?.map((col) => col.name) || []; - if (sortColumn && !columns.includes(sortColumn)) { - sortColumn = void 0; - } - const countResult = await this.db.prepare(`SELECT COUNT(*) as count FROM ${tableName}`).first(); - const totalRows = countResult?.count || 0; - let query = `SELECT * FROM ${tableName}`; - if (sortColumn) { - query += ` ORDER BY ${sortColumn} ${sortDirection.toUpperCase()}`; - } - query += ` LIMIT ${limit} OFFSET ${offset}`; - const dataResult = await this.db.prepare(query).all(); - return { - tableName, - columns, - rows: dataResult.results || [], - totalRows - }; - } catch (error) { - throw new Error(`Failed to fetch table data: ${error}`); - } - } - /** - * Validate database integrity - */ - async validateDatabase() { - const issues = []; - try { - const requiredTables = ["users", "content", "collections"]; - const existingTables = await this.getTables(); - for (const table of requiredTables) { - if (!existingTables.includes(table)) { - issues.push(`Critical table missing: ${table}`); - } - } - const adminCount = await this.db.prepare( - "SELECT COUNT(*) as count FROM users WHERE role = ?" - ).bind("admin").first(); - if (adminCount?.count === 0) { - issues.push("No admin users found"); - } - try { - const integrityResult = await this.db.prepare("PRAGMA integrity_check").first(); - if (integrityResult && integrityResult.integrity_check !== "ok") { - issues.push(`Database integrity check failed: ${integrityResult.integrity_check}`); - } - } catch (error) { - issues.push(`Could not run integrity check: ${error}`); - } - } catch (error) { - issues.push(`Validation error: ${error}`); - } - return { - valid: issues.length === 0, - issues - }; - } -}; - -// src/templates/pages/admin-database-table.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderDatabaseTablePage(data) { - const totalPages = Math.ceil(data.totalRows / data.pageSize); - const startRow = (data.currentPage - 1) * data.pageSize + 1; - const endRow = Math.min(data.currentPage * data.pageSize, data.totalRows); - const pageContent = ` -
- -
-
- -

Table: ${data.tableName}

-

- Showing ${startRow.toLocaleString()} - ${endRow.toLocaleString()} of ${data.totalRows.toLocaleString()} rows -

-
-
-
- - -
- -
-
- - -
- -
- - - - ${data.columns.map((col) => ` - - `).join("")} - - - - ${data.rows.length > 0 ? data.rows.map((row, idx) => ` - - ${data.columns.map((col) => ` - - `).join("")} - - `).join("") : ` - - - - `} - -
-
- ${col} - ${data.sortColumn === col ? ` - - - - ` : ` - - - - `} -
-
- ${formatCellValue(row[col])} -
- - - -

No data in this table

-
-
- - - ${totalPages > 1 ? ` -
-
- - -
- -
- ` : ""} -
-
- - - `; - const layoutData = { - title: `Table: ${data.tableName}`, - pageTitle: `Database: ${data.tableName}`, - currentPath: `/admin/database-tools/tables/${data.tableName}`, - user: data.user, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} -function generatePageNumbers(currentPage, totalPages) { - const pages = []; - const maxVisible = 7; - if (totalPages <= maxVisible) { - for (let i = 1; i <= totalPages; i++) { - pages.push(i); - } - } else { - if (currentPage <= 4) { - for (let i = 1; i <= 5; i++) pages.push(i); - pages.push(-1); - pages.push(totalPages); - } else if (currentPage >= totalPages - 3) { - pages.push(1); - pages.push(-1); - for (let i = totalPages - 4; i <= totalPages; i++) pages.push(i); - } else { - pages.push(1); - pages.push(-1); - for (let i = currentPage - 1; i <= currentPage + 1; i++) pages.push(i); - pages.push(-1); - pages.push(totalPages); - } - } - return pages.map((page) => { - if (page === -1) { - return ` - - ... - - `; - } - const isActive = page === currentPage; - return ` - - `; - }).join(""); -} -function escapeHtml2(text) { - const map = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'" - }; - return String(text).replace(/[&<>"']/g, (m) => map[m] || m); -} -function formatCellValue(value) { - if (value === null || value === void 0) { - return 'null'; - } - if (typeof value === "boolean") { - return `${value}`; - } - if (typeof value === "object") { - return '' + JSON.stringify(value).substring(0, 50) + (JSON.stringify(value).length > 50 ? "..." : "") + ""; - } - const str = String(value); - if (str.length > 100) { - return escapeHtml2(str.substring(0, 100)) + "..."; - } - return escapeHtml2(str); -} - -// src/plugins/core-plugins/database-tools-plugin/admin-routes.ts -function createDatabaseToolsAdminRoutes() { - const router3 = new hono.Hono(); - router3.use("*", chunkDVQA5II3_cjs.requireAuth()); - router3.get("/api/stats", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.json({ - success: false, - error: "Unauthorized. Admin access required." - }, 403); - } - const db = c.env.DB; - const service = new DatabaseToolsService(db); - const stats = await service.getDatabaseStats(); - return c.json({ - success: true, - data: stats - }); - } catch (error) { - console.error("Error fetching database stats:", error); - return c.json({ - success: false, - error: "Failed to fetch database statistics" - }, 500); - } - }); - router3.post("/api/truncate", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.json({ - success: false, - error: "Unauthorized. Admin access required." - }, 403); - } - const body = await c.req.json(); - const { confirmText } = body; - if (confirmText !== "TRUNCATE ALL DATA") { - return c.json({ - success: false, - error: "Invalid confirmation text. Operation cancelled." - }, 400); - } - const db = c.env.DB; - const service = new DatabaseToolsService(db); - const result = await service.truncateAllData(user.email); - return c.json({ - success: result.success, - message: result.message, - data: { - tablesCleared: result.tablesCleared, - adminUserPreserved: result.adminUserPreserved, - errors: result.errors - } - }); - } catch (error) { - console.error("Error truncating database:", error); - return c.json({ - success: false, - error: "Failed to truncate database" - }, 500); - } - }); - router3.post("/api/backup", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.json({ - success: false, - error: "Unauthorized. Admin access required." - }, 403); - } - const db = c.env.DB; - const service = new DatabaseToolsService(db); - const result = await service.createBackup(); - return c.json({ - success: result.success, - message: result.message, - data: { - backupId: result.backupId - } - }); - } catch (error) { - console.error("Error creating backup:", error); - return c.json({ - success: false, - error: "Failed to create backup" - }, 500); - } - }); - router3.get("/api/validate", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.json({ - success: false, - error: "Unauthorized. Admin access required." - }, 403); - } - const db = c.env.DB; - const service = new DatabaseToolsService(db); - const validation = await service.validateDatabase(); - return c.json({ - success: true, - data: validation - }); - } catch (error) { - console.error("Error validating database:", error); - return c.json({ - success: false, - error: "Failed to validate database" - }, 500); - } - }); - router3.get("/api/tables/:tableName", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.json({ - success: false, - error: "Unauthorized. Admin access required." - }, 403); - } - const tableName = c.req.param("tableName"); - const limit = parseInt(c.req.query("limit") || "100"); - const offset = parseInt(c.req.query("offset") || "0"); - const sortColumn = c.req.query("sort"); - const sortDirection = c.req.query("dir") || "asc"; - const db = c.env.DB; - const service = new DatabaseToolsService(db); - const tableData = await service.getTableData(tableName, limit, offset, sortColumn, sortDirection); - return c.json({ - success: true, - data: tableData - }); - } catch (error) { - console.error("Error fetching table data:", error); - return c.json({ - success: false, - error: `Failed to fetch table data: ${error}` - }, 500); - } - }); - router3.get("/tables/:tableName", async (c) => { - try { - const user = c.get("user"); - if (!user || user.role !== "admin") { - return c.redirect("/admin/login"); - } - const tableName = c.req.param("tableName"); - const page = parseInt(c.req.query("page") || "1"); - const pageSize = parseInt(c.req.query("pageSize") || "20"); - const sortColumn = c.req.query("sort"); - const sortDirection = c.req.query("dir") || "asc"; - const offset = (page - 1) * pageSize; - const db = c.env.DB; - const service = new DatabaseToolsService(db); - const tableData = await service.getTableData(tableName, pageSize, offset, sortColumn, sortDirection); - const pageData = { - user: { - name: user.email.split("@")[0] || "Unknown", - email: user.email, - role: user.role - }, - tableName: tableData.tableName, - columns: tableData.columns, - rows: tableData.rows, - totalRows: tableData.totalRows, - currentPage: page, - pageSize, - sortColumn, - sortDirection - }; - return c.html(renderDatabaseTablePage(pageData)); - } catch (error) { - console.error("Error rendering table page:", error); - return c.text(`Error: ${error}`, 500); - } - }); - return router3; -} - -// src/plugins/core-plugins/seed-data-plugin/services/seed-data-service.ts -var SeedDataService = class { - constructor(db) { - this.db = db; - } - // First names for generating realistic users - firstNames = [ - "Emma", - "Liam", - "Olivia", - "Noah", - "Ava", - "Ethan", - "Sophia", - "Mason", - "Isabella", - "William", - "Mia", - "James", - "Charlotte", - "Benjamin", - "Amelia", - "Lucas", - "Harper", - "Henry", - "Evelyn", - "Alexander" - ]; - // Last names for generating realistic users - lastNames = [ - "Smith", - "Johnson", - "Williams", - "Brown", - "Jones", - "Garcia", - "Miller", - "Davis", - "Rodriguez", - "Martinez", - "Hernandez", - "Lopez", - "Gonzalez", - "Wilson", - "Anderson", - "Thomas", - "Taylor", - "Moore", - "Jackson", - "Martin" - ]; - // Content titles for blog posts - blogTitles = [ - "Getting Started with Modern Web Development", - "The Future of JavaScript Frameworks", - "Building Scalable Applications with Microservices", - "Understanding TypeScript: A Complete Guide", - "Best Practices for API Design", - "Introduction to Cloud Computing", - "Mastering Git and Version Control", - "The Art of Code Review", - "Performance Optimization Techniques", - "Security Best Practices for Web Apps", - "Exploring Serverless Architecture", - "Database Design Fundamentals", - "Testing Strategies for Modern Apps", - "CI/CD Pipeline Implementation", - "Mobile-First Development Approach" - ]; - // Content titles for pages - pageTitles = [ - "About Us", - "Contact", - "Privacy Policy", - "Terms of Service", - "FAQ", - "Our Team", - "Careers", - "Press Kit", - "Support", - "Documentation", - "Pricing", - "Features" - ]; - // Content titles for products - productTitles = [ - "Premium Wireless Headphones", - "Smart Watch Pro", - "Laptop Stand Adjustable", - "Mechanical Keyboard RGB", - "HD Webcam 4K", - "USB-C Hub 7-in-1", - "Portable SSD 1TB", - "Wireless Mouse Ergonomic", - 'Monitor 27" 4K', - "Desk Lamp LED", - "Phone Case Premium", - "Tablet Stand Aluminum", - "Cable Management Kit", - "Power Bank 20000mAh", - "Bluetooth Speaker Portable" - ]; - // Content for generating blog posts - blogContent = [ - "This comprehensive guide covers everything you need to know about modern development practices and tools.", - "Learn the fundamentals and advanced concepts that will help you build better applications.", - "Discover the latest trends and best practices used by industry professionals.", - "A deep dive into the technologies and methodologies shaping the future of software development.", - "Practical tips and real-world examples to improve your development workflow.", - "Explore cutting-edge techniques and proven strategies for building robust applications.", - "Master the essential skills needed to excel in modern software development.", - "An in-depth look at the tools and frameworks that power today's web applications.", - "Step-by-step instructions and expert insights for developers of all levels.", - "Understanding the core principles that drive successful software projects." - ]; - // Generate a random ID - generateId() { - return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - // Generate a slug from a title - generateSlug(title) { - return title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, ""); - } - // Generate random date within the last year - randomDate() { - const now = /* @__PURE__ */ new Date(); - const yearAgo = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate()); - const randomTime = yearAgo.getTime() + Math.random() * (now.getTime() - yearAgo.getTime()); - return new Date(randomTime); - } - // Create 20 example users - async createUsers() { - const roles = ["admin", "editor", "author", "viewer"]; - const hashedPassword = "password123"; - let count = 0; - for (let i = 0; i < 20; i++) { - const firstName = this.firstNames[Math.floor(Math.random() * this.firstNames.length)] || "John"; - const lastName = this.lastNames[Math.floor(Math.random() * this.lastNames.length)] || "Doe"; - const username = `${firstName.toLowerCase()}${lastName.toLowerCase()}${i}`; - const email = `${username}@example.com`; - const createdAt = this.randomDate(); - const createdAtTimestamp = Math.floor(createdAt.getTime() / 1e3); - const stmt = this.db.prepare(` - INSERT INTO users (id, email, username, first_name, last_name, password_hash, role, is_active, last_login_at, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await stmt.bind( - this.generateId(), - email, - username, - firstName, - lastName, - hashedPassword, - roles[Math.floor(Math.random() * roles.length)], - Math.random() > 0.1 ? 1 : 0, - // 90% active - Math.random() > 0.3 ? createdAtTimestamp : null, - createdAtTimestamp, - createdAtTimestamp - ).run(); - count++; - } - return count; - } - // Create 200 content items across different types - async createContent() { - const usersStmt = this.db.prepare("SELECT * FROM users"); - const { results: allUsers } = await usersStmt.all(); - const collectionsStmt = this.db.prepare("SELECT * FROM collections"); - const { results: allCollections } = await collectionsStmt.all(); - if (!allUsers || allUsers.length === 0) { - throw new Error("No users found. Please create users first."); - } - if (!allCollections || allCollections.length === 0) { - throw new Error("No collections found. Please create collections first."); - } - const statuses = ["draft", "published", "archived"]; - let count = 0; - for (let i = 0; i < 200; i++) { - const collection = allCollections[Math.floor(Math.random() * allCollections.length)]; - const author = allUsers[Math.floor(Math.random() * allUsers.length)]; - const status = statuses[Math.floor(Math.random() * statuses.length)]; - let title; - let contentData; - if (collection.name === "blog_posts" || collection.name.includes("blog")) { - title = this.blogTitles[Math.floor(Math.random() * this.blogTitles.length)] || "Untitled Blog Post"; - contentData = { - body: this.blogContent[Math.floor(Math.random() * this.blogContent.length)] || "Blog content here", - excerpt: "A brief introduction to this article that provides an overview of the main topics covered.", - tags: this.generateTags(), - featured: Math.random() > 0.7 - }; - } else if (collection.name === "pages" || collection.name.includes("page")) { - title = this.pageTitles[Math.floor(Math.random() * this.pageTitles.length)] || "Untitled Page"; - contentData = { - body: "This is a standard page with important information about our services and policies.", - template: "default", - showInMenu: Math.random() > 0.5 - }; - } else if (collection.name === "products" || collection.name.includes("product")) { - title = this.productTitles[Math.floor(Math.random() * this.productTitles.length)] || "Untitled Product"; - contentData = { - description: "High-quality product with excellent features and great value for money.", - price: (Math.random() * 500 + 10).toFixed(2), - sku: `SKU-${Math.random().toString(36).substr(2, 9).toUpperCase()}`, - inStock: Math.random() > 0.2, - rating: (Math.random() * 2 + 3).toFixed(1) - // 3.0 - 5.0 - }; - } else { - title = `${collection.display_name || collection.name} Item ${i + 1}`; - contentData = { - description: "This is a sample content item with generic data.", - value: Math.floor(Math.random() * 1e3) - }; - } - const slug = `${this.generateSlug(title)}-${i}`; - const createdAt = this.randomDate(); - const createdAtTimestamp = Math.floor(createdAt.getTime() / 1e3); - const publishedAtTimestamp = status === "published" ? createdAtTimestamp : null; - const stmt = this.db.prepare(` - INSERT INTO content (id, collection_id, slug, title, data, status, published_at, author_id, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - await stmt.bind( - this.generateId(), - collection.id, - slug, - `${title} ${i}`, - JSON.stringify(contentData), - status, - publishedAtTimestamp, - author.id, - createdAtTimestamp, - createdAtTimestamp - ).run(); - count++; - } - return count; - } - // Generate random tags for blog posts - generateTags() { - const allTags = [ - "tutorial", - "guide", - "javascript", - "typescript", - "web-dev", - "backend", - "frontend", - "best-practices", - "security", - "performance", - "testing", - "deployment", - "cloud", - "database", - "api" - ]; - const numTags = Math.floor(Math.random() * 4) + 1; - const shuffled = allTags.sort(() => 0.5 - Math.random()); - return shuffled.slice(0, numTags); - } - // Seed all data - async seedAll() { - const userCount = await this.createUsers(); - const contentCount = await this.createContent(); - return { - users: userCount, - content: contentCount - }; - } - // Clear all seed data (optional cleanup method) - async clearSeedData() { - const deleteContentStmt = this.db.prepare("DELETE FROM content"); - await deleteContentStmt.run(); - const deleteUsersStmt = this.db.prepare( - "DELETE FROM users WHERE role != 'admin'" - ); - await deleteUsersStmt.run(); - } -}; - -// src/plugins/core-plugins/seed-data-plugin/admin-routes.ts -function createSeedDataAdminRoutes() { - const routes = new hono.Hono(); - routes.get("/", async (c) => { - const html = ` - - - - Seed Data - SonicJS Admin - - - - - -
- \u2190 Back to Plugin Settings -

\u{1F331} Seed Data Generator

-

- Generate realistic example data for testing and development. This will create 20 users and 200 content items with realistic data. -

- -
- \u26A0\uFE0F Warning: This will create new data in your database. Make sure you're not running this in production! -
- -
-
- -
-

What will be created?

-
    -
  • 20 Users: With realistic names, emails, and various roles (admin, editor, author, viewer)
  • -
  • 200 Content Items: Including blog posts, pages, and products with realistic titles and data
  • -
  • All passwords: Set to "password123" for testing
  • -
  • Random dates: Created within the last year
  • -
  • Various statuses: Draft, published, and archived content
  • -
-
- -
-

Generate Seed Data

-

Click the button below to generate example data. This may take a few moments.

- -
- -
-

Clear Seed Data

-

Remove all users and content from the database (except admin users).

- -
-
- - - - - `; - return c.html(html); - }); - routes.post("/generate", async (c) => { - try { - const db = c.env.DB; - const seedService = new SeedDataService(db); - const result = await seedService.seedAll(); - return c.json({ - success: true, - users: result.users, - content: result.content - }); - } catch (error) { - return c.json({ - success: false, - error: error.message - }, 500); - } - }); - routes.post("/clear", async (c) => { - try { - const db = c.env.DB; - const seedService = new SeedDataService(db); - await seedService.clearSeedData(); - return c.json({ - success: true - }); - } catch (error) { - return c.json({ - success: false, - error: error.message - }, 500); - } - }); - return routes; -} -function createEmailPlugin() { - const builder = chunk6FHNRRJ3_cjs.PluginBuilder.create({ - name: "email", - version: "1.0.0-beta.1", - description: "Send transactional emails using Resend" - }); - builder.metadata({ - author: { - name: "SonicJS Team", - email: "team@sonicjs.com" - }, - license: "MIT", - compatibility: "^2.0.0" - }); - const emailRoutes = new hono.Hono(); - emailRoutes.post("/settings", async (c) => { - try { - const body = await c.req.json(); - const db = c.env.DB; - await db.prepare(` - UPDATE plugins - SET settings = ?, - updated_at = unixepoch() - WHERE id = 'email' - `).bind(JSON.stringify(body)).run(); - return c.json({ success: true }); - } catch (error) { - console.error("Error saving email settings:", error); - return c.json({ success: false, error: "Failed to save settings" }, 500); - } - }); - emailRoutes.post("/test", async (c) => { - try { - const db = c.env.DB; - const body = await c.req.json(); - const plugin2 = await db.prepare(` - SELECT settings FROM plugins WHERE id = 'email' - `).first(); - if (!plugin2?.settings) { - return c.json({ - success: false, - error: "Email settings not configured. Please save your settings first." - }, 400); - } - const settings = JSON.parse(plugin2.settings); - if (!settings.apiKey || !settings.fromEmail || !settings.fromName) { - return c.json({ - success: false, - error: "Missing required settings. Please configure API Key, From Email, and From Name." - }, 400); - } - const toEmail = body.toEmail || settings.fromEmail; - if (!toEmail.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) { - return c.json({ - success: false, - error: "Invalid email address format" - }, 400); - } - const response = await fetch("https://api.resend.com/emails", { - method: "POST", - headers: { - "Authorization": `Bearer ${settings.apiKey}`, - "Content-Type": "application/json" - }, - body: JSON.stringify({ - from: `${settings.fromName} <${settings.fromEmail}>`, - to: [toEmail], - subject: "Test Email from SonicJS", - html: ` -
-

Test Email Successful! \u{1F389}

-

This is a test email from your SonicJS Email plugin.

-

Configuration:

-
    -
  • From: ${settings.fromName} <${settings.fromEmail}>
  • -
  • Reply-To: ${settings.replyTo || "Not set"}
  • -
  • Sent at: ${(/* @__PURE__ */ new Date()).toISOString()}
  • -
-

Your email settings are working correctly!

-
- `, - reply_to: settings.replyTo || settings.fromEmail - }) - }); - const data = await response.json(); - if (!response.ok) { - console.error("Resend API error:", data); - return c.json({ - success: false, - error: data.message || "Failed to send test email. Check your API key and domain verification." - }, response.status); - } - return c.json({ - success: true, - message: `Test email sent successfully to ${toEmail}`, - emailId: data.id - }); - } catch (error) { - console.error("Test email error:", error); - return c.json({ - success: false, - error: error.message || "An error occurred while sending test email" - }, 500); - } - }); - builder.addRoute("/admin/plugins/email", emailRoutes, { - description: "Email plugin settings", - requiresAuth: true, - priority: 80 - }); - builder.addMenuItem("Email", "/admin/plugins/email", { - icon: "envelope", - order: 80, - permissions: ["email:manage"] - }); - builder.lifecycle({ - activate: async () => { - console.info("\u2705 Email plugin activated"); - }, - deactivate: async () => { - console.info("\u274C Email plugin deactivated"); - } - }); - return builder.build(); -} -var emailPlugin = createEmailPlugin(); - -// src/plugins/core-plugins/otp-login-plugin/otp-service.ts -var OTPService = class { - constructor(db) { - this.db = db; - } - /** - * Generate a secure random OTP code - */ - generateCode(length = 6) { - const digits = "0123456789"; - let code = ""; - for (let i = 0; i < length; i++) { - const randomValues = new Uint8Array(1); - crypto.getRandomValues(randomValues); - const randomValue = randomValues[0] ?? 0; - code += digits[randomValue % digits.length]; - } - return code; - } - /** - * Create and store a new OTP code - */ - async createOTPCode(email, settings, ipAddress, userAgent) { - const code = this.generateCode(settings.codeLength); - const id = crypto.randomUUID(); - const now = Date.now(); - const expiresAt = now + settings.codeExpiryMinutes * 60 * 1e3; - const otpCode = { - id, - user_email: email.toLowerCase(), - code, - expires_at: expiresAt, - used: 0, - used_at: null, - ip_address: ipAddress || null, - user_agent: userAgent || null, - attempts: 0, - created_at: now - }; - await this.db.prepare(` - INSERT INTO otp_codes ( - id, user_email, code, expires_at, used, used_at, - ip_address, user_agent, attempts, created_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).bind( - otpCode.id, - otpCode.user_email, - otpCode.code, - otpCode.expires_at, - otpCode.used, - otpCode.used_at, - otpCode.ip_address, - otpCode.user_agent, - otpCode.attempts, - otpCode.created_at - ).run(); - return otpCode; - } - /** - * Verify an OTP code - */ - async verifyCode(email, code, settings) { - const normalizedEmail = email.toLowerCase(); - const now = Date.now(); - const otpCode = await this.db.prepare(` - SELECT * FROM otp_codes - WHERE user_email = ? AND code = ? AND used = 0 - ORDER BY created_at DESC - LIMIT 1 - `).bind(normalizedEmail, code).first(); - if (!otpCode) { - return { valid: false, error: "Invalid or expired code" }; - } - if (now > otpCode.expires_at) { - return { valid: false, error: "Code has expired" }; - } - if (otpCode.attempts >= settings.maxAttempts) { - return { valid: false, error: "Maximum attempts exceeded" }; - } - await this.db.prepare(` - UPDATE otp_codes - SET used = 1, used_at = ?, attempts = attempts + 1 - WHERE id = ? - `).bind(now, otpCode.id).run(); - return { valid: true }; - } - /** - * Increment failed attempt count - */ - async incrementAttempts(email, code) { - const normalizedEmail = email.toLowerCase(); - const result = await this.db.prepare(` - UPDATE otp_codes - SET attempts = attempts + 1 - WHERE user_email = ? AND code = ? AND used = 0 - RETURNING attempts - `).bind(normalizedEmail, code).first(); - return result?.attempts || 0; - } - /** - * Check rate limiting - */ - async checkRateLimit(email, settings) { - const normalizedEmail = email.toLowerCase(); - const oneHourAgo = Date.now() - 60 * 60 * 1e3; - const result = await this.db.prepare(` - SELECT COUNT(*) as count - FROM otp_codes - WHERE user_email = ? AND created_at > ? - `).bind(normalizedEmail, oneHourAgo).first(); - const count = result?.count || 0; - return count < settings.rateLimitPerHour; - } - /** - * Get recent OTP requests for activity log - */ - async getRecentRequests(limit = 50) { - const result = await this.db.prepare(` - SELECT * FROM otp_codes - ORDER BY created_at DESC - LIMIT ? - `).bind(limit).all(); - const rows = result.results || []; - return rows.map((row) => this.mapRowToOTP(row)); - } - /** - * Clean up expired codes (for maintenance) - */ - async cleanupExpiredCodes() { - const now = Date.now(); - const result = await this.db.prepare(` - DELETE FROM otp_codes - WHERE expires_at < ? OR (used = 1 AND used_at < ?) - `).bind(now, now - 30 * 24 * 60 * 60 * 1e3).run(); - return result.meta.changes || 0; - } - mapRowToOTP(row) { - return { - id: String(row.id), - user_email: String(row.user_email), - code: String(row.code), - expires_at: Number(row.expires_at ?? Date.now()), - used: Number(row.used ?? 0), - used_at: row.used_at === null || row.used_at === void 0 ? null : Number(row.used_at), - ip_address: typeof row.ip_address === "string" ? row.ip_address : null, - user_agent: typeof row.user_agent === "string" ? row.user_agent : null, - attempts: Number(row.attempts ?? 0), - created_at: Number(row.created_at ?? Date.now()) - }; - } - /** - * Get OTP statistics - */ - async getStats(days = 7) { - const since = Date.now() - days * 24 * 60 * 60 * 1e3; - const stats = await this.db.prepare(` - SELECT - COUNT(*) as total, - SUM(CASE WHEN used = 1 THEN 1 ELSE 0 END) as successful, - SUM(CASE WHEN attempts >= 3 AND used = 0 THEN 1 ELSE 0 END) as failed, - SUM(CASE WHEN expires_at < ? AND used = 0 THEN 1 ELSE 0 END) as expired - FROM otp_codes - WHERE created_at > ? - `).bind(Date.now(), since).first(); - return { - total: stats?.total || 0, - successful: stats?.successful || 0, - failed: stats?.failed || 0, - expired: stats?.expired || 0 - }; - } -}; - -// src/plugins/core-plugins/otp-login-plugin/email-templates.ts -function renderOTPEmailHTML(data) { - return ` - - - - - Your Login Code - - - -
- - ${data.logoUrl ? ` -
- Logo -
- ` : ""} - -
-

Your Login Code

-

Enter this code to sign in to ${data.appName}

-
- -
-
-
- ${data.code} -
-
- -
-

- \u26A0\uFE0F This code expires in ${data.expiryMinutes} minutes -

-
- -
-

Quick Tips:

-
    -
  • Enter the code exactly as shown (${data.codeLength} digits)
  • -
  • The code can only be used once
  • -
  • You have ${data.maxAttempts} attempts to enter the correct code
  • -
  • Request a new code if this one expires
  • -
-
- -
-

- \u{1F512} Security Notice -

-

- Never share this code with anyone. ${data.appName} will never ask you for this code via phone, email, or social media. -

-
-
- -
-

- Didn't request this code?
- Someone may have entered your email by mistake. You can safely ignore this email. -

- -
-

This email was sent to ${data.email}

- ${data.ipAddress ? `

IP Address: ${data.ipAddress}

` : ""} -

Time: ${data.timestamp}

-
-
- -
- -
-

© ${(/* @__PURE__ */ new Date()).getFullYear()} ${data.appName}. All rights reserved.

-
- - -`; -} -function renderOTPEmailText(data) { - return `Your Login Code for ${data.appName} - -Your one-time verification code is: - -${data.code} - -This code expires in ${data.expiryMinutes} minutes. - -Quick Tips: -\u2022 Enter the code exactly as shown (${data.codeLength} digits) -\u2022 The code can only be used once -\u2022 You have ${data.maxAttempts} attempts to enter the correct code -\u2022 Request a new code if this one expires - -Security Notice: -Never share this code with anyone. ${data.appName} will never ask you for this code via phone, email, or social media. - -Didn't request this code? -Someone may have entered your email by mistake. You can safely ignore this email. - ---- -This email was sent to ${data.email} -${data.ipAddress ? `IP Address: ${data.ipAddress}` : ""} -Time: ${data.timestamp} - -\xA9 ${(/* @__PURE__ */ new Date()).getFullYear()} ${data.appName}. All rights reserved.`; -} -function renderOTPEmail(data) { - return { - html: renderOTPEmailHTML(data), - text: renderOTPEmailText(data) - }; -} - -// src/plugins/core-plugins/otp-login-plugin/index.ts -var otpRequestSchema = zod.z.object({ - email: zod.z.string().email("Valid email is required") -}); -var otpVerifySchema = zod.z.object({ - email: zod.z.string().email("Valid email is required"), - code: zod.z.string().min(4).max(8) -}); -var DEFAULT_SETTINGS = { - codeLength: 6, - codeExpiryMinutes: 10, - maxAttempts: 3, - rateLimitPerHour: 5, - allowNewUserRegistration: false -}; -function createOTPLoginPlugin() { - const builder = chunk6FHNRRJ3_cjs.PluginBuilder.create({ - name: "otp-login", - version: "1.0.0-beta.1", - description: "Passwordless authentication via email one-time codes" - }); - builder.metadata({ - author: { - name: "SonicJS Team", - email: "team@sonicjs.com" - }, - license: "MIT", - compatibility: "^2.0.0" - }); - const otpAPI = new hono.Hono(); - otpAPI.post("/request", async (c) => { - try { - const body = await c.req.json(); - const validation = otpRequestSchema.safeParse(body); - if (!validation.success) { - return c.json({ - error: "Validation failed", - details: validation.error.issues - }, 400); - } - const { email } = validation.data; - const normalizedEmail = email.toLowerCase(); - const db = c.env.DB; - const otpService = new OTPService(db); - let settings = { ...DEFAULT_SETTINGS }; - const pluginRow = await db.prepare(` - SELECT settings FROM plugins WHERE id = 'otp-login' - `).first(); - if (pluginRow?.settings) { - try { - const savedSettings = JSON.parse(pluginRow.settings); - settings = { ...DEFAULT_SETTINGS, ...savedSettings }; - } catch (e) { - console.warn("Failed to parse OTP plugin settings, using defaults"); - } - } - const settingsService = new chunkVNLR35GO_cjs.SettingsService(db); - const generalSettings = await settingsService.getGeneralSettings(); - const siteName = generalSettings.siteName; - const canRequest = await otpService.checkRateLimit(normalizedEmail, settings); - if (!canRequest) { - return c.json({ - error: "Too many requests. Please try again in an hour." - }, 429); - } - const user = await db.prepare(` - SELECT id, email, role, is_active - FROM users - WHERE email = ? - `).bind(normalizedEmail).first(); - if (!user && !settings.allowNewUserRegistration) { - return c.json({ - message: "If an account exists for this email, you will receive a verification code shortly.", - expiresIn: settings.codeExpiryMinutes * 60 - }); - } - if (user && !user.is_active) { - return c.json({ - error: "This account has been deactivated." - }, 403); - } - const ipAddress = c.req.header("cf-connecting-ip") || c.req.header("x-forwarded-for") || "unknown"; - const userAgent = c.req.header("user-agent") || "unknown"; - const otpCode = await otpService.createOTPCode( - normalizedEmail, - settings, - ipAddress, - userAgent - ); - try { - const isDevMode = c.env.ENVIRONMENT === "development"; - if (isDevMode) { - console.log(`[DEV] OTP Code for ${normalizedEmail}: ${otpCode.code}`); - } - const emailContent = renderOTPEmail({ - code: otpCode.code, - expiryMinutes: settings.codeExpiryMinutes, - codeLength: settings.codeLength, - maxAttempts: settings.maxAttempts, - email: normalizedEmail, - ipAddress, - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - appName: siteName - }); - const emailPlugin2 = await db.prepare(` - SELECT settings FROM plugins WHERE id = 'email' - `).first(); - if (emailPlugin2?.settings) { - const emailSettings = JSON.parse(emailPlugin2.settings); - if (emailSettings.apiKey && emailSettings.fromEmail && emailSettings.fromName) { - const emailResponse = await fetch("https://api.resend.com/emails", { - method: "POST", - headers: { - "Authorization": `Bearer ${emailSettings.apiKey}`, - "Content-Type": "application/json" - }, - body: JSON.stringify({ - from: `${emailSettings.fromName} <${emailSettings.fromEmail}>`, - to: [normalizedEmail], - subject: `Your login code for ${siteName}`, - html: emailContent.html, - text: emailContent.text, - reply_to: emailSettings.replyTo || emailSettings.fromEmail - }) - }); - if (!emailResponse.ok) { - const errorData = await emailResponse.json(); - console.error("Failed to send OTP email via Resend:", errorData); - } - } else { - console.warn("Email plugin is not fully configured (missing apiKey, fromEmail, or fromName)"); - } - } else { - console.warn("Email plugin is not active or has no settings configured"); - } - const response = { - message: "If an account exists for this email, you will receive a verification code shortly.", - expiresIn: settings.codeExpiryMinutes * 60 - }; - if (isDevMode) { - response.dev_code = otpCode.code; - } - return c.json(response); - } catch (emailError) { - console.error("Error sending OTP email:", emailError); - return c.json({ - error: "Failed to send verification code. Please try again." - }, 500); - } - } catch (error) { - console.error("OTP request error:", error); - return c.json({ - error: "An error occurred. Please try again." - }, 500); - } - }); - otpAPI.post("/verify", async (c) => { - try { - const body = await c.req.json(); - const validation = otpVerifySchema.safeParse(body); - if (!validation.success) { - return c.json({ - error: "Validation failed", - details: validation.error.issues - }, 400); - } - const { email, code } = validation.data; - const normalizedEmail = email.toLowerCase(); - const db = c.env.DB; - const otpService = new OTPService(db); - let settings = { ...DEFAULT_SETTINGS }; - const pluginRow = await db.prepare(` - SELECT settings FROM plugins WHERE id = 'otp-login' - `).first(); - if (pluginRow?.settings) { - try { - const savedSettings = JSON.parse(pluginRow.settings); - settings = { ...DEFAULT_SETTINGS, ...savedSettings }; - } catch (e) { - console.warn("Failed to parse OTP plugin settings, using defaults"); - } - } - const verification = await otpService.verifyCode(normalizedEmail, code, settings); - if (!verification.valid) { - await otpService.incrementAttempts(normalizedEmail, code); - return c.json({ - error: verification.error || "Invalid code", - attemptsRemaining: verification.attemptsRemaining - }, 401); - } - const user = await db.prepare(` - SELECT id, email, role, is_active - FROM users - WHERE email = ? - `).bind(normalizedEmail).first(); - if (!user) { - return c.json({ - error: "User not found" - }, 404); - } - if (!user.is_active) { - return c.json({ - error: "Account is deactivated" - }, 403); - } - const token = await chunkDVQA5II3_cjs.AuthManager.generateToken(user.id, user.email, user.role); - cookie.setCookie(c, "auth_token", token, { - httpOnly: true, - secure: true, - sameSite: "Strict", - maxAge: 60 * 60 * 24 - // 24 hours - }); - return c.json({ - success: true, - user: { - id: user.id, - email: user.email, - role: user.role - }, - token, - message: "Authentication successful" - }); - } catch (error) { - console.error("OTP verify error:", error); - return c.json({ - error: "An error occurred. Please try again." - }, 500); - } - }); - otpAPI.post("/resend", async (c) => { - try { - const body = await c.req.json(); - const validation = otpRequestSchema.safeParse(body); - if (!validation.success) { - return c.json({ - error: "Validation failed", - details: validation.error.issues - }, 400); - } - return otpAPI.fetch( - new Request(c.req.url.replace("/resend", "/request"), { - method: "POST", - headers: c.req.raw.headers, - body: JSON.stringify({ email: validation.data.email }) - }), - c.env - ); - } catch (error) { - console.error("OTP resend error:", error); - return c.json({ - error: "An error occurred. Please try again." - }, 500); - } - }); - builder.addRoute("/auth/otp", otpAPI, { - description: "OTP authentication endpoints", - requiresAuth: false, - priority: 100 - }); - builder.addMenuItem("OTP Login", "/admin/plugins/otp-login", { - icon: "key", - order: 85, - permissions: ["otp:manage"] - }); - builder.lifecycle({ - activate: async () => { - console.info("\u2705 OTP Login plugin activated"); - }, - deactivate: async () => { - console.info("\u274C OTP Login plugin deactivated"); - } - }); - return builder.build(); -} -var otpLoginPlugin = createOTPLoginPlugin(); - -// src/plugins/core-plugins/ai-search-plugin/services/embedding.service.ts -var EmbeddingService = class { - constructor(ai) { - this.ai = ai; - } - /** - * Generate embedding for a single text - */ - async generateEmbedding(text) { - try { - const response = await this.ai.run("@cf/baai/bge-base-en-v1.5", { - text: this.preprocessText(text) - }); - if (response.data && response.data.length > 0) { - return response.data[0]; - } - throw new Error("No embedding data returned"); - } catch (error) { - console.error("[EmbeddingService] Error generating embedding:", error); - throw error; - } - } - /** - * Generate embeddings for multiple texts (batch processing) - */ - async generateBatch(texts) { - try { - const batchSize = 10; - const batches = []; - for (let i = 0; i < texts.length; i += batchSize) { - batches.push(texts.slice(i, i + batchSize)); - } - const allEmbeddings = []; - for (const batch of batches) { - const batchEmbeddings = await Promise.all( - batch.map((text) => this.generateEmbedding(text)) - ); - allEmbeddings.push(...batchEmbeddings); - } - return allEmbeddings; - } catch (error) { - console.error("[EmbeddingService] Error generating batch embeddings:", error); - throw error; - } - } - /** - * Preprocess text before generating embedding - * - Trim whitespace - * - Limit length to avoid token limits - * - Remove special characters that might cause issues - */ - preprocessText(text) { - if (!text) return ""; - let processed = text.trim().replace(/\s+/g, " "); - if (processed.length > 8e3) { - processed = processed.substring(0, 8e3); - } - return processed; - } - /** - * Calculate cosine similarity between two embeddings - */ - cosineSimilarity(a, b) { - if (a.length !== b.length) { - throw new Error("Embeddings must have same dimensions"); - } - let dotProduct = 0; - let normA = 0; - let normB = 0; - for (let i = 0; i < a.length; i++) { - const aVal = a[i] ?? 0; - const bVal = b[i] ?? 0; - dotProduct += aVal * bVal; - normA += aVal * aVal; - normB += bVal * bVal; - } - return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB)); - } -}; - -// src/plugins/core-plugins/ai-search-plugin/services/chunking.service.ts -var ChunkingService = class { - // Default chunk size (in approximate tokens) - CHUNK_SIZE = 500; - CHUNK_OVERLAP = 50; - /** - * Chunk a single content item - */ - chunkContent(contentId, collectionId, title, data, metadata = {}) { - const text = this.extractText(data); - if (!text || text.trim().length === 0) { - console.warn(`[ChunkingService] No text found for content ${contentId}`); - return []; - } - const textChunks = this.splitIntoChunks(text); - return textChunks.map((chunkText, index) => ({ - id: `${contentId}_chunk_${index}`, - content_id: contentId, - collection_id: collectionId, - title, - text: chunkText, - chunk_index: index, - metadata: { - ...metadata, - total_chunks: textChunks.length - } - })); - } - /** - * Chunk multiple content items - */ - chunkContentBatch(items) { - const allChunks = []; - for (const item of items) { - const chunks = this.chunkContent( - item.id, - item.collection_id, - item.title, - item.data, - item.metadata - ); - allChunks.push(...chunks); - } - return allChunks; - } - /** - * Extract all text from content data - */ - extractText(data) { - const parts = []; - if (data.title) parts.push(String(data.title)); - if (data.name) parts.push(String(data.name)); - if (data.description) parts.push(String(data.description)); - if (data.content) parts.push(String(data.content)); - if (data.body) parts.push(String(data.body)); - if (data.text) parts.push(String(data.text)); - if (data.summary) parts.push(String(data.summary)); - const extractRecursive = (obj) => { - if (typeof obj === "string") { - if (obj.length > 10 && !obj.startsWith("http")) { - parts.push(obj); - } - } else if (Array.isArray(obj)) { - obj.forEach(extractRecursive); - } else if (obj && typeof obj === "object") { - const skipKeys = ["id", "slug", "url", "image", "thumbnail", "metadata"]; - Object.entries(obj).forEach(([key, value]) => { - if (!skipKeys.includes(key.toLowerCase())) { - extractRecursive(value); - } - }); - } - }; - extractRecursive(data); - return parts.join("\n\n").trim(); - } - /** - * Split text into overlapping chunks - */ - splitIntoChunks(text) { - const words = text.split(/\s+/); - if (words.length <= this.CHUNK_SIZE) { - return [text]; - } - const chunks = []; - let startIndex = 0; - while (startIndex < words.length) { - const endIndex = Math.min(startIndex + this.CHUNK_SIZE, words.length); - const chunk = words.slice(startIndex, endIndex).join(" "); - chunks.push(chunk); - startIndex += this.CHUNK_SIZE - this.CHUNK_OVERLAP; - if (startIndex >= words.length - this.CHUNK_OVERLAP) { - break; - } - } - return chunks; - } - /** - * Get optimal chunk size based on content type - */ - getOptimalChunkSize(contentType) { - switch (contentType) { - case "blog_posts": - case "articles": - return 600; - // Larger chunks for long-form content - case "products": - case "pages": - return 400; - // Medium chunks for structured content - case "messages": - case "comments": - return 200; - // Small chunks for short content - default: - return this.CHUNK_SIZE; - } - } -}; - -// src/plugins/core-plugins/ai-search-plugin/services/custom-rag.service.ts -var CustomRAGService = class { - constructor(db, ai, vectorize) { - this.db = db; - this.ai = ai; - this.vectorize = vectorize; - this.embeddingService = new EmbeddingService(ai); - this.chunkingService = new ChunkingService(); - } - embeddingService; - chunkingService; - /** - * Index all content from a collection - */ - async indexCollection(collectionId) { - console.log(`[CustomRAG] Starting indexing for collection: ${collectionId}`); - try { - const { results: contentItems } = await this.db.prepare(` - SELECT c.id, c.title, c.data, c.collection_id, c.status, - c.created_at, c.updated_at, c.author_id, - col.name as collection_name, col.display_name as collection_display_name - FROM content c - JOIN collections col ON c.collection_id = col.id - WHERE c.collection_id = ? AND c.status = 'published' - `).bind(collectionId).all(); - const totalItems = contentItems?.length || 0; - if (totalItems === 0) { - console.log(`[CustomRAG] No content found in collection ${collectionId}`); - return { total_items: 0, total_chunks: 0, indexed_chunks: 0, errors: 0 }; - } - const items = (contentItems || []).map((item) => ({ - id: item.id, - collection_id: item.collection_id, - title: item.title || "Untitled", - data: typeof item.data === "string" ? JSON.parse(item.data) : item.data, - metadata: { - status: item.status, - created_at: item.created_at, - updated_at: item.updated_at, - author_id: item.author_id, - collection_name: item.collection_name, - collection_display_name: item.collection_display_name - } - })); - const chunks = this.chunkingService.chunkContentBatch(items); - const totalChunks = chunks.length; - console.log(`[CustomRAG] Generated ${totalChunks} chunks from ${totalItems} items`); - const embeddings = await this.embeddingService.generateBatch( - chunks.map((c) => `${c.title} - -${c.text}`) - ); - console.log(`[CustomRAG] Generated ${embeddings.length} embeddings`); - let indexedChunks = 0; - let errors = 0; - const batchSize = 100; - for (let i = 0; i < chunks.length; i += batchSize) { - const chunkBatch = chunks.slice(i, i + batchSize); - const embeddingBatch = embeddings.slice(i, i + batchSize); - try { - await this.vectorize.upsert( - chunkBatch.map((chunk, idx) => ({ - id: chunk.id, - values: embeddingBatch[idx], - metadata: { - content_id: chunk.content_id, - collection_id: chunk.collection_id, - title: chunk.title, - text: chunk.text.substring(0, 500), - // Store snippet for display - chunk_index: chunk.chunk_index, - ...chunk.metadata - } - })) - ); - indexedChunks += chunkBatch.length; - console.log(`[CustomRAG] Indexed batch ${i / batchSize + 1}: ${chunkBatch.length} chunks`); - } catch (error) { - console.error(`[CustomRAG] Error indexing batch ${i / batchSize + 1}:`, error); - errors += chunkBatch.length; - } - } - console.log(`[CustomRAG] Indexing complete: ${indexedChunks}/${totalChunks} chunks indexed`); - return { - total_items: totalItems, - total_chunks: totalChunks, - indexed_chunks: indexedChunks, - errors - }; - } catch (error) { - console.error(`[CustomRAG] Error indexing collection ${collectionId}:`, error); - throw error; - } - } - /** - * Search using RAG (semantic search with Vectorize) - */ - async search(query, settings) { - const startTime = Date.now(); - try { - console.log(`[CustomRAG] Searching for: "${query.query}"`); - const queryEmbedding = await this.embeddingService.generateEmbedding(query.query); - const filter = {}; - if (query.filters?.collections && query.filters.collections.length > 0) { - filter.collection_id = { $in: query.filters.collections }; - } else if (settings.selected_collections.length > 0) { - filter.collection_id = { $in: settings.selected_collections }; - } - if (query.filters?.status && query.filters.status.length > 0) { - filter.status = { $in: query.filters.status }; - } - const vectorResults = await this.vectorize.query(queryEmbedding, { - topK: 50, - // Max allowed with returnMetadata: true - returnMetadata: true - }); - let filteredMatches = vectorResults.matches || []; - if (filter.collection_id?.$in && Array.isArray(filter.collection_id.$in)) { - const allowedCollections = filter.collection_id.$in; - filteredMatches = filteredMatches.filter( - (match) => allowedCollections.includes(match.metadata?.collection_id) - ); - } - if (filter.status?.$in && Array.isArray(filter.status.$in)) { - const allowedStatuses = filter.status.$in; - filteredMatches = filteredMatches.filter( - (match) => allowedStatuses.includes(match.metadata?.status) - ); - } - const topK = query.limit || settings.results_limit || 20; - filteredMatches = filteredMatches.slice(0, topK); - vectorResults.matches = filteredMatches; - if (!vectorResults.matches || vectorResults.matches.length === 0) { - return { - results: [], - total: 0, - query_time_ms: Date.now() - startTime, - mode: "ai" - }; - } - const contentIds = [...new Set( - vectorResults.matches.map((m) => m.metadata.content_id) - )]; - const placeholders = contentIds.map(() => "?").join(","); - const { results: contentItems } = await this.db.prepare(` - SELECT c.id, c.title, c.slug, c.collection_id, c.status, - c.created_at, c.updated_at, c.author_id, - col.display_name as collection_name - FROM content c - JOIN collections col ON c.collection_id = col.id - WHERE c.id IN (${placeholders}) - `).bind(...contentIds).all(); - const searchResults = (contentItems || []).map((item) => { - const matchingChunks = vectorResults.matches.filter( - (m) => m.metadata.content_id === item.id - ); - const bestMatch = matchingChunks.reduce( - (best, current) => current.score > (best?.score || 0) ? current : best, - null - ); - return { - id: item.id, - title: item.title || "Untitled", - slug: item.slug || "", - collection_id: item.collection_id, - collection_name: item.collection_name, - snippet: bestMatch?.metadata?.text || "", - relevance_score: bestMatch?.score || 0, - status: item.status, - created_at: item.created_at, - updated_at: item.updated_at - }; - }); - searchResults.sort((a, b) => (b.relevance_score || 0) - (a.relevance_score || 0)); - const queryTime = Date.now() - startTime; - console.log(`[CustomRAG] Search completed in ${queryTime}ms, ${searchResults.length} results`); - return { - results: searchResults, - total: searchResults.length, - query_time_ms: queryTime, - mode: "ai" - }; - } catch (error) { - console.error("[CustomRAG] Search error:", error); - throw error; - } - } - /** - * Update index for a single content item - */ - async updateContentIndex(contentId) { - try { - const content2 = await this.db.prepare(` - SELECT c.id, c.title, c.data, c.collection_id, c.status, - c.created_at, c.updated_at, c.author_id, - col.name as collection_name, col.display_name as collection_display_name - FROM content c - JOIN collections col ON c.collection_id = col.id - WHERE c.id = ? - `).bind(contentId).first(); - if (!content2) { - console.warn(`[CustomRAG] Content ${contentId} not found`); - return; - } - if (content2.status !== "published") { - await this.removeContentFromIndex(contentId); - return; - } - const chunks = this.chunkingService.chunkContent( - content2.id, - content2.collection_id, - content2.title || "Untitled", - typeof content2.data === "string" ? JSON.parse(content2.data) : content2.data, - { - status: content2.status, - created_at: content2.created_at, - updated_at: content2.updated_at, - author_id: content2.author_id, - collection_name: content2.collection_name, - collection_display_name: content2.collection_display_name - } - ); - const embeddings = await this.embeddingService.generateBatch( - chunks.map((c) => `${c.title} - -${c.text}`) - ); - await this.vectorize.upsert( - chunks.map((chunk, idx) => ({ - id: chunk.id, - values: embeddings[idx], - metadata: { - content_id: chunk.content_id, - collection_id: chunk.collection_id, - title: chunk.title, - text: chunk.text.substring(0, 500), - chunk_index: chunk.chunk_index, - ...chunk.metadata - } - })) - ); - console.log(`[CustomRAG] Updated index for content ${contentId}: ${chunks.length} chunks`); - } catch (error) { - console.error(`[CustomRAG] Error updating index for ${contentId}:`, error); - throw error; - } - } - /** - * Remove content from index - */ - async removeContentFromIndex(contentId) { - try { - console.log(`[CustomRAG] Removing content ${contentId} from index`); - } catch (error) { - console.error(`[CustomRAG] Error removing content ${contentId}:`, error); - throw error; - } - } - /** - * Get search suggestions based on query - */ - async getSuggestions(partialQuery, limit = 5) { - try { - const queryEmbedding = await this.embeddingService.generateEmbedding(partialQuery); - const results = await this.vectorize.query(queryEmbedding, { - topK: limit * 2, - // Get more to filter - returnMetadata: true - }); - const suggestions = [...new Set( - results.matches?.map((m) => m.metadata.title).filter(Boolean) || [] - )].slice(0, limit); - return suggestions; - } catch (error) { - console.error("[CustomRAG] Error getting suggestions:", error); - return []; - } - } - /** - * Check if Vectorize is available and configured - */ - isAvailable() { - return !!this.vectorize && !!this.ai; - } -}; - -// src/plugins/core-plugins/ai-search-plugin/services/ai-search.ts -var AISearchService = class { - constructor(db, ai, vectorize) { - this.db = db; - this.ai = ai; - this.vectorize = vectorize; - if (this.ai && this.vectorize) { - this.customRAG = new CustomRAGService(db, ai, vectorize); - console.log("[AISearchService] Custom RAG initialized"); - } else { - console.log("[AISearchService] Custom RAG not available, using keyword search only"); - } - } - customRAG; - /** - * Get plugin settings - */ - async getSettings() { - try { - const plugin2 = await this.db.prepare(`SELECT settings FROM plugins WHERE id = ? LIMIT 1`).bind("ai-search").first(); - if (!plugin2 || !plugin2.settings) { - return this.getDefaultSettings(); - } - return JSON.parse(plugin2.settings); - } catch (error) { - console.error("Error fetching AI Search settings:", error); - return this.getDefaultSettings(); - } - } - /** - * Get default settings - */ - getDefaultSettings() { - return { - enabled: true, - ai_mode_enabled: true, - selected_collections: [], - dismissed_collections: [], - autocomplete_enabled: true, - cache_duration: 1, - results_limit: 20, - index_media: false - }; - } - /** - * Update plugin settings - */ - async updateSettings(settings) { - const existing = await this.getSettings(); - const updated = { - ...existing, - ...settings - }; - try { - await this.db.prepare(` - UPDATE plugins - SET settings = ?, - updated_at = unixepoch() - WHERE id = 'ai-search' - `).bind(JSON.stringify(updated)).run(); - return updated; - } catch (error) { - console.error("Error updating AI Search settings:", error); - throw error; - } - } - /** - * Detect new collections that aren't indexed or dismissed - */ - async detectNewCollections() { - try { - const collectionsStmt = this.db.prepare( - "SELECT id, name, display_name, description FROM collections WHERE is_active = 1" - ); - const { results: allCollections } = await collectionsStmt.all(); - const collections2 = (allCollections || []).filter( - (col) => { - if (!col.name) return false; - const name = col.name.toLowerCase(); - return !name.startsWith("test_") && !name.endsWith("_test") && name !== "test_collection" && !name.includes("_test_") && name !== "large_payload_test" && name !== "concurrent_test"; - } - ); - const settings = await this.getSettings(); - const selected = settings?.selected_collections || []; - const dismissed = settings?.dismissed_collections || []; - const notifications = []; - for (const collection of collections2 || []) { - const collectionId = String(collection.id); - if (selected.includes(collectionId) || dismissed.includes(collectionId)) { - continue; - } - const countStmt = this.db.prepare( - "SELECT COUNT(*) as count FROM content WHERE collection_id = ?" - ); - const countResult = await countStmt.bind(collectionId).first(); - const itemCount = countResult?.count || 0; - notifications.push({ - collection: { - id: collectionId, - name: collection.name, - display_name: collection.display_name, - description: collection.description, - item_count: itemCount, - is_indexed: false, - is_dismissed: false, - is_new: true - }, - message: `New collection "${collection.display_name}" with ${itemCount} items available for indexing` - }); - } - return notifications; - } catch (error) { - console.error("Error detecting new collections:", error); - return []; - } - } - /** - * Get all collections with indexing status - */ - async getAllCollections() { - try { - const collectionsStmt = this.db.prepare( - "SELECT id, name, display_name, description FROM collections WHERE is_active = 1 ORDER BY display_name" - ); - const { results: allCollections } = await collectionsStmt.all(); - console.log("[AISearchService.getAllCollections] Raw collections from DB:", allCollections?.length || 0); - const firstCollection = allCollections?.[0]; - if (firstCollection) { - console.log("[AISearchService.getAllCollections] Sample collection:", { - id: firstCollection.id, - name: firstCollection.name, - display_name: firstCollection.display_name - }); - } - const collections2 = (allCollections || []).filter( - (col) => col.id && col.name - ); - console.log("[AISearchService.getAllCollections] After filtering test collections:", collections2.length); - console.log("[AISearchService.getAllCollections] Remaining collections:", collections2.map((c) => c.name).join(", ")); - const settings = await this.getSettings(); - const selected = settings?.selected_collections || []; - const dismissed = settings?.dismissed_collections || []; - console.log("[AISearchService.getAllCollections] Settings:", { - selected_count: selected.length, - dismissed_count: dismissed.length, - selected - }); - const collectionInfos = []; - for (const collection of collections2) { - if (!collection.id || !collection.name) continue; - const collectionId = String(collection.id); - if (!collectionId) { - console.warn("[AISearchService] Skipping invalid collection:", collection); - continue; - } - const countStmt = this.db.prepare( - "SELECT COUNT(*) as count FROM content WHERE collection_id = ?" - ); - const countResult = await countStmt.bind(collectionId).first(); - const itemCount = countResult?.count || 0; - collectionInfos.push({ - id: collectionId, - name: collection.name, - display_name: collection.display_name || collection.name, - description: collection.description, - item_count: itemCount, - is_indexed: selected.includes(collectionId), - is_dismissed: dismissed.includes(collectionId), - is_new: !selected.includes(collectionId) && !dismissed.includes(collectionId) - }); - } - console.log("[AISearchService.getAllCollections] Returning collectionInfos:", collectionInfos.length); - const firstInfo = collectionInfos[0]; - if (collectionInfos.length > 0 && firstInfo) { - console.log("[AISearchService.getAllCollections] First collectionInfo:", { - id: firstInfo.id, - name: firstInfo.name, - display_name: firstInfo.display_name, - item_count: firstInfo.item_count - }); - } - return collectionInfos; - } catch (error) { - console.error("[AISearchService] Error fetching collections:", error); - return []; - } - } - /** - * Execute search query - */ - async search(query) { - const settings = await this.getSettings(); - if (!settings?.enabled) { - return { - results: [], - total: 0, - query_time_ms: 0, - mode: query.mode - }; - } - if (query.mode === "ai" && settings.ai_mode_enabled && this.customRAG?.isAvailable()) { - return this.searchAI(query, settings); - } - return this.searchKeyword(query, settings); - } - /** - * AI-powered semantic search using Custom RAG - */ - async searchAI(query, settings) { - try { - if (!this.customRAG) { - console.warn("[AISearchService] CustomRAG not available, falling back to keyword search"); - return this.searchKeyword(query, settings); - } - const result = await this.customRAG.search(query, settings); - return result; - } catch (error) { - console.error("[AISearchService] AI search error, falling back to keyword:", error); - return this.searchKeyword(query, settings); - } - } - /** - * Traditional keyword search - */ - async searchKeyword(query, settings) { - const startTime = Date.now(); - try { - const conditions = []; - const params = []; - if (query.query) { - conditions.push("(c.title LIKE ? OR c.slug LIKE ? OR c.data LIKE ?)"); - const searchTerm = `%${query.query}%`; - params.push(searchTerm, searchTerm, searchTerm); - } - if (query.filters?.collections && query.filters.collections.length > 0) { - const placeholders = query.filters.collections.map(() => "?").join(","); - conditions.push(`c.collection_id IN (${placeholders})`); - params.push(...query.filters.collections); - } else if (settings.selected_collections.length > 0) { - const placeholders = settings.selected_collections.map(() => "?").join(","); - conditions.push(`c.collection_id IN (${placeholders})`); - params.push(...settings.selected_collections); - } - if (query.filters?.status && query.filters.status.length > 0) { - const placeholders = query.filters.status.map(() => "?").join(","); - conditions.push(`c.status IN (${placeholders})`); - params.push(...query.filters.status); - } else { - conditions.push("c.status != 'deleted'"); - } - if (query.filters?.dateRange) { - const field = query.filters.dateRange.field || "created_at"; - if (query.filters.dateRange.start) { - conditions.push(`c.${field} >= ?`); - params.push(query.filters.dateRange.start.getTime()); - } - if (query.filters.dateRange.end) { - conditions.push(`c.${field} <= ?`); - params.push(query.filters.dateRange.end.getTime()); - } - } - if (query.filters?.author) { - conditions.push("c.author_id = ?"); - params.push(query.filters.author); - } - const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : ""; - const countStmt = this.db.prepare(` - SELECT COUNT(*) as count - FROM content c - ${whereClause} - `); - const countResult = await countStmt.bind(...params).first(); - const total = countResult?.count || 0; - const limit = query.limit || settings.results_limit; - const offset = query.offset || 0; - const resultsStmt = this.db.prepare(` - SELECT - c.id, c.title, c.slug, c.collection_id, c.status, - c.created_at, c.updated_at, c.author_id, c.data, - col.name as collection_name, col.display_name as collection_display_name, - u.email as author_email - FROM content c - JOIN collections col ON c.collection_id = col.id - LEFT JOIN users u ON c.author_id = u.id - ${whereClause} - ORDER BY c.updated_at DESC - LIMIT ? OFFSET ? - `); - const { results } = await resultsStmt.bind(...params, limit, offset).all(); - const searchResults = (results || []).map((row) => ({ - id: String(row.id), - title: row.title || "Untitled", - slug: row.slug || "", - collection_id: String(row.collection_id), - collection_name: row.collection_display_name || row.collection_name, - snippet: this.extractSnippet(row.data, query.query), - status: row.status, - created_at: Number(row.created_at), - updated_at: Number(row.updated_at), - author_name: row.author_email - })); - const queryTime = Date.now() - startTime; - await this.logSearch(query.query, query.mode, searchResults.length); - return { - results: searchResults, - total, - query_time_ms: queryTime, - mode: query.mode - }; - } catch (error) { - console.error("Keyword search error:", error); - return { - results: [], - total: 0, - query_time_ms: Date.now() - startTime, - mode: query.mode - }; - } - } - /** - * Extract snippet from content data - */ - extractSnippet(data, query) { - try { - const parsed = typeof data === "string" ? JSON.parse(data) : data; - const text = JSON.stringify(parsed).toLowerCase(); - const queryLower = query.toLowerCase(); - const index = text.indexOf(queryLower); - if (index === -1) { - return JSON.stringify(parsed).substring(0, 200) + "..."; - } - const start = Math.max(0, index - 50); - const end = Math.min(text.length, index + query.length + 50); - return text.substring(start, end) + "..."; - } catch { - return data.substring(0, 200) + "..."; - } - } - /** - * Get search suggestions (autocomplete) - */ - async getSearchSuggestions(partial) { - try { - const settings = await this.getSettings(); - if (!settings?.autocomplete_enabled) { - return []; - } - if (this.customRAG?.isAvailable()) { - try { - const aiSuggestions = await this.customRAG.getSuggestions(partial, 5); - if (aiSuggestions.length > 0) { - return aiSuggestions; - } - } catch (error) { - console.error("[AISearchService] Error getting AI suggestions:", error); - } - } - const stmt = this.db.prepare(` - SELECT DISTINCT query - FROM ai_search_history - WHERE query LIKE ? - ORDER BY created_at DESC - LIMIT 10 - `); - const { results } = await stmt.bind(`%${partial}%`).all(); - return (results || []).map((r) => r.query); - } catch (error) { - console.error("Error getting suggestions:", error); - return []; - } - } - /** - * Log search query to history - */ - async logSearch(query, mode, resultsCount) { - try { - const stmt = this.db.prepare(` - INSERT INTO ai_search_history (query, mode, results_count, created_at) - VALUES (?, ?, ?, ?) - `); - await stmt.bind(query, mode, resultsCount, Date.now()).run(); - } catch (error) { - console.error("Error logging search:", error); - } - } - /** - * Get search analytics - */ - async getSearchAnalytics() { - try { - const totalStmt = this.db.prepare(` - SELECT COUNT(*) as count - FROM ai_search_history - WHERE created_at >= ? - `); - const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1e3; - const totalResult = await totalStmt.bind(thirtyDaysAgo).first(); - const modeStmt = this.db.prepare(` - SELECT mode, COUNT(*) as count - FROM ai_search_history - WHERE created_at >= ? - GROUP BY mode - `); - const { results: modeResults } = await modeStmt.bind(thirtyDaysAgo).all(); - const aiCount = modeResults?.find((r) => r.mode === "ai")?.count || 0; - const keywordCount = modeResults?.find((r) => r.mode === "keyword")?.count || 0; - const popularStmt = this.db.prepare(` - SELECT query, COUNT(*) as count - FROM ai_search_history - WHERE created_at >= ? - GROUP BY query - ORDER BY count DESC - LIMIT 10 - `); - const { results: popularResults } = await popularStmt.bind(thirtyDaysAgo).all(); - return { - total_queries: totalResult?.count || 0, - ai_queries: aiCount, - keyword_queries: keywordCount, - popular_queries: (popularResults || []).map((r) => ({ - query: r.query, - count: r.count - })), - average_query_time: 0 - // TODO: Track query times - }; - } catch (error) { - console.error("Error getting analytics:", error); - return { - total_queries: 0, - ai_queries: 0, - keyword_queries: 0, - popular_queries: [], - average_query_time: 0 - }; - } - } - /** - * Verify Custom RAG is available - */ - verifyBinding() { - return this.customRAG?.isAvailable() ?? false; - } - /** - * Get Custom RAG service instance (for indexer) - */ - getCustomRAG() { - return this.customRAG; - } -}; - -// src/plugins/core-plugins/ai-search-plugin/services/indexer.ts -var IndexManager = class { - constructor(db, ai, vectorize) { - this.db = db; - this.ai = ai; - this.vectorize = vectorize; - if (this.ai && this.vectorize) { - this.customRAG = new CustomRAGService(db, ai, vectorize); - console.log("[IndexManager] Custom RAG initialized"); - } - } - customRAG; - /** - * Index all content items within a collection using Custom RAG - */ - async indexCollection(collectionId) { - try { - const collectionStmt = this.db.prepare( - "SELECT id, name, display_name FROM collections WHERE id = ?" - ); - const collection = await collectionStmt.bind(collectionId).first(); - if (!collection) { - throw new Error(`Collection ${collectionId} not found`); - } - await this.updateIndexStatus(collectionId, { - collection_id: collectionId, - collection_name: collection.display_name, - total_items: 0, - indexed_items: 0, - status: "indexing" - }); - if (this.customRAG?.isAvailable()) { - console.log(`[IndexManager] Using Custom RAG to index collection ${collectionId}`); - const result = await this.customRAG.indexCollection(collectionId); - const finalStatus = { - collection_id: collectionId, - collection_name: collection.display_name, - total_items: result.total_items, - indexed_items: result.indexed_chunks, - last_sync_at: Date.now(), - status: result.errors > 0 ? "error" : "completed", - error_message: result.errors > 0 ? `${result.errors} errors during indexing` : void 0 - }; - await this.updateIndexStatus(collectionId, finalStatus); - return finalStatus; - } - console.warn(`[IndexManager] Custom RAG not available, skipping indexing for ${collectionId}`); - const fallbackStatus = { - collection_id: collectionId, - collection_name: collection.display_name, - total_items: 0, - indexed_items: 0, - last_sync_at: Date.now(), - status: "completed", - error_message: "Custom RAG not available - using keyword search only" - }; - await this.updateIndexStatus(collectionId, fallbackStatus); - return fallbackStatus; - } catch (error) { - console.error(`[IndexManager] Error indexing collection ${collectionId}:`, error); - const errorStatus = { - collection_id: collectionId, - collection_name: "Unknown", - total_items: 0, - indexed_items: 0, - status: "error", - error_message: error instanceof Error ? error.message : String(error) - }; - await this.updateIndexStatus(collectionId, errorStatus); - return errorStatus; - } - } - /** - * Index a single content item - */ - async indexContentItem(item, collectionId) { - try { - let parsedData = {}; - try { - parsedData = typeof item.data === "string" ? JSON.parse(item.data) : item.data; - } catch { - parsedData = {}; - } - const document = { - id: `content_${item.id}`, - title: item.title || "Untitled", - slug: item.slug || "", - content: this.extractSearchableText(parsedData), - metadata: { - collection_id: collectionId, - collection_name: item.collection_name, - collection_display_name: item.collection_display_name, - status: item.status, - created_at: item.created_at, - updated_at: item.updated_at, - author_id: item.author_id - } - }; - console.log(`Indexed content item: ${item.id}`); - } catch (error) { - console.error(`Error indexing content item ${item.id}:`, error); - throw error; - } - } - /** - * Extract searchable text from content data - */ - extractSearchableText(data) { - const parts = []; - if (data.title) parts.push(String(data.title)); - if (data.name) parts.push(String(data.name)); - if (data.description) parts.push(String(data.description)); - if (data.content) parts.push(String(data.content)); - if (data.body) parts.push(String(data.body)); - if (data.text) parts.push(String(data.text)); - const extractStrings = (obj) => { - if (typeof obj === "string") { - parts.push(obj); - } else if (Array.isArray(obj)) { - obj.forEach(extractStrings); - } else if (obj && typeof obj === "object") { - Object.values(obj).forEach(extractStrings); - } - }; - extractStrings(data); - return parts.join(" "); - } - /** - * Update a single content item in the index - */ - async updateIndex(collectionId, contentId) { - try { - const stmt = this.db.prepare(` - SELECT - c.id, c.title, c.slug, c.data, c.status, - c.created_at, c.updated_at, c.author_id, - col.name as collection_name, col.display_name as collection_display_name - FROM content c - JOIN collections col ON c.collection_id = col.id - WHERE c.id = ? AND c.collection_id = ? - `); - const item = await stmt.bind(contentId, collectionId).first(); - if (!item) { - throw new Error(`Content item ${contentId} not found`); - } - await this.indexContentItem(item, String(collectionId)); - const status = await this.getIndexStatus(String(collectionId)); - if (status) { - await this.updateIndexStatus(String(collectionId), { - ...status, - last_sync_at: Date.now() - }); - } - } catch (error) { - console.error(`Error updating index for content ${contentId}:`, error); - throw error; - } - } - /** - * Remove a content item from the index using Custom RAG - */ - async removeFromIndex(collectionId, contentId) { - try { - if (this.customRAG?.isAvailable()) { - console.log(`[IndexManager] Removing content ${contentId} from index`); - await this.customRAG.removeContentFromIndex(contentId); - } else { - console.warn(`[IndexManager] Custom RAG not available, skipping removal for ${contentId}`); - } - } catch (error) { - console.error(`[IndexManager] Error removing content ${contentId} from index:`, error); - throw error; - } - } - /** - * Get indexing status for a collection - */ - async getIndexStatus(collectionId) { - try { - const stmt = this.db.prepare( - "SELECT * FROM ai_search_index_meta WHERE collection_id = ?" - ); - const result = await stmt.bind(collectionId).first(); - if (!result) { - return null; - } - return { - collection_id: String(result.collection_id), - collection_name: result.collection_name, - total_items: result.total_items, - indexed_items: result.indexed_items, - last_sync_at: result.last_sync_at, - status: result.status, - error_message: result.error_message - }; - } catch (error) { - console.error(`Error getting index status for collection ${collectionId}:`, error); - return null; - } - } - /** - * Get indexing status for all collections - */ - async getAllIndexStatus() { - try { - const stmt = this.db.prepare("SELECT * FROM ai_search_index_meta"); - const { results } = await stmt.all(); - const statusMap = {}; - for (const row of results || []) { - const collectionId = String(row.collection_id); - statusMap[collectionId] = { - collection_id: collectionId, - collection_name: row.collection_name, - total_items: row.total_items, - indexed_items: row.indexed_items, - last_sync_at: row.last_sync_at, - status: row.status, - error_message: row.error_message - }; - } - return statusMap; - } catch (error) { - console.error("Error getting all index status:", error); - return {}; - } - } - /** - * Update index status in database - */ - async updateIndexStatus(collectionId, status) { - try { - const checkStmt = this.db.prepare( - "SELECT id FROM ai_search_index_meta WHERE collection_id = ?" - ); - const existing = await checkStmt.bind(collectionId).first(); - if (existing) { - const stmt = this.db.prepare(` - UPDATE ai_search_index_meta - SET collection_name = ?, - total_items = ?, - indexed_items = ?, - last_sync_at = ?, - status = ?, - error_message = ? - WHERE collection_id = ? - `); - await stmt.bind( - status.collection_name, - status.total_items, - status.indexed_items, - status.last_sync_at || null, - status.status, - status.error_message || null, - String(collectionId) - ).run(); - } else { - const stmt = this.db.prepare(` - INSERT INTO ai_search_index_meta ( - collection_id, collection_name, total_items, indexed_items, - last_sync_at, status, error_message - ) VALUES (?, ?, ?, ?, ?, ?, ?) - `); - await stmt.bind( - String(status.collection_id), - status.collection_name, - status.total_items, - status.indexed_items, - status.last_sync_at || null, - status.status, - status.error_message || null - ).run(); - } - } catch (error) { - console.error(`Error updating index status for collection ${collectionId}:`, error); - throw error; - } - } - /** - * Sync all selected collections - */ - async syncAll(selectedCollections) { - for (const collectionId of selectedCollections) { - try { - await this.indexCollection(collectionId); - } catch (error) { - console.error(`Error syncing collection ${collectionId}:`, error); - } - } - } -}; - -// src/plugins/core-plugins/ai-search-plugin/components/settings-page.ts -function renderSettingsPage(data) { - const settings = data.settings || { - enabled: false, - ai_mode_enabled: true, - selected_collections: [], - dismissed_collections: [], - autocomplete_enabled: true, - cache_duration: 1, - results_limit: 20, - index_media: false - }; - const selectedCollections = Array.isArray(settings.selected_collections) ? settings.selected_collections : []; - const dismissedCollections = Array.isArray(settings.dismissed_collections) ? settings.dismissed_collections : []; - const enabled = settings.enabled === true; - const aiModeEnabled = settings.ai_mode_enabled !== false; - const autocompleteEnabled = settings.autocomplete_enabled !== false; - const indexMedia = settings.index_media === true; - const selectedCollectionIds = new Set(selectedCollections.map((id) => String(id))); - const dismissedCollectionIds = new Set(dismissedCollections.map((id) => String(id))); - const collections2 = Array.isArray(data.collections) ? data.collections : []; - console.log("[SettingsPage Template] Collections received:", collections2.length); - if (collections2.length > 0) { - console.log("[SettingsPage Template] First collection:", collections2[0]); - } - const content2 = ` -
- -
-
-

\u{1F50D} AI Search Settings

-

- Configure advanced search with Cloudflare AI Search. Select collections to index and manage search preferences. -

-
- -
- - - -
-
- -
-

\u{1F50D} Search Settings

-
-
- -
- -

Turn on advanced search capabilities across your content

-
-
- -
- -
- -

- Enable natural language queries (requires Cloudflare Workers AI binding) - \u2192 Setup Guide -

-

- \u26A0\uFE0F If AI binding unavailable, will fallback to keyword search -

-
-
-
-
- -
- - -
-
-
-

\u{1F4DA} Collections to Index

-

- Select which content collections should be indexed and searchable. Only checked collections will be included in search results. -

-
-
-
- ${collections2.length === 0 ? '

No collections available. Create collections first.

' : collections2.map((collection) => { - const collectionId = String(collection.id); - const isChecked = selectedCollectionIds.has(collectionId); - const isDismissed = dismissedCollectionIds.has(collectionId); - const indexStatusMap = data.indexStatus || {}; - const status = indexStatusMap[collectionId]; - const isNew = collection.is_new === true && !isDismissed && !status; - const statusBadge = status && isChecked ? `${status.status}` : ""; - return `
- -
- -

- ${collection.description || collection.name || "No description"} \u2022 ${collection.item_count || 0} items - ${status ? ` \u2022 ${status.indexed_items}/${status.total_items} indexed` : ""} -

- ${status && status.status === "indexing" ? `
-
-
` : ""} -
- ${isChecked ? ` - - ` : ""} -
`; - }).join("")} -
-
- -
- - -
-

\u2699\uFE0F Advanced Options

-
-
- -
- -

Show search suggestions as users type

-
-
- -
- -
- -

Include media files in search results

-
-
- -
- - -
-
- - -
-
-
- - -
-

- \u{1F4A1} Collections marked as NEW haven't been indexed yet -

- -
-
-
- - - -
-

\u{1F4CA} Search Analytics

-
-
-
Total Queries
-
${data.analytics.total_queries}
-
-
-
AI Queries
-
${data.analytics.ai_queries}
-
-
-
Keyword Queries
-
${data.analytics.keyword_queries}
-
-
- ${data.analytics.popular_queries.length > 0 ? ` -
-

Popular Searches

-
- ${data.analytics.popular_queries.map( - (item) => ` -
- "${item.query}" - ${item.count} times -
- ` - ).join("")} -
-
- ` : '

No search history yet.

'} -
- - - -
- - `; - return chunkSHCYIZAN_cjs.renderAdminLayout({ - title: "AI Search Settings", - pageTitle: "AI Search Settings", - currentPath: "/admin/plugins/ai-search/settings", - user: data.user, - content: content2 - }); -} - -// src/plugins/core-plugins/ai-search-plugin/routes/admin.ts -var adminRoutes = new hono.Hono(); -adminRoutes.use("*", chunkDVQA5II3_cjs.requireAuth()); -adminRoutes.get("/", async (c) => { - try { - const user = c.get("user"); - const db = c.env.DB; - const ai = c.env.AI; - const vectorize = c.env.VECTORIZE_INDEX; - const service = new AISearchService(db, ai, vectorize); - const indexer = new IndexManager(db, ai, vectorize); - const settings = await service.getSettings(); - console.log("[AI Search Settings Route] Settings loaded:", !!settings); - const collections2 = await service.getAllCollections(); - console.log("[AI Search Settings Route] Collections returned:", collections2.length); - if (collections2.length === 0) { - const directQuery = await db.prepare("SELECT id, name, display_name FROM collections WHERE is_active = 1").all(); - console.log("[AI Search Settings Route] Direct DB query found:", directQuery.results?.length || 0, "collections"); - if (directQuery.results && directQuery.results.length > 0) { - console.log("[AI Search Settings Route] Sample from DB:", directQuery.results[0]); - } - } else if (collections2.length > 0 && collections2[0]) { - console.log("[AI Search Settings Route] First collection:", { - id: collections2[0].id, - name: collections2[0].name, - display_name: collections2[0].display_name - }); - } - const newCollections = await service.detectNewCollections(); - console.log("AI Search: New collections:", newCollections.length); - const indexStatus = await indexer.getAllIndexStatus(); - console.log("AI Search: Index status:", Object.keys(indexStatus).length); - const analytics = await service.getSearchAnalytics(); - return c.html( - renderSettingsPage({ - settings, - collections: collections2 || [], - newCollections: newCollections || [], - indexStatus: indexStatus || {}, - analytics, - user: { - name: user.email, - email: user.email, - role: user.role - } - }) - ); - } catch (error) { - console.error("Error rendering AI Search settings:", error); - return c.html(`

Error loading settings: ${error instanceof Error ? error.message : String(error)}

`, 500); - } -}); -adminRoutes.post("/", async (c) => { - try { - const db = c.env.DB; - const ai = c.env.AI; - const vectorize = c.env.VECTORIZE_INDEX; - const service = new AISearchService(db, ai, vectorize); - const indexer = new IndexManager(db, ai, vectorize); - const body = await c.req.json(); - console.log("[AI Search POST] Received body:", JSON.stringify(body, null, 2)); - const currentSettings = await service.getSettings(); - console.log("[AI Search POST] Current settings selected_collections:", currentSettings?.selected_collections); - const updatedSettings = { - enabled: body.enabled !== void 0 ? Boolean(body.enabled) : currentSettings?.enabled, - ai_mode_enabled: body.ai_mode_enabled !== void 0 ? Boolean(body.ai_mode_enabled) : currentSettings?.ai_mode_enabled, - selected_collections: Array.isArray(body.selected_collections) ? body.selected_collections.map(String) : currentSettings?.selected_collections || [], - dismissed_collections: Array.isArray(body.dismissed_collections) ? body.dismissed_collections.map(String) : currentSettings?.dismissed_collections || [], - autocomplete_enabled: body.autocomplete_enabled !== void 0 ? Boolean(body.autocomplete_enabled) : currentSettings?.autocomplete_enabled, - cache_duration: body.cache_duration ? Number(body.cache_duration) : currentSettings?.cache_duration, - results_limit: body.results_limit ? Number(body.results_limit) : currentSettings?.results_limit, - index_media: body.index_media !== void 0 ? Boolean(body.index_media) : currentSettings?.index_media - }; - console.log("[AI Search POST] Updated settings selected_collections:", updatedSettings.selected_collections); - const collectionsChanged = JSON.stringify(updatedSettings.selected_collections) !== JSON.stringify(currentSettings?.selected_collections || []); - const saved = await service.updateSettings(updatedSettings); - console.log("[AI Search POST] Settings saved, selected_collections:", saved.selected_collections); - if (collectionsChanged && updatedSettings.selected_collections) { - console.log("[AI Search POST] Collections changed, starting background indexing"); - c.executionCtx.waitUntil( - indexer.syncAll(updatedSettings.selected_collections).then(() => console.log("[AI Search POST] Background indexing completed")).catch((error) => console.error("[AI Search POST] Background indexing error:", error)) - ); - } - return c.json({ success: true, settings: saved }); - } catch (error) { - console.error("Error updating AI Search settings:", error); - return c.json({ error: "Failed to update settings" }, 500); - } -}); -adminRoutes.get("/api/settings", async (c) => { - try { - const db = c.env.DB; - const ai = c.env.AI; - const vectorize = c.env.VECTORIZE_INDEX; - const service = new AISearchService(db, ai, vectorize); - const settings = await service.getSettings(); - return c.json({ success: true, data: settings }); - } catch (error) { - console.error("Error fetching settings:", error); - return c.json({ error: "Failed to fetch settings" }, 500); - } -}); -adminRoutes.get("/api/new-collections", async (c) => { - try { - const db = c.env.DB; - const ai = c.env.AI; - const vectorize = c.env.VECTORIZE_INDEX; - const service = new AISearchService(db, ai, vectorize); - const notifications = await service.detectNewCollections(); - return c.json({ success: true, data: notifications }); - } catch (error) { - console.error("Error detecting new collections:", error); - return c.json({ error: "Failed to detect new collections" }, 500); - } -}); -adminRoutes.get("/api/status", async (c) => { - try { - const db = c.env.DB; - const ai = c.env.AI; - const vectorize = c.env.VECTORIZE_INDEX; - const indexer = new IndexManager(db, ai, vectorize); - const status = await indexer.getAllIndexStatus(); - return c.json({ success: true, data: status }); - } catch (error) { - console.error("Error fetching index status:", error); - return c.json({ error: "Failed to fetch status" }, 500); - } -}); -adminRoutes.post("/api/reindex", async (c) => { - try { - const db = c.env.DB; - const ai = c.env.AI; - const vectorize = c.env.VECTORIZE_INDEX; - const indexer = new IndexManager(db, ai, vectorize); - const body = await c.req.json(); - const collectionIdRaw = body.collection_id; - const collectionId = collectionIdRaw ? String(collectionIdRaw) : ""; - if (!collectionId || collectionId === "undefined" || collectionId === "null") { - return c.json({ error: "collection_id is required" }, 400); - } - c.executionCtx.waitUntil( - indexer.indexCollection(collectionId).then(() => console.log(`[AI Search Reindex] Completed for collection ${collectionId}`)).catch((error) => console.error(`[AI Search Reindex] Error for collection ${collectionId}:`, error)) - ); - return c.json({ success: true, message: "Re-indexing started" }); - } catch (error) { - console.error("Error starting re-index:", error); - return c.json({ error: "Failed to start re-indexing" }, 500); - } -}); -var admin_default = adminRoutes; -var apiRoutes = new hono.Hono(); -apiRoutes.post("/", async (c) => { - try { - const db = c.env.DB; - const ai = c.env.AI; - const vectorize = c.env.VECTORIZE_INDEX; - const service = new AISearchService(db, ai, vectorize); - const body = await c.req.json(); - const query = { - query: body.query || "", - mode: body.mode || "keyword", - filters: body.filters || {}, - limit: body.limit ? Number(body.limit) : void 0, - offset: body.offset ? Number(body.offset) : void 0 - }; - if (query.filters?.dateRange) { - if (typeof query.filters.dateRange.start === "string") { - query.filters.dateRange.start = new Date(query.filters.dateRange.start); - } - if (typeof query.filters.dateRange.end === "string") { - query.filters.dateRange.end = new Date(query.filters.dateRange.end); - } - } - const results = await service.search(query); - return c.json({ - success: true, - data: results - }); - } catch (error) { - console.error("Search error:", error); - return c.json( - { - success: false, - error: "Search failed", - message: error instanceof Error ? error.message : String(error) - }, - 500 - ); - } -}); -apiRoutes.get("/suggest", async (c) => { - try { - const db = c.env.DB; - const ai = c.env.AI; - const vectorize = c.env.VECTORIZE_INDEX; - const service = new AISearchService(db, ai, vectorize); - const query = c.req.query("q") || ""; - if (!query || query.length < 2) { - return c.json({ success: true, data: [] }); - } - const suggestions = await service.getSearchSuggestions(query); - return c.json({ - success: true, - data: suggestions - }); - } catch (error) { - console.error("Suggestions error:", error); - return c.json( - { - success: false, - error: "Failed to get suggestions" - }, - 500 - ); - } -}); -apiRoutes.get("/analytics", async (c) => { - try { - const db = c.env.DB; - const ai = c.env.AI; - const vectorize = c.env.VECTORIZE_INDEX; - const service = new AISearchService(db, ai, vectorize); - const analytics = await service.getSearchAnalytics(); - return c.json({ - success: true, - data: analytics - }); - } catch (error) { - console.error("Analytics error:", error); - return c.json( - { - success: false, - error: "Failed to get analytics" - }, - 500 - ); - } -}); -var api_default2 = apiRoutes; - -// src/plugins/core-plugins/ai-search-plugin/manifest.json -var manifest_default = { - name: "AI Search", - description: "Advanced search with Cloudflare AI Search. Full-text search, semantic search, and advanced filtering across all content collections.", - version: "1.0.0", - author: "SonicJS"}; - -// src/plugins/core-plugins/ai-search-plugin/index.ts -var aiSearchPlugin = new chunk6FHNRRJ3_cjs.PluginBuilder({ - name: manifest_default.name, - version: manifest_default.version, - description: manifest_default.description, - author: { name: manifest_default.author } -}).metadata({ - description: manifest_default.description, - author: { name: manifest_default.author } -}).addService("aiSearch", AISearchService).addService("indexManager", IndexManager).addRoute("/admin/plugins/ai-search", admin_default).addRoute("/api/search", api_default2).build(); -var magicLinkRequestSchema = zod.z.object({ - email: zod.z.string().email("Valid email is required") -}); -function createMagicLinkAuthPlugin() { - const magicLinkRoutes = new hono.Hono(); - magicLinkRoutes.post("/request", async (c) => { - try { - const body = await c.req.json(); - const validation = magicLinkRequestSchema.safeParse(body); - if (!validation.success) { - return c.json({ - error: "Validation failed", - details: validation.error.issues - }, 400); - } - const { email } = validation.data; - const normalizedEmail = email.toLowerCase(); - const db = c.env.DB; - const oneHourAgo = Date.now() - 60 * 60 * 1e3; - const recentLinks = await db.prepare(` - SELECT COUNT(*) as count - FROM magic_links - WHERE user_email = ? AND created_at > ? - `).bind(normalizedEmail, oneHourAgo).first(); - const rateLimitPerHour = 5; - if (recentLinks && recentLinks.count >= rateLimitPerHour) { - return c.json({ - error: "Too many requests. Please try again later." - }, 429); - } - const user = await db.prepare(` - SELECT id, email, role, is_active - FROM users - WHERE email = ? - `).bind(normalizedEmail).first(); - const allowNewUsers = false; - if (!user && !allowNewUsers) { - return c.json({ - message: "If an account exists for this email, you will receive a magic link shortly." - }); - } - if (user && !user.is_active) { - return c.json({ - error: "This account has been deactivated." - }, 403); - } - const token = crypto.randomUUID() + "-" + crypto.randomUUID(); - const tokenId = crypto.randomUUID(); - const linkExpiryMinutes = 15; - const expiresAt = Date.now() + linkExpiryMinutes * 60 * 1e3; - await db.prepare(` - INSERT INTO magic_links ( - id, user_email, token, expires_at, used, created_at, ip_address, user_agent - ) VALUES (?, ?, ?, ?, 0, ?, ?, ?) - `).bind( - tokenId, - normalizedEmail, - token, - expiresAt, - Date.now(), - c.req.header("cf-connecting-ip") || c.req.header("x-forwarded-for") || "unknown", - c.req.header("user-agent") || "unknown" - ).run(); - const baseUrl = new URL(c.req.url).origin; - const magicLink = `${baseUrl}/auth/magic-link/verify?token=${token}`; - try { - const emailPlugin2 = c.env.plugins?.get("email"); - if (emailPlugin2 && emailPlugin2.sendEmail) { - await emailPlugin2.sendEmail({ - to: normalizedEmail, - subject: "Your Magic Link to Sign In", - html: renderMagicLinkEmail(magicLink, linkExpiryMinutes) - }); - } else { - console.error("Email plugin not available"); - console.log(`Magic link for ${normalizedEmail}: ${magicLink}`); - } - } catch (error) { - console.error("Failed to send magic link email:", error); - return c.json({ - error: "Failed to send email. Please try again later." - }, 500); - } - return c.json({ - message: "If an account exists for this email, you will receive a magic link shortly.", - // For development only - remove in production - ...c.env.ENVIRONMENT === "development" && { dev_link: magicLink } - }); - } catch (error) { - console.error("Magic link request error:", error); - return c.json({ error: "Failed to process request" }, 500); - } - }); - magicLinkRoutes.get("/verify", async (c) => { - try { - const token = c.req.query("token"); - if (!token) { - return c.redirect("/auth/login?error=Invalid magic link"); - } - const db = c.env.DB; - const magicLink = await db.prepare(` - SELECT * FROM magic_links - WHERE token = ? AND used = 0 - `).bind(token).first(); - if (!magicLink) { - return c.redirect("/auth/login?error=Invalid or expired magic link"); - } - if (magicLink.expires_at < Date.now()) { - return c.redirect("/auth/login?error=This magic link has expired"); - } - let user = await db.prepare(` - SELECT * FROM users WHERE email = ? AND is_active = 1 - `).bind(magicLink.user_email).first(); - const allowNewUsers = false; - if (!user && allowNewUsers) { - const userId = crypto.randomUUID(); - const username = magicLink.user_email.split("@")[0]; - const now = Date.now(); - await db.prepare(` - INSERT INTO users ( - id, email, username, first_name, last_name, - password_hash, role, is_active, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, NULL, 'viewer', 1, ?, ?) - `).bind( - userId, - magicLink.user_email, - username, - username, - "", - now, - now - ).run(); - user = { - id: userId, - email: magicLink.user_email, - username, - role: "viewer" - }; - } else if (!user) { - return c.redirect("/auth/login?error=No account found for this email"); - } - await db.prepare(` - UPDATE magic_links - SET used = 1, used_at = ? - WHERE id = ? - `).bind(Date.now(), magicLink.id).run(); - const jwtToken = await chunkDVQA5II3_cjs.AuthManager.generateToken( - user.id, - user.email, - user.role - ); - chunkDVQA5II3_cjs.AuthManager.setAuthCookie(c, jwtToken); - await db.prepare(` - UPDATE users SET last_login_at = ? WHERE id = ? - `).bind(Date.now(), user.id).run(); - return c.redirect("/admin/dashboard?message=Successfully signed in"); - } catch (error) { - console.error("Magic link verification error:", error); - return c.redirect("/auth/login?error=Authentication failed"); - } - }); - return { - name: "magic-link-auth", - version: "1.0.0", - description: "Passwordless authentication via email magic links", - author: { - name: "SonicJS Team", - email: "team@sonicjs.com" - }, - dependencies: ["email"], - routes: [{ - path: "/auth/magic-link", - handler: magicLinkRoutes, - description: "Magic link authentication endpoints", - requiresAuth: false - }], - async install(context) { - console.log("Installing magic-link-auth plugin..."); - }, - async activate(context) { - console.log("Magic link authentication activated"); - console.log("Users can now sign in via /auth/magic-link/request"); - }, - async deactivate(context) { - console.log("Magic link authentication deactivated"); - }, - async uninstall(context) { - console.log("Uninstalling magic-link-auth plugin..."); - } - }; -} -function renderMagicLinkEmail(magicLink, expiryMinutes) { - return ` - - - - - - Your Magic Link - - - -
-
-

\u{1F517} Your Magic Link

-
- -
-

Hello!

-

You requested a magic link to sign in to your account. Click the button below to continue:

- -
- Sign In -
- -

\u23F0 This link expires in ${expiryMinutes} minutes

- -
- Security Notice: If you didn't request this link, you can safely ignore this email. - Someone may have entered your email address by mistake. -
-
- - -
- - - `; -} -createMagicLinkAuthPlugin(); - -// src/plugins/cache/services/cache-config.ts -var CACHE_CONFIGS = { - // Content (high read, low write) - content: { - ttl: 3600, - // 1 hour - kvEnabled: true, - memoryEnabled: true, - namespace: "content", - invalidateOn: ["content.update", "content.delete", "content.publish"], - version: "v1" - }, - // User data (medium read, medium write) - user: { - ttl: 900, - // 15 minutes - kvEnabled: true, - memoryEnabled: true, - namespace: "user", - invalidateOn: ["user.update", "user.delete", "auth.login"], - version: "v1" - }, - // Configuration (high read, very low write) - config: { - ttl: 7200, - // 2 hours - kvEnabled: true, - memoryEnabled: true, - namespace: "config", - invalidateOn: ["config.update", "plugin.activate", "plugin.deactivate"], - version: "v1" - }, - // Media metadata (high read, low write) - media: { - ttl: 3600, - // 1 hour - kvEnabled: true, - memoryEnabled: true, - namespace: "media", - invalidateOn: ["media.upload", "media.delete", "media.update"], - version: "v1" - }, - // API responses (very high read, low write) - api: { - ttl: 300, - // 5 minutes - kvEnabled: true, - memoryEnabled: true, - namespace: "api", - invalidateOn: ["content.update", "content.publish"], - version: "v1" - }, - // Session data (very high read, medium write) - session: { - ttl: 1800, - // 30 minutes - kvEnabled: false, - // Only in-memory for sessions - memoryEnabled: true, - namespace: "session", - invalidateOn: ["auth.logout"], - version: "v1" - }, - // Plugin data - plugin: { - ttl: 3600, - // 1 hour - kvEnabled: true, - memoryEnabled: true, - namespace: "plugin", - invalidateOn: ["plugin.activate", "plugin.deactivate", "plugin.update"], - version: "v1" - }, - // Collections/schema - collection: { - ttl: 7200, - // 2 hours - kvEnabled: true, - memoryEnabled: true, - namespace: "collection", - invalidateOn: ["collection.update", "collection.delete"], - version: "v1" - } -}; -function getCacheConfig(namespace) { - return CACHE_CONFIGS[namespace] || { - ttl: 3600, - kvEnabled: true, - memoryEnabled: true, - namespace, - invalidateOn: [], - version: "v1" - }; -} -function generateCacheKey(namespace, type, identifier, version) { - const v = version || getCacheConfig(namespace).version || "v1"; - return `${namespace}:${type}:${identifier}:${v}`; -} -function parseCacheKey(key) { - const parts = key.split(":"); - if (parts.length !== 4) { - return null; - } - return { - namespace: parts[0] || "", - type: parts[1] || "", - identifier: parts[2] || "", - version: parts[3] || "" - }; -} - -// src/plugins/cache/services/cache.ts -var MemoryCache = class { - cache = /* @__PURE__ */ new Map(); - maxSize = 50 * 1024 * 1024; - // 50MB - currentSize = 0; - /** - * Get item from memory cache - */ - get(key) { - const entry = this.cache.get(key); - if (!entry) { - return null; - } - if (Date.now() > entry.expiresAt) { - this.delete(key); - return null; - } - return entry.data; - } - /** - * Set item in memory cache - */ - set(key, value, ttl, version = "v1") { - const now = Date.now(); - const entry = { - data: value, - timestamp: now, - expiresAt: now + ttl * 1e3, - version - }; - const entrySize = JSON.stringify(entry).length * 2; - if (this.currentSize + entrySize > this.maxSize) { - this.evictLRU(entrySize); - } - if (this.cache.has(key)) { - this.delete(key); - } - this.cache.set(key, entry); - this.currentSize += entrySize; - } - /** - * Delete item from memory cache - */ - delete(key) { - const entry = this.cache.get(key); - if (entry) { - const entrySize = JSON.stringify(entry).length * 2; - this.currentSize -= entrySize; - return this.cache.delete(key); - } - return false; - } - /** - * Clear all items from memory cache - */ - clear() { - this.cache.clear(); - this.currentSize = 0; - } - /** - * Get cache statistics - */ - getStats() { - return { - size: this.currentSize, - count: this.cache.size - }; - } - /** - * Evict least recently used items to make space - */ - evictLRU(neededSpace) { - const entries = Array.from(this.cache.entries()).sort( - (a, b) => a[1].timestamp - b[1].timestamp - ); - let freedSpace = 0; - for (const [key, entry] of entries) { - if (freedSpace >= neededSpace) break; - const entrySize = JSON.stringify(entry).length * 2; - this.delete(key); - freedSpace += entrySize; - } - } - /** - * Delete items matching a pattern - */ - invalidatePattern(pattern) { - const regex = new RegExp( - "^" + pattern.replace(/\*/g, ".*").replace(/\?/g, ".") + "$" - ); - let count = 0; - for (const key of this.cache.keys()) { - if (regex.test(key)) { - this.delete(key); - count++; - } - } - return count; - } -}; -var CacheService = class { - memoryCache; - config; - stats; - kvNamespace; - constructor(config, kvNamespace) { - this.memoryCache = new MemoryCache(); - this.config = config; - this.kvNamespace = kvNamespace; - this.stats = { - memoryHits: 0, - memoryMisses: 0, - kvHits: 0, - kvMisses: 0, - dbHits: 0, - totalRequests: 0, - hitRate: 0, - memorySize: 0, - entryCount: 0 - }; - } - /** - * Get value from cache (tries memory first, then KV) - */ - async get(key) { - this.stats.totalRequests++; - if (this.config.memoryEnabled) { - const memoryValue = this.memoryCache.get(key); - if (memoryValue !== null) { - this.stats.memoryHits++; - this.updateHitRate(); - return memoryValue; - } - this.stats.memoryMisses++; - } - if (this.config.kvEnabled && this.kvNamespace) { - try { - const kvValue = await this.kvNamespace.get(key, "json"); - if (kvValue !== null) { - this.stats.kvHits++; - if (this.config.memoryEnabled) { - this.memoryCache.set(key, kvValue, this.config.ttl, this.config.version); - } - this.updateHitRate(); - return kvValue; - } - this.stats.kvMisses++; - } catch (error) { - console.error("KV cache read error:", error); - this.stats.kvMisses++; - } - } - this.updateHitRate(); - return null; - } - /** - * Get value from cache with source information - */ - async getWithSource(key) { - this.stats.totalRequests++; - if (this.config.memoryEnabled) { - const memoryValue = this.memoryCache.get(key); - if (memoryValue !== null) { - this.stats.memoryHits++; - this.updateHitRate(); - const entry = await this.getEntry(key); - return { - data: memoryValue, - source: "memory", - hit: true, - timestamp: entry?.timestamp, - ttl: entry?.ttl - }; - } - this.stats.memoryMisses++; - } - if (this.config.kvEnabled && this.kvNamespace) { - try { - const kvValue = await this.kvNamespace.get(key, "json"); - if (kvValue !== null) { - this.stats.kvHits++; - if (this.config.memoryEnabled) { - this.memoryCache.set(key, kvValue, this.config.ttl, this.config.version); - } - this.updateHitRate(); - return { - data: kvValue, - source: "kv", - hit: true - }; - } - this.stats.kvMisses++; - } catch (error) { - console.error("KV cache read error:", error); - this.stats.kvMisses++; - } - } - this.updateHitRate(); - return { - data: null, - source: "miss", - hit: false - }; - } - /** - * Set value in cache (stores in both memory and KV) - */ - async set(key, value, customConfig) { - const config = { ...this.config, ...customConfig }; - if (config.memoryEnabled) { - this.memoryCache.set(key, value, config.ttl, config.version); - } - if (config.kvEnabled && this.kvNamespace) { - try { - await this.kvNamespace.put(key, JSON.stringify(value), { - expirationTtl: config.ttl - }); - } catch (error) { - console.error("KV cache write error:", error); - } - } - } - /** - * Delete value from cache (removes from both memory and KV) - */ - async delete(key) { - if (this.config.memoryEnabled) { - this.memoryCache.delete(key); - } - if (this.config.kvEnabled && this.kvNamespace) { - try { - await this.kvNamespace.delete(key); - } catch (error) { - console.error("KV cache delete error:", error); - } - } - } - /** - * Clear all cache entries for this namespace - */ - async clear() { - if (this.config.memoryEnabled) { - this.memoryCache.clear(); - } - this.stats = { - memoryHits: 0, - memoryMisses: 0, - kvHits: 0, - kvMisses: 0, - dbHits: 0, - totalRequests: 0, - hitRate: 0, - memorySize: 0, - entryCount: 0 - }; - } - /** - * Invalidate cache entries matching a pattern - */ - async invalidate(pattern) { - let count = 0; - if (this.config.memoryEnabled) { - count += this.memoryCache.invalidatePattern(pattern); - } - if (this.config.kvEnabled && this.kvNamespace) { - try { - const regex = new RegExp( - "^" + pattern.replace(/\*/g, ".*").replace(/\?/g, ".") + "$" - ); - const prefix = this.config.namespace + ":"; - const list = await this.kvNamespace.list({ prefix }); - for (const key of list.keys) { - if (regex.test(key.name)) { - await this.kvNamespace.delete(key.name); - count++; - } - } - } catch (error) { - console.error("KV cache invalidation error:", error); - } - } - return count; - } - /** - * Invalidate cache entries matching a pattern (alias for invalidate) - */ - async invalidatePattern(pattern) { - return this.invalidate(pattern); - } - /** - * Get cache statistics - */ - getStats() { - const memStats = this.memoryCache.getStats(); - return { - ...this.stats, - memorySize: memStats.size, - entryCount: memStats.count - }; - } - /** - * Update hit rate calculation - */ - updateHitRate() { - const totalHits = this.stats.memoryHits + this.stats.kvHits + this.stats.dbHits; - this.stats.hitRate = this.stats.totalRequests > 0 ? totalHits / this.stats.totalRequests * 100 : 0; - } - /** - * Generate a cache key using the configured namespace - */ - generateKey(type, identifier) { - return generateCacheKey( - this.config.namespace, - type, - identifier, - this.config.version - ); - } - /** - * Warm cache with multiple entries - */ - async warmCache(entries) { - for (const entry of entries) { - await this.set(entry.key, entry.value); - } - } - /** - * Check if a key exists in cache - */ - async has(key) { - const value = await this.get(key); - return value !== null; - } - /** - * Get multiple values at once - */ - async getMany(keys) { - const results = /* @__PURE__ */ new Map(); - for (const key of keys) { - const value = await this.get(key); - if (value !== null) { - results.set(key, value); - } - } - return results; - } - /** - * Set multiple values at once - */ - async setMany(entries, customConfig) { - for (const entry of entries) { - await this.set(entry.key, entry.value, customConfig); - } - } - /** - * Delete multiple keys at once - */ - async deleteMany(keys) { - for (const key of keys) { - await this.delete(key); - } - } - /** - * Get or set pattern - fetch from cache or compute if not found - */ - async getOrSet(key, fetcher, customConfig) { - const cached = await this.get(key); - if (cached !== null) { - return cached; - } - const value = await fetcher(); - await this.set(key, value, customConfig); - return value; - } - /** - * List all cache keys with metadata - */ - async listKeys() { - const keys = []; - if (this.config.memoryEnabled) { - const cache = this.memoryCache.cache; - for (const [key, entry] of cache.entries()) { - const size = JSON.stringify(entry).length * 2; - const age = Date.now() - entry.timestamp; - keys.push({ - key, - size, - expiresAt: entry.expiresAt, - age - }); - } - } - return keys.sort((a, b) => a.age - b.age); - } - /** - * Get cache entry with full metadata - */ - async getEntry(key) { - if (!this.config.memoryEnabled) { - return null; - } - const cache = this.memoryCache.cache; - const entry = cache.get(key); - if (!entry) { - return null; - } - if (Date.now() > entry.expiresAt) { - await this.delete(key); - return null; - } - const size = JSON.stringify(entry).length * 2; - const ttl = Math.max(0, entry.expiresAt - Date.now()) / 1e3; - return { - data: entry.data, - timestamp: entry.timestamp, - expiresAt: entry.expiresAt, - ttl, - size - }; - } -}; -var cacheInstances = /* @__PURE__ */ new Map(); -var globalKVNamespace; -function getCacheService(config, kvNamespace) { - const key = config.namespace; - if (!cacheInstances.has(key)) { - const kv = globalKVNamespace; - cacheInstances.set(key, new CacheService(config, kv)); - } - return cacheInstances.get(key); -} -async function clearAllCaches() { - for (const cache of cacheInstances.values()) { - await cache.clear(); - } -} -function getAllCacheStats() { - const stats = {}; - for (const [namespace, cache] of cacheInstances.entries()) { - stats[namespace] = cache.getStats(); - } - return stats; -} - -// src/plugins/cache/services/event-bus.ts -var EventBus = class { - subscriptions = /* @__PURE__ */ new Map(); - eventLog = []; - maxLogSize = 100; - /** - * Subscribe to an event - */ - on(event, handler) { - if (!this.subscriptions.has(event)) { - this.subscriptions.set(event, []); - } - this.subscriptions.get(event).push(handler); - return () => { - const handlers = this.subscriptions.get(event); - if (handlers) { - const index = handlers.indexOf(handler); - if (index > -1) { - handlers.splice(index, 1); - } - } - }; - } - /** - * Emit an event to all subscribers - */ - async emit(event, data) { - this.logEvent(event, data); - const handlers = this.subscriptions.get(event) || []; - await Promise.all( - handlers.map(async (handler) => { - try { - await handler(data); - } catch (error) { - console.error(`Error in event handler for ${event}:`, error); - } - }) - ); - const wildcardHandlers = this.subscriptions.get("*") || []; - await Promise.all( - wildcardHandlers.map(async (handler) => { - try { - await handler({ event, data }); - } catch (error) { - console.error(`Error in wildcard event handler for ${event}:`, error); - } - }) - ); - } - /** - * Remove all subscribers for an event - */ - off(event) { - this.subscriptions.delete(event); - } - /** - * Get all registered events - */ - getEvents() { - return Array.from(this.subscriptions.keys()); - } - /** - * Get subscriber count for an event - */ - getSubscriberCount(event) { - return this.subscriptions.get(event)?.length || 0; - } - /** - * Log an event for debugging - */ - logEvent(event, data) { - this.eventLog.push({ - event, - timestamp: Date.now(), - data - }); - if (this.eventLog.length > this.maxLogSize) { - this.eventLog.shift(); - } - } - /** - * Get recent event log - */ - getEventLog(limit = 50) { - return this.eventLog.slice(-limit); - } - /** - * Clear event log - */ - clearEventLog() { - this.eventLog = []; - } - /** - * Get statistics - */ - getStats() { - const eventCounts = {}; - for (const log of this.eventLog) { - eventCounts[log.event] = (eventCounts[log.event] || 0) + 1; - } - return { - totalEvents: this.eventLog.length, - totalSubscriptions: this.subscriptions.size, - eventCounts - }; - } -}; -var globalEventBus = null; -function getEventBus() { - if (!globalEventBus) { - globalEventBus = new EventBus(); - } - return globalEventBus; -} -function onEvent(event, handler) { - const bus = getEventBus(); - return bus.on(event, handler); -} - -// src/plugins/cache/services/cache-invalidation.ts -function setupCacheInvalidation() { - getEventBus(); - setupContentInvalidation(); - setupUserInvalidation(); - setupConfigInvalidation(); - setupMediaInvalidation(); - setupAPIInvalidation(); - setupCollectionInvalidation(); - console.log("Cache invalidation listeners registered"); -} -function setupContentInvalidation() { - const config = CACHE_CONFIGS.content; - if (!config) return; - const contentCache = getCacheService(config); - onEvent("content.create", async (_data) => { - await contentCache.invalidate("content:*"); - console.log("Cache invalidated: content.create"); - }); - onEvent("content.update", async (data) => { - if (data?.id) { - await contentCache.delete(contentCache.generateKey("item", data.id)); - } - await contentCache.invalidate("content:list:*"); - console.log("Cache invalidated: content.update", data?.id); - }); - onEvent("content.delete", async (data) => { - if (data?.id) { - await contentCache.delete(contentCache.generateKey("item", data.id)); - } - await contentCache.invalidate("content:*"); - console.log("Cache invalidated: content.delete", data?.id); - }); - onEvent("content.publish", async (_data) => { - await contentCache.invalidate("content:*"); - console.log("Cache invalidated: content.publish"); - }); -} -function setupUserInvalidation() { - const config = CACHE_CONFIGS.user; - if (!config) return; - const userCache = getCacheService(config); - onEvent("user.update", async (data) => { - if (data?.id) { - await userCache.delete(userCache.generateKey("id", data.id)); - } - if (data?.email) { - await userCache.delete(userCache.generateKey("email", data.email)); - } - console.log("Cache invalidated: user.update", data?.id); - }); - onEvent("user.delete", async (data) => { - if (data?.id) { - await userCache.delete(userCache.generateKey("id", data.id)); - } - if (data?.email) { - await userCache.delete(userCache.generateKey("email", data.email)); - } - console.log("Cache invalidated: user.delete", data?.id); - }); - onEvent("auth.login", async (data) => { - if (data?.userId) { - await userCache.delete(userCache.generateKey("id", data.userId)); - } - console.log("Cache invalidated: auth.login", data?.userId); - }); - onEvent("auth.logout", async (data) => { - const sessionConfig = CACHE_CONFIGS.session; - if (sessionConfig) { - const sessionCache = getCacheService(sessionConfig); - if (data?.sessionId) { - await sessionCache.delete(sessionCache.generateKey("session", data.sessionId)); - } - } - console.log("Cache invalidated: auth.logout"); - }); -} -function setupConfigInvalidation() { - const configConfig = CACHE_CONFIGS.config; - if (!configConfig) return; - const configCache = getCacheService(configConfig); - onEvent("config.update", async (_data) => { - await configCache.invalidate("config:*"); - console.log("Cache invalidated: config.update"); - }); - onEvent("plugin.activate", async (data) => { - await configCache.invalidate("config:*"); - const pluginConfig = CACHE_CONFIGS.plugin; - if (pluginConfig) { - const pluginCache = getCacheService(pluginConfig); - await pluginCache.invalidate("plugin:*"); - } - console.log("Cache invalidated: plugin.activate", data?.pluginId); - }); - onEvent("plugin.deactivate", async (data) => { - await configCache.invalidate("config:*"); - const pluginConfig = CACHE_CONFIGS.plugin; - if (pluginConfig) { - const pluginCache = getCacheService(pluginConfig); - await pluginCache.invalidate("plugin:*"); - } - console.log("Cache invalidated: plugin.deactivate", data?.pluginId); - }); - onEvent("plugin.update", async (data) => { - const pluginConfig = CACHE_CONFIGS.plugin; - if (!pluginConfig) return; - const pluginCache = getCacheService(pluginConfig); - await pluginCache.invalidate("plugin:*"); - console.log("Cache invalidated: plugin.update", data?.pluginId); - }); -} -function setupMediaInvalidation() { - const config = CACHE_CONFIGS.media; - if (!config) return; - const mediaCache = getCacheService(config); - onEvent("media.upload", async (_data) => { - await mediaCache.invalidate("media:*"); - console.log("Cache invalidated: media.upload"); - }); - onEvent("media.delete", async (data) => { - if (data?.id) { - await mediaCache.delete(mediaCache.generateKey("item", data.id)); - } - await mediaCache.invalidate("media:list:*"); - console.log("Cache invalidated: media.delete", data?.id); - }); - onEvent("media.update", async (data) => { - if (data?.id) { - await mediaCache.delete(mediaCache.generateKey("item", data.id)); - } - await mediaCache.invalidate("media:list:*"); - console.log("Cache invalidated: media.update", data?.id); - }); -} -function setupAPIInvalidation() { - const config = CACHE_CONFIGS.api; - if (!config) return; - const apiCache = getCacheService(config); - onEvent("content.update", async (_data) => { - await apiCache.invalidate("api:*"); - console.log("Cache invalidated: api (content.update)"); - }); - onEvent("content.publish", async (_data) => { - await apiCache.invalidate("api:*"); - console.log("Cache invalidated: api (content.publish)"); - }); - onEvent("content.create", async (_data) => { - await apiCache.invalidate("api:*"); - console.log("Cache invalidated: api (content.create)"); - }); - onEvent("content.delete", async (_data) => { - await apiCache.invalidate("api:*"); - console.log("Cache invalidated: api (content.delete)"); - }); - onEvent("collection.update", async (_data) => { - await apiCache.invalidate("api:*"); - console.log("Cache invalidated: api (collection.update)"); - }); -} -function setupCollectionInvalidation() { - const config = CACHE_CONFIGS.collection; - if (!config) return; - const collectionCache = getCacheService(config); - onEvent("collection.create", async (_data) => { - await collectionCache.invalidate("collection:*"); - console.log("Cache invalidated: collection.create"); - }); - onEvent("collection.update", async (data) => { - if (data?.id) { - await collectionCache.delete(collectionCache.generateKey("item", data.id)); - } - await collectionCache.invalidate("collection:*"); - console.log("Cache invalidated: collection.update", data?.id); - }); - onEvent("collection.delete", async (data) => { - await collectionCache.invalidate("collection:*"); - console.log("Cache invalidated: collection.delete", data?.id); - }); -} -function getCacheInvalidationStats() { - const eventBus = getEventBus(); - return eventBus.getStats(); -} -function getRecentInvalidations(limit = 50) { - const eventBus = getEventBus(); - return eventBus.getEventLog(limit); -} - -// src/plugins/cache/services/cache-warming.ts -async function warmCommonCaches(db) { - let totalWarmed = 0; - let totalErrors = 0; - const details = []; - try { - const collectionCount = await warmCollections(db); - totalWarmed += collectionCount; - details.push({ namespace: "collection", count: collectionCount }); - const contentCount = await warmRecentContent(db); - totalWarmed += contentCount; - details.push({ namespace: "content", count: contentCount }); - const mediaCount = await warmRecentMedia(db); - totalWarmed += mediaCount; - details.push({ namespace: "media", count: mediaCount }); - } catch (error) { - console.error("Error warming caches:", error); - totalErrors++; - } - return { - warmed: totalWarmed, - errors: totalErrors, - details - }; -} -async function warmCollections(db) { - const config = CACHE_CONFIGS.collection; - if (!config) return 0; - const collectionCache = getCacheService(config); - let count = 0; - try { - const stmt = db.prepare("SELECT * FROM collections WHERE is_active = 1"); - const { results } = await stmt.all(); - for (const collection of results) { - const key = collectionCache.generateKey("item", collection.id); - await collectionCache.set(key, collection); - count++; - } - const listKey = collectionCache.generateKey("list", "all"); - await collectionCache.set(listKey, results); - count++; - } catch (error) { - console.error("Error warming collections cache:", error); - } - return count; -} -async function warmRecentContent(db, limit = 50) { - const config = CACHE_CONFIGS.content; - if (!config) return 0; - const contentCache = getCacheService(config); - let count = 0; - try { - const stmt = db.prepare(`SELECT * FROM content ORDER BY created_at DESC LIMIT ${limit}`); - const { results } = await stmt.all(); - for (const content2 of results) { - const key = contentCache.generateKey("item", content2.id); - await contentCache.set(key, content2); - count++; - } - const listKey = contentCache.generateKey("list", "recent"); - await contentCache.set(listKey, results); - count++; - } catch (error) { - console.error("Error warming content cache:", error); - } - return count; -} -async function warmRecentMedia(db, limit = 50) { - const config = CACHE_CONFIGS.media; - if (!config) return 0; - const mediaCache = getCacheService(config); - let count = 0; - try { - const stmt = db.prepare(`SELECT * FROM media WHERE deleted_at IS NULL ORDER BY uploaded_at DESC LIMIT ${limit}`); - const { results } = await stmt.all(); - for (const media2 of results) { - const key = mediaCache.generateKey("item", media2.id); - await mediaCache.set(key, media2); - count++; - } - const listKey = mediaCache.generateKey("list", "recent"); - await mediaCache.set(listKey, results); - count++; - } catch (error) { - console.error("Error warming media cache:", error); - } - return count; -} -async function warmNamespace(namespace, entries) { - const config = CACHE_CONFIGS[namespace]; - if (!config) { - throw new Error(`Unknown namespace: ${namespace}`); - } - const cache = getCacheService(config); - await cache.setMany(entries); - return entries.length; -} - -// src/templates/pages/admin-cache.template.ts -chunkSHCYIZAN_cjs.init_admin_layout_catalyst_template(); -function renderCacheDashboard(data) { - const pageContent = ` -
- -
-
-

Cache System

-

- Monitor and manage cache performance across all namespaces -

-
-
- - -
-
- - -
- ${renderStatCard("Total Requests", data.totals.requests.toLocaleString(), "lime", ` - - - - `)} - - ${renderStatCard("Hit Rate", data.totals.hitRate + "%", "blue", ` - - - - `, parseFloat(data.totals.hitRate) > 70 ? "lime" : parseFloat(data.totals.hitRate) > 40 ? "amber" : "red")} - - ${renderStatCard("Memory Usage", formatBytes(data.totals.memorySize), "purple", ` - - - - `)} - - ${renderStatCard("Cached Entries", data.totals.entryCount.toLocaleString(), "sky", ` - - - - `)} -
- - -
-
-

Cache Namespaces

-
-
- - - - - - - - - - - - - - - ${data.namespaces.map((namespace) => { - const stat = data.stats[namespace]; - if (!stat) return ""; - return renderNamespaceRow(namespace, stat); - }).join("")} - -
- Namespace - - Requests - - Hit Rate - - Memory Hits - - KV Hits - - Entries - - Size - - Actions -
-
-
- - -
-
-

Performance Overview

-
-
-
- ${renderPerformanceMetric("Memory Cache", data.totals.hits, data.totals.misses)} - ${renderHealthStatus(parseFloat(data.totals.hitRate))} -
-
-
-
- - - - - ${chunkVAPDSKKV_cjs.renderConfirmationDialog({ - id: "clear-all-cache-confirm", - title: "Clear All Cache", - message: "Are you sure you want to clear all cache entries? This cannot be undone.", - confirmText: "Clear All", - cancelText: "Cancel", - iconColor: "yellow", - confirmClass: "bg-yellow-500 hover:bg-yellow-400", - onConfirm: "performClearAllCaches()" - })} - - ${chunkVAPDSKKV_cjs.renderConfirmationDialog({ - id: "clear-namespace-cache-confirm", - title: "Clear Namespace Cache", - message: "Clear cache for this namespace?", - confirmText: "Clear", - cancelText: "Cancel", - iconColor: "yellow", - confirmClass: "bg-yellow-500 hover:bg-yellow-400", - onConfirm: "performClearNamespaceCache()" - })} - - ${chunkVAPDSKKV_cjs.getConfirmationDialogScript()} - `; - const layoutData = { - title: "Cache System", - pageTitle: "Cache System", - currentPath: "/admin/cache", - user: data.user, - version: data.version, - content: pageContent - }; - return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst(layoutData); -} -function renderStatCard(label, value, color, icon, colorOverride) { - const finalColor = colorOverride || color; - const colorClasses = { - lime: "bg-lime-50 dark:bg-lime-500/10 text-lime-600 dark:text-lime-400 ring-lime-600/20 dark:ring-lime-500/20", - blue: "bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 ring-blue-600/20 dark:ring-blue-500/20", - purple: "bg-purple-50 dark:bg-purple-500/10 text-purple-600 dark:text-purple-400 ring-purple-600/20 dark:ring-purple-500/20", - sky: "bg-sky-50 dark:bg-sky-500/10 text-sky-600 dark:text-sky-400 ring-sky-600/20 dark:ring-sky-500/20", - amber: "bg-amber-50 dark:bg-amber-500/10 text-amber-600 dark:text-amber-400 ring-amber-600/20 dark:ring-amber-500/20", - red: "bg-red-50 dark:bg-red-500/10 text-red-600 dark:text-red-400 ring-red-600/20 dark:ring-red-500/20" - }; - return ` -
-
-
-
-
- ${icon} -
-
-

${label}

-

${value}

-
-
-
-
-
- `; -} -function renderNamespaceRow(namespace, stat) { - const hitRate = stat.hitRate.toFixed(1); - const hitRateColor = stat.hitRate > 70 ? "text-lime-600 dark:text-lime-400" : stat.hitRate > 40 ? "text-amber-600 dark:text-amber-400" : "text-red-600 dark:text-red-400"; - return ` - - - - ${namespace} - - - - ${stat.totalRequests.toLocaleString()} - - - - ${hitRate}% - - - - ${stat.memoryHits.toLocaleString()} - - - ${stat.kvHits.toLocaleString()} - - - ${stat.entryCount.toLocaleString()} - - - ${formatBytes(stat.memorySize)} - - - - - - `; -} -function renderPerformanceMetric(label, hits, misses) { - const total = hits + misses; - const hitPercentage = total > 0 ? hits / total * 100 : 0; - return ` -
-

${label}

-
-
- Hits - ${hits.toLocaleString()} -
-
- Misses - ${misses.toLocaleString()} -
-
-
- Hit Rate - ${hitPercentage.toFixed(1)}% -
-
-
-
-
-
-
- `; -} -function renderHealthStatus(hitRate) { - const status = hitRate > 70 ? "healthy" : hitRate > 40 ? "warning" : "critical"; - const statusConfig = { - healthy: { - label: "Healthy", - color: "lime", - icon: ` - - ` - }, - warning: { - label: "Needs Attention", - color: "amber", - icon: ` - - ` - }, - critical: { - label: "Critical", - color: "red", - icon: ` - - ` - } - }; - const config = statusConfig[status]; - const colorClasses = { - lime: "bg-lime-50 dark:bg-lime-500/10 text-lime-600 dark:text-lime-400 ring-lime-600/20 dark:ring-lime-500/20", - amber: "bg-amber-50 dark:bg-amber-500/10 text-amber-600 dark:text-amber-400 ring-amber-600/20 dark:ring-amber-500/20", - red: "bg-red-50 dark:bg-red-500/10 text-red-600 dark:text-red-400 ring-red-600/20 dark:ring-red-500/20" - }; - return ` -
-

System Health

-
- ${config.icon} -
-

${config.label}

-

- ${status === "healthy" ? "Cache is performing well" : status === "warning" ? "Consider increasing cache TTL or capacity" : "Cache hit rate is too low"} -

-
-
-
- `; -} -function formatBytes(bytes) { - if (bytes === 0) return "0 B"; - const k = 1024; - const sizes = ["B", "KB", "MB", "GB"]; - const i = Math.floor(Math.log(bytes) / Math.log(k)); - return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`; -} - -// src/plugins/cache/routes.ts -var app = new hono.Hono(); -app.get("/", async (c) => { - const stats = getAllCacheStats(); - const user = c.get("user"); - let totalHits = 0; - let totalMisses = 0; - let totalSize = 0; - let totalEntries = 0; - Object.values(stats).forEach((stat) => { - totalHits += stat.memoryHits + stat.kvHits; - totalMisses += stat.memoryMisses + stat.kvMisses; - totalSize += stat.memorySize; - totalEntries += stat.entryCount; - }); - const totalRequests = totalHits + totalMisses; - const overallHitRate = totalRequests > 0 ? totalHits / totalRequests * 100 : 0; - const dashboardData = { - stats, - totals: { - hits: totalHits, - misses: totalMisses, - requests: totalRequests, - hitRate: overallHitRate.toFixed(2), - memorySize: totalSize, - entryCount: totalEntries - }, - namespaces: Object.keys(stats), - user: user ? { - name: user.email, - email: user.email, - role: user.role - } : void 0, - version: c.get("appVersion") - }; - return c.html(renderCacheDashboard(dashboardData)); -}); -app.get("/stats", async (c) => { - const stats = getAllCacheStats(); - return c.json({ - success: true, - data: stats, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -app.get("/stats/:namespace", async (c) => { - const namespace = c.req.param("namespace"); - const config = CACHE_CONFIGS[namespace]; - if (!config) { - return c.json({ - success: false, - error: `Unknown namespace: ${namespace}` - }, 404); - } - const cache = getCacheService(config); - const stats = cache.getStats(); - return c.json({ - success: true, - data: { - namespace, - config, - stats - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -app.post("/clear", async (c) => { - await clearAllCaches(); - return c.json({ - success: true, - message: "All cache entries cleared", - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -app.post("/clear/:namespace", async (c) => { - const namespace = c.req.param("namespace"); - const config = CACHE_CONFIGS[namespace]; - if (!config) { - return c.json({ - success: false, - error: `Unknown namespace: ${namespace}` - }, 404); - } - const cache = getCacheService(config); - await cache.clear(); - return c.json({ - success: true, - message: `Cache cleared for namespace: ${namespace}`, - namespace, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -app.post("/invalidate", async (c) => { - const body = await c.req.json(); - const { pattern, namespace } = body; - if (!pattern) { - return c.json({ - success: false, - error: "Pattern is required" - }, 400); - } - let totalInvalidated = 0; - if (namespace) { - const config = CACHE_CONFIGS[namespace]; - if (!config) { - return c.json({ - success: false, - error: `Unknown namespace: ${namespace}` - }, 404); - } - const cache = getCacheService(config); - totalInvalidated = await cache.invalidate(pattern); - } else { - for (const config of Object.values(CACHE_CONFIGS)) { - const cache = getCacheService(config); - totalInvalidated += await cache.invalidate(pattern); - } - } - return c.json({ - success: true, - invalidated: totalInvalidated, - pattern, - namespace: namespace || "all", - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -app.get("/health", async (c) => { - const stats = getAllCacheStats(); - const namespaces = Object.entries(stats); - const healthChecks = namespaces.map(([name, stat]) => { - const hitRate = stat.hitRate; - const memoryUsage = stat.memorySize / (50 * 1024 * 1024); - return { - namespace: name, - status: hitRate > 70 ? "healthy" : hitRate > 40 ? "warning" : "unhealthy", - hitRate, - memoryUsage: (memoryUsage * 100).toFixed(2) + "%", - entryCount: stat.entryCount - }; - }); - const overallStatus = healthChecks.every((h) => h.status === "healthy") ? "healthy" : healthChecks.some((h) => h.status === "unhealthy") ? "unhealthy" : "warning"; - return c.json({ - success: true, - data: { - status: overallStatus, - namespaces: healthChecks, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - } - }); -}); -app.get("/browser", async (c) => { - const namespace = c.req.query("namespace") || "all"; - const search = c.req.query("search") || ""; - const sortBy = c.req.query("sort") || "age"; - const limit = parseInt(c.req.query("limit") || "100"); - const entries = []; - const namespaces = namespace === "all" ? Object.keys(CACHE_CONFIGS) : [namespace]; - for (const ns of namespaces) { - const config = CACHE_CONFIGS[ns]; - if (!config) continue; - const cache = getCacheService(config); - const keys = await cache.listKeys(); - for (const keyInfo of keys) { - if (search && !keyInfo.key.toLowerCase().includes(search.toLowerCase())) { - continue; - } - const parsed = parseCacheKey(keyInfo.key); - const ttl = Math.max(0, keyInfo.expiresAt - Date.now()) / 1e3; - entries.push({ - namespace: ns, - key: keyInfo.key, - size: keyInfo.size, - age: keyInfo.age, - ttl, - expiresAt: keyInfo.expiresAt, - parsed - }); - } - } - if (sortBy === "size") { - entries.sort((a, b) => b.size - a.size); - } else if (sortBy === "age") { - entries.sort((a, b) => a.age - b.age); - } else if (sortBy === "key") { - entries.sort((a, b) => a.key.localeCompare(b.key)); - } - const limitedEntries = entries.slice(0, limit); - return c.json({ - success: true, - data: { - entries: limitedEntries, - total: entries.length, - showing: limitedEntries.length, - namespace, - search, - sortBy - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -app.get("/browser/:namespace/:key", async (c) => { - const namespace = c.req.param("namespace"); - const key = decodeURIComponent(c.req.param("key")); - const config = CACHE_CONFIGS[namespace]; - if (!config) { - return c.json({ - success: false, - error: `Unknown namespace: ${namespace}` - }, 404); - } - const cache = getCacheService(config); - const entry = await cache.getEntry(key); - if (!entry) { - return c.json({ - success: false, - error: "Cache entry not found or expired" - }, 404); - } - const parsed = parseCacheKey(key); - return c.json({ - success: true, - data: { - key, - namespace, - parsed, - ...entry, - createdAt: new Date(entry.timestamp).toISOString(), - expiresAt: new Date(entry.expiresAt).toISOString() - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -app.get("/analytics", async (c) => { - const stats = getAllCacheStats(); - const invalidationStats = getCacheInvalidationStats(); - const recentInvalidations = getRecentInvalidations(20); - let totalHits = 0; - let totalMisses = 0; - let totalSize = 0; - let totalEntries = 0; - const namespacesAnalytics = []; - for (const [namespace, stat] of Object.entries(stats)) { - totalHits += stat.memoryHits + stat.kvHits; - totalMisses += stat.memoryMisses + stat.kvMisses; - totalSize += stat.memorySize; - totalEntries += stat.entryCount; - const totalRequests2 = stat.memoryHits + stat.kvHits + stat.memoryMisses + stat.kvMisses; - const hitRate = totalRequests2 > 0 ? (stat.memoryHits + stat.kvHits) / totalRequests2 * 100 : 0; - const avgEntrySize = stat.entryCount > 0 ? stat.memorySize / stat.entryCount : 0; - namespacesAnalytics.push({ - namespace, - hitRate: hitRate.toFixed(2), - totalRequests: totalRequests2, - memoryHitRate: totalRequests2 > 0 ? (stat.memoryHits / totalRequests2 * 100).toFixed(2) : "0", - kvHitRate: totalRequests2 > 0 ? (stat.kvHits / totalRequests2 * 100).toFixed(2) : "0", - avgEntrySize: Math.round(avgEntrySize), - totalSize: stat.memorySize, - entryCount: stat.entryCount, - efficiency: totalRequests2 > 0 ? ((stat.memoryHits + stat.kvHits) / (stat.memoryHits + stat.kvHits + stat.dbHits + 1)).toFixed(2) : "0" - }); - } - namespacesAnalytics.sort((a, b) => parseFloat(b.hitRate) - parseFloat(a.hitRate)); - const totalRequests = totalHits + totalMisses; - const overallHitRate = totalRequests > 0 ? totalHits / totalRequests * 100 : 0; - const dbQueriesAvoided = totalHits; - const timeSaved = dbQueriesAvoided * 48; - const estimatedCostSavings = dbQueriesAvoided / 1e6 * 0.5; - return c.json({ - success: true, - data: { - overview: { - totalHits, - totalMisses, - totalRequests, - overallHitRate: overallHitRate.toFixed(2), - totalSize, - totalEntries, - avgEntrySize: totalEntries > 0 ? Math.round(totalSize / totalEntries) : 0 - }, - performance: { - dbQueriesAvoided, - timeSavedMs: timeSaved, - timeSavedMinutes: (timeSaved / 1e3 / 60).toFixed(2), - estimatedCostSavings: estimatedCostSavings.toFixed(4) - }, - namespaces: namespacesAnalytics, - invalidation: { - ...invalidationStats, - recent: recentInvalidations - } - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -app.get("/analytics/trends", async (c) => { - const stats = getAllCacheStats(); - const dataPoint = { - timestamp: Date.now(), - stats: Object.entries(stats).map(([namespace, stat]) => ({ - namespace, - hitRate: stat.hitRate, - entryCount: stat.entryCount, - memorySize: stat.memorySize, - totalRequests: stat.totalRequests - })) - }; - return c.json({ - success: true, - data: { - trends: [dataPoint], - note: "Historical trends require persistent storage. This returns current snapshot only." - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -app.get("/analytics/top-keys", async (c) => { - c.req.query("namespace") || "all"; - parseInt(c.req.query("limit") || "10"); - return c.json({ - success: true, - data: { - topKeys: [], - note: "Top keys tracking requires per-key hit counting. Feature not yet implemented." - }, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); -}); -app.post("/warm", async (c) => { - try { - const db = c.env.DB; - const result = await warmCommonCaches(db); - return c.json({ - success: true, - message: "Cache warming completed", - ...result, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } catch (error) { - console.error("Cache warming error:", error); - return c.json({ - success: false, - error: "Cache warming failed", - details: error instanceof Error ? error.message : "Unknown error" - }, 500); - } -}); -app.post("/warm/:namespace", async (c) => { - try { - const namespace = c.req.param("namespace"); - const body = await c.req.json(); - const { entries } = body; - if (!entries || !Array.isArray(entries)) { - return c.json({ - success: false, - error: "Entries array is required" - }, 400); - } - const count = await warmNamespace(namespace, entries); - return c.json({ - success: true, - message: `Warmed ${count} entries in namespace: ${namespace}`, - namespace, - count, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } catch (error) { - console.error("Namespace warming error:", error); - return c.json({ - success: false, - error: "Namespace warming failed", - details: error instanceof Error ? error.message : "Unknown error" - }, 500); - } -}); -var routes_default = app; - -// src/plugins/cache/index.ts -var CachePlugin = class { - _context = null; - /** - * Get plugin routes - */ - getRoutes() { - return routes_default; - } - /** - * Activate the cache plugin - */ - async activate(context) { - this._context = context; - const settings = context.config || {}; - console.log("\u2705 Cache plugin activated", { - memoryEnabled: settings.memoryEnabled ?? true, - kvEnabled: settings.kvEnabled ?? false, - defaultTTL: settings.defaultTTL ?? 3600 - }); - for (const [_namespace, config] of Object.entries(CACHE_CONFIGS)) { - getCacheService({ - ...config, - memoryEnabled: settings.memoryEnabled ?? config.memoryEnabled, - kvEnabled: settings.kvEnabled ?? config.kvEnabled, - ttl: settings.defaultTTL ?? config.ttl - }); - } - setupCacheInvalidation(); - } - /** - * Deactivate the cache plugin - */ - async deactivate() { - console.log("\u274C Cache plugin deactivated - clearing all caches"); - await clearAllCaches(); - this._context = null; - } - /** - * Configure the cache plugin - */ - async configure(settings) { - console.log("\u2699\uFE0F Cache plugin configured", settings); - for (const [_namespace, config] of Object.entries(CACHE_CONFIGS)) { - getCacheService({ - ...config, - memoryEnabled: settings.memoryEnabled ?? config.memoryEnabled, - kvEnabled: settings.kvEnabled ?? config.kvEnabled, - ttl: settings.defaultTTL ?? config.ttl - }); - } - } - /** - * Get cache statistics - */ - async getStats(c) { - const stats = getAllCacheStats(); - return c.json({ - success: true, - data: stats, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } - /** - * Clear all cache entries - */ - async clearCache(c) { - await clearAllCaches(); - return c.json({ - success: true, - message: "All cache entries cleared", - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } - /** - * Invalidate cache entries matching pattern - */ - async invalidatePattern(c) { - const body = await c.req.json(); - const { pattern, namespace: _namespace } = body; - if (!pattern) { - return c.json({ - success: false, - error: "Pattern is required" - }, 400); - } - let totalInvalidated = 0; - if (_namespace) { - const cache = getCacheService(CACHE_CONFIGS[_namespace] || { - ttl: 3600, - kvEnabled: false, - memoryEnabled: true, - namespace: _namespace, - invalidateOn: [], - version: "v1" - }); - totalInvalidated = await cache.invalidate(pattern); - } else { - for (const config of Object.values(CACHE_CONFIGS)) { - const cache = getCacheService(config); - totalInvalidated += await cache.invalidate(pattern); - } - } - return c.json({ - success: true, - invalidated: totalInvalidated, - pattern, - namespace: _namespace || "all", - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - } -}; -var plugin = new CachePlugin(); -var cache_default = plugin; - -// src/assets/favicon.ts -var faviconSvg = ` - - - - - - - -`; - -// src/app.ts -function createSonicJSApp(config = {}) { - const app2 = new hono.Hono(); - const appVersion = config.version || chunk5HMR2SJW_cjs.getCoreVersion(); - const appName = config.name || "SonicJS AI"; - app2.use("*", async (c, next) => { - c.set("appVersion", appVersion); - await next(); - }); - app2.use("*", chunkDVQA5II3_cjs.metricsMiddleware()); - app2.use("*", chunkDVQA5II3_cjs.bootstrapMiddleware(config)); - if (config.middleware?.beforeAuth) { - for (const middleware of config.middleware.beforeAuth) { - app2.use("*", middleware); - } - } - app2.use("*", async (_c, next) => { - await next(); - }); - app2.use("*", async (_c, next) => { - await next(); - }); - if (config.middleware?.afterAuth) { - for (const middleware of config.middleware.afterAuth) { - app2.use("*", middleware); - } - } - app2.route("/api", chunkVAPDSKKV_cjs.api_default); - app2.route("/api/media", chunkVAPDSKKV_cjs.api_media_default); - app2.route("/api/system", chunkVAPDSKKV_cjs.api_system_default); - app2.route("/admin/api", chunkVAPDSKKV_cjs.admin_api_default); - app2.route("/admin/dashboard", chunkVAPDSKKV_cjs.router); - app2.route("/admin/collections", chunkVAPDSKKV_cjs.adminCollectionsRoutes); - app2.route("/admin/forms", chunkVAPDSKKV_cjs.adminFormsRoutes); - app2.route("/admin/settings", chunkVAPDSKKV_cjs.adminSettingsRoutes); - app2.route("/forms", chunkVAPDSKKV_cjs.public_forms_default); - app2.route("/api/forms", chunkVAPDSKKV_cjs.public_forms_default); - app2.route("/admin/api-reference", chunkVAPDSKKV_cjs.router2); - app2.route("/admin/database-tools", createDatabaseToolsAdminRoutes()); - app2.route("/admin/seed-data", createSeedDataAdminRoutes()); - app2.route("/admin/content", chunkVAPDSKKV_cjs.admin_content_default); - app2.route("/admin/media", chunkVAPDSKKV_cjs.adminMediaRoutes); - if (aiSearchPlugin.routes && aiSearchPlugin.routes.length > 0) { - for (const route of aiSearchPlugin.routes) { - app2.route(route.path, route.handler); - } - } - app2.route("/admin/cache", cache_default.getRoutes()); - if (otpLoginPlugin.routes && otpLoginPlugin.routes.length > 0) { - for (const route of otpLoginPlugin.routes) { - app2.route(route.path, route.handler); - } - } - app2.route("/admin/plugins", chunkVAPDSKKV_cjs.adminPluginRoutes); - app2.route("/admin/logs", chunkVAPDSKKV_cjs.adminLogsRoutes); - app2.route("/admin", chunkVAPDSKKV_cjs.userRoutes); - app2.route("/auth", chunkVAPDSKKV_cjs.auth_default); - app2.route("/", chunkVAPDSKKV_cjs.test_cleanup_default); - if (emailPlugin.routes && emailPlugin.routes.length > 0) { - for (const route of emailPlugin.routes) { - app2.route(route.path, route.handler); - } - } - const magicLinkPlugin = createMagicLinkAuthPlugin(); - if (magicLinkPlugin.routes && magicLinkPlugin.routes.length > 0) { - for (const route of magicLinkPlugin.routes) { - app2.route(route.path, route.handler); - } - } - app2.get("/favicon.svg", (c) => { - return new Response(faviconSvg, { - headers: { - "Content-Type": "image/svg+xml", - "Cache-Control": "public, max-age=31536000" - } - }); - }); - app2.get("/files/*", async (c) => { - try { - const url = new URL(c.req.url); - const pathname = url.pathname; - const objectKey = pathname.replace(/^\/files\//, ""); - if (!objectKey) { - return c.notFound(); - } - const object = await c.env.MEDIA_BUCKET.get(objectKey); - if (!object) { - return c.notFound(); - } - const headers = new Headers(); - object.httpMetadata?.contentType && headers.set("Content-Type", object.httpMetadata.contentType); - object.httpMetadata?.contentDisposition && headers.set("Content-Disposition", object.httpMetadata.contentDisposition); - headers.set("Cache-Control", "public, max-age=31536000"); - headers.set("Access-Control-Allow-Origin", "*"); - headers.set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS"); - headers.set("Access-Control-Allow-Headers", "Content-Type"); - return new Response(object.body, { - headers - }); - } catch (error) { - console.error("Error serving file:", error); - return c.notFound(); - } - }); - if (config.routes) { - for (const route of config.routes) { - app2.route(route.path, route.handler); - } - } - app2.get("/", (c) => { - return c.redirect("/auth/login"); - }); - app2.get("/health", (c) => { - return c.json({ - name: appName, - version: appVersion, - status: "running", - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }); - }); - app2.notFound((c) => { - return c.json({ error: "Not Found", status: 404 }, 404); - }); - app2.onError((err, c) => { - console.error(err); - return c.json({ error: "Internal Server Error", status: 500 }, 500); - }); - return app2; -} -function setupCoreMiddleware(_app) { - console.warn("setupCoreMiddleware is deprecated. Use createSonicJSApp() instead."); -} -function setupCoreRoutes(_app) { - console.warn("setupCoreRoutes is deprecated. Use createSonicJSApp() instead."); -} -function createDb(d1$1) { - return d1.drizzle(d1$1, { schema: chunkVNLR35GO_cjs.schema_exports }); -} - -// src/index.ts -var VERSION = chunk5HMR2SJW_cjs.package_default.version; - -Object.defineProperty(exports, "ROUTES_INFO", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.ROUTES_INFO; } -}); -Object.defineProperty(exports, "adminApiRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.admin_api_default; } -}); -Object.defineProperty(exports, "adminCheckboxRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminCheckboxRoutes; } -}); -Object.defineProperty(exports, "adminCodeExamplesRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.admin_code_examples_default; } -}); -Object.defineProperty(exports, "adminCollectionsRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminCollectionsRoutes; } -}); -Object.defineProperty(exports, "adminContentRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.admin_content_default; } -}); -Object.defineProperty(exports, "adminDashboardRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.router; } -}); -Object.defineProperty(exports, "adminDesignRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminDesignRoutes; } -}); -Object.defineProperty(exports, "adminLogsRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminLogsRoutes; } -}); -Object.defineProperty(exports, "adminMediaRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminMediaRoutes; } -}); -Object.defineProperty(exports, "adminPluginRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminPluginRoutes; } -}); -Object.defineProperty(exports, "adminSettingsRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminSettingsRoutes; } -}); -Object.defineProperty(exports, "adminTestimonialsRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.admin_testimonials_default; } -}); -Object.defineProperty(exports, "adminUsersRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.userRoutes; } -}); -Object.defineProperty(exports, "apiContentCrudRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.api_content_crud_default; } -}); -Object.defineProperty(exports, "apiMediaRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.api_media_default; } -}); -Object.defineProperty(exports, "apiRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.api_default; } -}); -Object.defineProperty(exports, "apiSystemRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.api_system_default; } -}); -Object.defineProperty(exports, "authRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.auth_default; } -}); -Object.defineProperty(exports, "Logger", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.Logger; } -}); -Object.defineProperty(exports, "apiTokens", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.apiTokens; } -}); -Object.defineProperty(exports, "collections", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.collections; } -}); -Object.defineProperty(exports, "content", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.content; } -}); -Object.defineProperty(exports, "contentVersions", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.contentVersions; } -}); -Object.defineProperty(exports, "getLogger", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.getLogger; } -}); -Object.defineProperty(exports, "initLogger", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.initLogger; } -}); -Object.defineProperty(exports, "insertCollectionSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertCollectionSchema; } -}); -Object.defineProperty(exports, "insertContentSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertContentSchema; } -}); -Object.defineProperty(exports, "insertLogConfigSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertLogConfigSchema; } -}); -Object.defineProperty(exports, "insertMediaSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertMediaSchema; } -}); -Object.defineProperty(exports, "insertPluginActivityLogSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertPluginActivityLogSchema; } -}); -Object.defineProperty(exports, "insertPluginAssetSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertPluginAssetSchema; } -}); -Object.defineProperty(exports, "insertPluginHookSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertPluginHookSchema; } -}); -Object.defineProperty(exports, "insertPluginRouteSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertPluginRouteSchema; } -}); -Object.defineProperty(exports, "insertPluginSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertPluginSchema; } -}); -Object.defineProperty(exports, "insertSystemLogSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertSystemLogSchema; } -}); -Object.defineProperty(exports, "insertUserSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertUserSchema; } -}); -Object.defineProperty(exports, "insertWorkflowHistorySchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.insertWorkflowHistorySchema; } -}); -Object.defineProperty(exports, "logConfig", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.logConfig; } -}); -Object.defineProperty(exports, "media", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.media; } -}); -Object.defineProperty(exports, "pluginActivityLog", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.pluginActivityLog; } -}); -Object.defineProperty(exports, "pluginAssets", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.pluginAssets; } -}); -Object.defineProperty(exports, "pluginHooks", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.pluginHooks; } -}); -Object.defineProperty(exports, "pluginRoutes", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.pluginRoutes; } -}); -Object.defineProperty(exports, "plugins", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.plugins; } -}); -Object.defineProperty(exports, "selectCollectionSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectCollectionSchema; } -}); -Object.defineProperty(exports, "selectContentSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectContentSchema; } -}); -Object.defineProperty(exports, "selectLogConfigSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectLogConfigSchema; } -}); -Object.defineProperty(exports, "selectMediaSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectMediaSchema; } -}); -Object.defineProperty(exports, "selectPluginActivityLogSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectPluginActivityLogSchema; } -}); -Object.defineProperty(exports, "selectPluginAssetSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectPluginAssetSchema; } -}); -Object.defineProperty(exports, "selectPluginHookSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectPluginHookSchema; } -}); -Object.defineProperty(exports, "selectPluginRouteSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectPluginRouteSchema; } -}); -Object.defineProperty(exports, "selectPluginSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectPluginSchema; } -}); -Object.defineProperty(exports, "selectSystemLogSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectSystemLogSchema; } -}); -Object.defineProperty(exports, "selectUserSchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectUserSchema; } -}); -Object.defineProperty(exports, "selectWorkflowHistorySchema", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.selectWorkflowHistorySchema; } -}); -Object.defineProperty(exports, "systemLogs", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.systemLogs; } -}); -Object.defineProperty(exports, "users", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.users; } -}); -Object.defineProperty(exports, "workflowHistory", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.workflowHistory; } -}); -Object.defineProperty(exports, "AuthManager", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.AuthManager; } -}); -Object.defineProperty(exports, "PermissionManager", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.PermissionManager; } -}); -Object.defineProperty(exports, "bootstrapMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.bootstrapMiddleware; } -}); -Object.defineProperty(exports, "cacheHeaders", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.cacheHeaders; } -}); -Object.defineProperty(exports, "compressionMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.compressionMiddleware; } -}); -Object.defineProperty(exports, "detailedLoggingMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.detailedLoggingMiddleware; } -}); -Object.defineProperty(exports, "getActivePlugins", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.getActivePlugins; } -}); -Object.defineProperty(exports, "isPluginActive", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.isPluginActive; } -}); -Object.defineProperty(exports, "logActivity", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.logActivity; } -}); -Object.defineProperty(exports, "loggingMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.loggingMiddleware; } -}); -Object.defineProperty(exports, "optionalAuth", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.optionalAuth; } -}); -Object.defineProperty(exports, "performanceLoggingMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.performanceLoggingMiddleware; } -}); -Object.defineProperty(exports, "requireActivePlugin", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requireActivePlugin; } -}); -Object.defineProperty(exports, "requireActivePlugins", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requireActivePlugins; } -}); -Object.defineProperty(exports, "requireAnyPermission", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requireAnyPermission; } -}); -Object.defineProperty(exports, "requireAuth", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requireAuth; } -}); -Object.defineProperty(exports, "requirePermission", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requirePermission; } -}); -Object.defineProperty(exports, "requireRole", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requireRole; } -}); -Object.defineProperty(exports, "securityHeaders", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.securityHeaders; } -}); -Object.defineProperty(exports, "securityLoggingMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.securityLoggingMiddleware; } -}); -Object.defineProperty(exports, "PluginBootstrapService", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.PluginBootstrapService; } -}); -Object.defineProperty(exports, "PluginServiceClass", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.PluginService; } -}); -Object.defineProperty(exports, "cleanupRemovedCollections", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.cleanupRemovedCollections; } -}); -Object.defineProperty(exports, "fullCollectionSync", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.fullCollectionSync; } -}); -Object.defineProperty(exports, "getAvailableCollectionNames", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.getAvailableCollectionNames; } -}); -Object.defineProperty(exports, "getManagedCollections", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.getManagedCollections; } -}); -Object.defineProperty(exports, "isCollectionManaged", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.isCollectionManaged; } -}); -Object.defineProperty(exports, "loadCollectionConfig", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.loadCollectionConfig; } -}); -Object.defineProperty(exports, "loadCollectionConfigs", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.loadCollectionConfigs; } -}); -Object.defineProperty(exports, "registerCollections", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.registerCollections; } -}); -Object.defineProperty(exports, "syncCollection", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.syncCollection; } -}); -Object.defineProperty(exports, "syncCollections", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.syncCollections; } -}); -Object.defineProperty(exports, "validateCollectionConfig", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.validateCollectionConfig; } -}); -Object.defineProperty(exports, "MigrationService", { - enumerable: true, - get: function () { return chunkFQSMNIY2_cjs.MigrationService; } -}); -Object.defineProperty(exports, "renderFilterBar", { - enumerable: true, - get: function () { return chunkS6K2H2TS_cjs.renderFilterBar; } -}); -Object.defineProperty(exports, "getConfirmationDialogScript", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.getConfirmationDialogScript; } -}); -Object.defineProperty(exports, "renderAlert", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderAlert; } -}); -Object.defineProperty(exports, "renderConfirmationDialog", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderConfirmationDialog; } -}); -Object.defineProperty(exports, "renderForm", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderForm; } -}); -Object.defineProperty(exports, "renderFormField", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderFormField; } -}); -Object.defineProperty(exports, "renderPagination", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderPagination; } -}); -Object.defineProperty(exports, "renderTable", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderTable; } -}); -Object.defineProperty(exports, "HookSystemImpl", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.HookSystemImpl; } -}); -Object.defineProperty(exports, "HookUtils", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.HookUtils; } -}); -Object.defineProperty(exports, "PluginManagerClass", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.PluginManager; } -}); -Object.defineProperty(exports, "PluginRegistryImpl", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.PluginRegistryImpl; } -}); -Object.defineProperty(exports, "PluginValidatorClass", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.PluginValidator; } -}); -Object.defineProperty(exports, "ScopedHookSystemClass", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.ScopedHookSystem; } -}); -Object.defineProperty(exports, "PluginBuilder", { - enumerable: true, - get: function () { return chunk6FHNRRJ3_cjs.PluginBuilder; } -}); -Object.defineProperty(exports, "PluginHelpers", { - enumerable: true, - get: function () { return chunk6FHNRRJ3_cjs.PluginHelpers; } -}); -Object.defineProperty(exports, "QueryFilterBuilder", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.QueryFilterBuilder; } -}); -Object.defineProperty(exports, "SONICJS_VERSION", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.SONICJS_VERSION; } -}); -Object.defineProperty(exports, "TemplateRenderer", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.TemplateRenderer; } -}); -Object.defineProperty(exports, "buildQuery", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.buildQuery; } -}); -Object.defineProperty(exports, "escapeHtml", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.escapeHtml; } -}); -Object.defineProperty(exports, "getCoreVersion", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.getCoreVersion; } -}); -Object.defineProperty(exports, "renderTemplate", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.renderTemplate; } -}); -Object.defineProperty(exports, "sanitizeInput", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.sanitizeInput; } -}); -Object.defineProperty(exports, "sanitizeObject", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.sanitizeObject; } -}); -Object.defineProperty(exports, "templateRenderer", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.templateRenderer; } -}); -Object.defineProperty(exports, "metricsTracker", { - enumerable: true, - get: function () { return chunkRCQ2HIQD_cjs.metricsTracker; } -}); -Object.defineProperty(exports, "HOOKS", { - enumerable: true, - get: function () { return chunkKYGRJCZM_cjs.HOOKS; } -}); -exports.VERSION = VERSION; -exports.createDb = createDb; -exports.createSonicJSApp = createSonicJSApp; -exports.setupCoreMiddleware = setupCoreMiddleware; -exports.setupCoreRoutes = setupCoreRoutes; -//# sourceMappingURL=index.cjs.map -//# sourceMappingURL=index.cjs.map \ No newline at end of file diff --git a/packages/core/dist/index.d.cts b/packages/core/dist/index.d.cts deleted file mode 100644 index 9ecfd94e8..000000000 --- a/packages/core/dist/index.d.cts +++ /dev/null @@ -1,539 +0,0 @@ -export { B as Bindings, b as SonicJSApp, S as SonicJSConfig, V as Variables, c as createSonicJSApp, s as setupCoreMiddleware, a as setupCoreRoutes } from './app-CYEm1ytG.cjs'; -import { t as schema } from './plugin-bootstrap-DKB5f8-E.cjs'; -export { ab as Collection, ad as Content, C as CorePlugin, aj as DbPlugin, al as DbPluginHook, n as LogCategory, av as LogConfig, o as LogEntry, p as LogFilter, m as LogLevel, L as Logger, af as Media, e as Migration, M as MigrationService, h as MigrationStatus, ac as NewCollection, ae as NewContent, aw as NewLogConfig, ag as NewMedia, ak as NewPlugin, as as NewPluginActivityLog, aq as NewPluginAsset, am as NewPluginHook, ao as NewPluginRoute, au as NewSystemLog, aa as NewUser, ai as NewWorkflowHistory, ar as PluginActivityLog, ap as PluginAsset, q as PluginBootstrapService, an as PluginRoute, P as PluginServiceClass, at as SystemLog, a9 as User, ah as WorkflowHistory, A as apiTokens, d as cleanupRemovedCollections, w as collections, x as content, y as contentVersions, f as fullCollectionSync, g as getAvailableCollectionNames, j as getLogger, c as getManagedCollections, k as initLogger, O as insertCollectionSchema, R as insertContentSchema, a7 as insertLogConfigSchema, T as insertMediaSchema, a3 as insertPluginActivityLogSchema, a1 as insertPluginAssetSchema, Z as insertPluginHookSchema, $ as insertPluginRouteSchema, X as insertPluginSchema, a5 as insertSystemLogSchema, K as insertUserSchema, V as insertWorkflowHistorySchema, i as isCollectionManaged, a as loadCollectionConfig, l as loadCollectionConfigs, J as logConfig, z as media, H as pluginActivityLog, G as pluginAssets, E as pluginHooks, F as pluginRoutes, D as plugins, r as registerCollections, Q as selectCollectionSchema, S as selectContentSchema, a8 as selectLogConfigSchema, U as selectMediaSchema, a4 as selectPluginActivityLogSchema, a2 as selectPluginAssetSchema, _ as selectPluginHookSchema, a0 as selectPluginRouteSchema, Y as selectPluginSchema, a6 as selectSystemLogSchema, N as selectUserSchema, W as selectWorkflowHistorySchema, b as syncCollection, s as syncCollections, I as systemLogs, u as users, v as validateCollectionConfig, B as workflowHistory } from './plugin-bootstrap-DKB5f8-E.cjs'; -export { AuthManager, Permission, PermissionManager, UserPermissions, bootstrapMiddleware, cacheHeaders, compressionMiddleware, detailedLoggingMiddleware, getActivePlugins, isPluginActive, logActivity, loggingMiddleware, optionalAuth, performanceLoggingMiddleware, requireActivePlugin, requireActivePlugins, requireAnyPermission, requireAuth, requirePermission, requireRole, securityHeaders, securityLoggingMiddleware } from './middleware.cjs'; -export { H as HookSystemImpl, a as HookUtils, b as PluginManagerClass, P as PluginRegistryImpl, c as PluginValidatorClass, S as ScopedHookSystemClass } from './plugin-manager-vBal9Zip.cjs'; -export { ROUTES_INFO, adminApiRoutes, adminCheckboxRoutes, adminCodeExamplesRoutes, adminCollectionsRoutes, adminContentRoutes, adminDashboardRoutes, adminDesignRoutes, adminLogsRoutes, adminMediaRoutes, adminPluginRoutes, adminSettingsRoutes, adminTestimonialsRoutes, adminUsersRoutes, apiContentCrudRoutes, apiMediaRoutes, apiRoutes, apiSystemRoutes, authRoutes } from './routes.cjs'; -export { A as AlertData, C as ConfirmationDialogOptions, k as Filter, j as FilterBarData, l as FilterOption, h as FormData, F as FormField, P as PaginationData, T as TableColumn, i as TableData, g as getConfirmationDialogScript, d as renderAlert, e as renderConfirmationDialog, f as renderFilterBar, r as renderForm, a as renderFormField, c as renderPagination, b as renderTable } from './filter-bar.template-By4jeiw_.cjs'; -export { c as CollectionConfig, d as CollectionConfigModule, C as CollectionSchema, e as CollectionSyncResult, a as FieldConfig, F as FieldType } from './collection-config-BF95LgQb.cjs'; -export { A as AuthService, C as ContentService, v as HOOKS, k as HookContext, H as HookHandler, u as HookName, l as HookSystem, p as MediaService, P as Plugin, g as PluginAdminPage, r as PluginBuilderOptions, h as PluginComponent, b as PluginConfig, a as PluginContext, j as PluginHook, q as PluginLogger, n as PluginManager, i as PluginMenuItem, d as PluginMiddleware, e as PluginModel, m as PluginRegistry, c as PluginRoutes, f as PluginService, o as PluginStatus, t as PluginValidationResult, s as PluginValidator, S as ScopedHookSystem } from './plugin-zvZpaiP5.cjs'; -export { P as PluginManifest } from './plugin-manifest-Dpy8wxIB.cjs'; -export { c as FilterCondition, d as FilterGroup, F as FilterOperator, f as QueryFilter, Q as QueryFilterBuilder, h as QueryResult, S as SONICJS_VERSION, T as TemplateRenderer, b as buildQuery, e as escapeHtml, g as getCoreVersion, m as metricsTracker, r as renderTemplate, s as sanitizeInput, a as sanitizeObject, t as templateRenderer } from './version-vktVAxhe.cjs'; -import * as drizzle_orm_d1 from 'drizzle-orm/d1'; -import { Hono, MiddlewareHandler, Context } from 'hono'; -import { z } from 'zod'; -import { D1Database as D1Database$1, KVNamespace, R2Bucket } from '@cloudflare/workers-types'; -import 'drizzle-zod'; -import 'drizzle-orm/sqlite-core'; -import 'hono/types'; - -/** - * SonicJS Plugin System Types - * - * Defines the core interfaces and types for the plugin system - */ - -interface Plugin { - /** Unique plugin identifier */ - name: string; - /** Plugin version (semantic versioning) */ - version: string; - /** Human-readable description */ - description?: string; - /** Plugin author information */ - author?: { - name: string; - email?: string; - url?: string; - }; - /** Plugin dependencies (other plugins required) */ - dependencies?: string[]; - /** SonicJS version compatibility */ - compatibility?: string; - /** Plugin license */ - license?: string; - routes?: PluginRoutes[]; - middleware?: PluginMiddleware[]; - models?: PluginModel[]; - services?: PluginService[]; - adminPages?: PluginAdminPage[]; - adminComponents?: PluginComponent[]; - menuItems?: PluginMenuItem[]; - hooks?: PluginHook[]; - install?: (context: PluginContext) => Promise; - uninstall?: (context: PluginContext) => Promise; - activate?: (context: PluginContext) => Promise; - deactivate?: (context: PluginContext) => Promise; - configure?: (config: PluginConfig) => Promise; -} -interface PluginContext { - /** Database instance */ - db: D1Database$1; - /** Key-value storage */ - kv: KVNamespace; - /** R2 storage bucket */ - r2?: R2Bucket; - /** Plugin configuration */ - config: PluginConfig; - /** Core SonicJS services */ - services: { - auth: AuthService; - content: ContentService; - media: MediaService; - }; - /** Hook system for inter-plugin communication */ - hooks: HookSystem | ScopedHookSystem; - /** Logging utilities */ - logger: PluginLogger; -} -interface PluginConfig { - /** Plugin-specific configuration */ - [key: string]: any; - /** Whether plugin is enabled */ - enabled: boolean; - /** Plugin installation timestamp */ - installedAt?: number; - /** Plugin last update timestamp */ - updatedAt?: number; -} -interface PluginRoutes { - /** Route path prefix */ - path: string; - /** Hono route handler */ - handler: Hono; - /** Route description */ - description?: string; - /** Whether route requires authentication */ - requiresAuth?: boolean; - /** Required roles for access */ - roles?: string[]; - /** Route priority (for ordering) */ - priority?: number; -} -interface PluginMiddleware { - /** Middleware name */ - name: string; - /** Middleware handler function */ - handler: MiddlewareHandler; - /** Middleware description */ - description?: string; - /** Middleware priority (lower = earlier) */ - priority?: number; - /** Routes to apply middleware to */ - routes?: string[]; - /** Whether to apply globally */ - global?: boolean; -} -interface PluginModel { - /** Model name */ - name: string; - /** Database table name */ - tableName: string; - /** Zod schema for validation */ - schema: z.ZodSchema; - /** Database migrations */ - migrations: string[]; - /** Model relationships */ - relationships?: ModelRelationship[]; - /** Whether model extends core content */ - extendsContent?: boolean; -} -interface ModelRelationship { - type: 'oneToOne' | 'oneToMany' | 'manyToMany'; - target: string; - foreignKey?: string; - joinTable?: string; -} -interface PluginService { - /** Service name */ - name: string; - /** Service implementation */ - implementation: any; - /** Service description */ - description?: string; - /** Service dependencies */ - dependencies?: string[]; - /** Whether service is singleton */ - singleton?: boolean; -} -interface PluginAdminPage { - /** Page path (relative to /admin) */ - path: string; - /** Page title */ - title: string; - /** Page component/template */ - component: string; - /** Page description */ - description?: string; - /** Required permissions */ - permissions?: string[]; - /** Menu item configuration */ - menuItem?: PluginMenuItem; - /** Page icon */ - icon?: string; -} -interface PluginComponent { - /** Component name */ - name: string; - /** Component template function */ - template: (props: any) => string; - /** Component description */ - description?: string; - /** Component props schema */ - propsSchema?: z.ZodSchema; -} -interface PluginMenuItem { - /** Menu item label */ - label: string; - /** Menu item path */ - path: string; - /** Menu item icon */ - icon?: string; - /** Menu item order */ - order?: number; - /** Parent menu item */ - parent?: string; - /** Required permissions */ - permissions?: string[]; - /** Whether item is active */ - active?: boolean; -} -interface PluginHook { - /** Hook name */ - name: string; - /** Hook handler function */ - handler: HookHandler; - /** Hook priority */ - priority?: number; - /** Hook description */ - description?: string; -} -type HookHandler = (data: any, context: HookContext) => Promise; -interface HookContext { - /** Plugin that registered the hook */ - plugin: string; - /** Hook execution context */ - context: PluginContext; - /** Cancel hook execution */ - cancel?: () => void; -} -interface HookSystem { - /** Register a hook handler */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** Execute all handlers for a hook */ - execute(hookName: string, data: any, context?: any): Promise; - /** Remove a hook handler */ - unregister(hookName: string, handler: HookHandler): void; - /** Get all registered hooks */ - getHooks(hookName: string): PluginHook[]; - /** Create a scoped hook system (optional) */ - createScope?(pluginName: string): ScopedHookSystem; -} -interface ScopedHookSystem { - /** Register a hook handler */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** Execute all handlers for a hook */ - execute(hookName: string, data: any, context?: any): Promise; - /** Remove a hook handler */ - unregister(hookName: string, handler: HookHandler): void; - /** Remove all hooks for this scope */ - unregisterAll(): void; -} -interface AuthService { - /** Generate JWT token for a user */ - generateToken(userId: string, email: string, role: string): Promise; - /** Verify and decode JWT token */ - verifyToken(token: string): Promise; - /** Set authentication cookie (useful for alternative auth methods) */ - setAuthCookie(context: Context, token: string, options?: { - maxAge?: number; - secure?: boolean; - httpOnly?: boolean; - sameSite?: 'Strict' | 'Lax' | 'None'; - }): void; - /** Hash password */ - hashPassword(password: string): Promise; - /** Verify password against hash */ - verifyPassword(password: string, hash: string): Promise; -} -interface AuthService { - /** Verify user permissions */ - hasPermission(userId: string, permission: string): Promise; - /** Get current user */ - getCurrentUser(context: Context): Promise; - /** Create authentication middleware */ - createMiddleware(options?: any): MiddlewareHandler; -} -interface ContentService { - /** Get content by ID */ - getById(id: string): Promise; - /** Create new content */ - create(data: any): Promise; - /** Update content */ - update(id: string, data: any): Promise; - /** Delete content */ - delete(id: string): Promise; - /** Search content */ - search(query: string, options?: any): Promise; -} -interface MediaService { - /** Upload file */ - upload(file: File, options?: any): Promise; - /** Get media by ID */ - getById(id: string): Promise; - /** Delete media */ - delete(id: string): Promise; - /** Transform image */ - transform(id: string, options: any): Promise; -} -interface PluginLogger { - debug(message: string, data?: any): void; - info(message: string, data?: any): void; - warn(message: string, data?: any): void; - error(message: string, error?: Error, data?: any): void; -} -interface PluginBuilderOptions { - name: string; - version: string; - description?: string; - author?: Plugin['author']; - dependencies?: string[]; -} - -declare function createDb(d1: D1Database): drizzle_orm_d1.DrizzleD1Database & { - $client: D1Database; -}; - -/** - * Plugin Builder SDK - * - * Provides a fluent API for building SonicJS plugins - * - * @packageDocumentation - */ - -/** - * Fluent builder for creating SonicJS plugins. - * - * @beta This API is in beta and may change in future releases. - * - * @example - * ```typescript - * import { PluginBuilder } from '@sonicjs-cms/core' - * - * const plugin = PluginBuilder.create({ - * name: 'my-plugin', - * version: '1.0.0', - * description: 'My custom plugin' - * }) - * .addRoute('/api/my-plugin', routes) - * .addHook('content:save', handler) - * .lifecycle({ activate: async () => console.log('Activated!') }) - * .build() - * ``` - */ -declare class PluginBuilder { - private plugin; - constructor(options: PluginBuilderOptions); - /** - * Create a new plugin builder - */ - static create(options: PluginBuilderOptions): PluginBuilder; - /** - * Add metadata to the plugin - */ - metadata(metadata: { - description?: string; - author?: Plugin['author']; - license?: string; - compatibility?: string; - dependencies?: string[]; - }): PluginBuilder; - /** - * Add routes to plugin - */ - addRoutes(routes: PluginRoutes[]): PluginBuilder; - /** - * Add a single route to plugin - */ - addRoute(path: string, handler: Hono, options?: { - description?: string; - requiresAuth?: boolean; - roles?: string[]; - priority?: number; - }): PluginBuilder; - /** - * Add middleware to plugin - */ - addMiddleware(middleware: PluginMiddleware[]): PluginBuilder; - /** - * Add a single middleware to plugin - */ - addSingleMiddleware(name: string, handler: any, options?: { - description?: string; - priority?: number; - routes?: string[]; - global?: boolean; - }): PluginBuilder; - /** - * Add models to plugin - */ - addModels(models: PluginModel[]): PluginBuilder; - /** - * Add a single model to plugin - */ - addModel(name: string, options: { - tableName: string; - schema: z.ZodSchema; - migrations: string[]; - relationships?: PluginModel['relationships']; - extendsContent?: boolean; - }): PluginBuilder; - /** - * Add services to plugin - */ - addServices(services: PluginService[]): PluginBuilder; - /** - * Add a single service to plugin - */ - addService(name: string, implementation: any, options?: { - description?: string; - dependencies?: string[]; - singleton?: boolean; - }): PluginBuilder; - /** - * Add admin pages to plugin - */ - addAdminPages(pages: PluginAdminPage[]): PluginBuilder; - /** - * Add a single admin page to plugin - */ - addAdminPage(path: string, title: string, component: string, options?: { - description?: string; - permissions?: string[]; - icon?: string; - menuItem?: PluginMenuItem; - }): PluginBuilder; - /** - * Add admin components to plugin - */ - addComponents(components: PluginComponent[]): PluginBuilder; - /** - * Add a single admin component to plugin - */ - addComponent(name: string, template: (props: any) => string, options?: { - description?: string; - propsSchema?: z.ZodSchema; - }): PluginBuilder; - /** - * Add menu items to plugin - */ - addMenuItems(items: PluginMenuItem[]): PluginBuilder; - /** - * Add a single menu item to plugin - */ - addMenuItem(label: string, path: string, options?: { - icon?: string; - order?: number; - parent?: string; - permissions?: string[]; - }): PluginBuilder; - /** - * Add hooks to plugin - */ - addHooks(hooks: PluginHook[]): PluginBuilder; - /** - * Add a single hook to plugin - */ - addHook(name: string, handler: any, options?: { - priority?: number; - description?: string; - }): PluginBuilder; - /** - * Add lifecycle hooks - */ - lifecycle(hooks: { - install?: Plugin['install']; - uninstall?: Plugin['uninstall']; - activate?: Plugin['activate']; - deactivate?: Plugin['deactivate']; - configure?: Plugin['configure']; - }): PluginBuilder; - /** - * Build the plugin - */ - build(): Plugin; -} -/** - * Helper functions for common plugin patterns. - * - * @beta This API is in beta and may change in future releases. - */ -declare class PluginHelpers { - /** - * Create a REST API route for a model. - * - * @experimental This method returns placeholder routes. Full implementation coming soon. - */ - static createModelAPI(modelName: string, options?: { - basePath?: string; - permissions?: { - read?: string[]; - write?: string[]; - delete?: string[]; - }; - }): Hono; - /** - * Create an admin CRUD interface for a model. - * - * @experimental This method generates basic admin page structures. Full implementation coming soon. - */ - static createAdminInterface(modelName: string, options?: { - icon?: string; - permissions?: string[]; - fields?: Array<{ - name: string; - type: string; - label: string; - required?: boolean; - }>; - }): { - pages: PluginAdminPage[]; - menuItems: PluginMenuItem[]; - }; - /** - * Create a database migration for a model - */ - static createMigration(tableName: string, fields: Array<{ - name: string; - type: 'TEXT' | 'INTEGER' | 'REAL' | 'BLOB'; - nullable?: boolean; - primaryKey?: boolean; - unique?: boolean; - defaultValue?: string; - }>): string; - /** - * Create a Zod schema for a model - */ - static createSchema(fields: Array<{ - name: string; - type: 'string' | 'number' | 'boolean' | 'date' | 'array' | 'object'; - optional?: boolean; - required?: boolean; - validation?: any; - items?: any; - properties?: Record; - }>): z.ZodSchema; -} - -/** - * @sonicjs/core - Main Entry Point - * - * Core framework for SonicJS headless CMS - * Built for Cloudflare's edge platform with TypeScript - * - * Phase 2 Migration Status: - * - Week 1: Types, Utils, Database (COMPLETED ✓) - * - Week 2: Services, Middleware, Plugins (COMPLETED ✓) - * - Week 3: Routes, Templates (COMPLETED ✓) - * - Week 4: Integration & Testing (COMPLETED ✓) - * - * Test Coverage: - * - Utilities: 48 tests (sanitize, query-filter, metrics) - * - Middleware: 51 tests (auth, logging, security, performance) - * - Total: 99 tests passing - */ - -declare const VERSION: string; - -export { PluginBuilder, PluginHelpers, VERSION, createDb }; diff --git a/packages/core/dist/index.d.ts b/packages/core/dist/index.d.ts deleted file mode 100644 index 29e14151e..000000000 --- a/packages/core/dist/index.d.ts +++ /dev/null @@ -1,539 +0,0 @@ -export { B as Bindings, b as SonicJSApp, S as SonicJSConfig, V as Variables, c as createSonicJSApp, s as setupCoreMiddleware, a as setupCoreRoutes } from './app-CYEm1ytG.js'; -import { t as schema } from './plugin-bootstrap-C7Mj00Ud.js'; -export { ab as Collection, ad as Content, C as CorePlugin, aj as DbPlugin, al as DbPluginHook, n as LogCategory, av as LogConfig, o as LogEntry, p as LogFilter, m as LogLevel, L as Logger, af as Media, e as Migration, M as MigrationService, h as MigrationStatus, ac as NewCollection, ae as NewContent, aw as NewLogConfig, ag as NewMedia, ak as NewPlugin, as as NewPluginActivityLog, aq as NewPluginAsset, am as NewPluginHook, ao as NewPluginRoute, au as NewSystemLog, aa as NewUser, ai as NewWorkflowHistory, ar as PluginActivityLog, ap as PluginAsset, q as PluginBootstrapService, an as PluginRoute, P as PluginServiceClass, at as SystemLog, a9 as User, ah as WorkflowHistory, A as apiTokens, d as cleanupRemovedCollections, w as collections, x as content, y as contentVersions, f as fullCollectionSync, g as getAvailableCollectionNames, j as getLogger, c as getManagedCollections, k as initLogger, O as insertCollectionSchema, R as insertContentSchema, a7 as insertLogConfigSchema, T as insertMediaSchema, a3 as insertPluginActivityLogSchema, a1 as insertPluginAssetSchema, Z as insertPluginHookSchema, $ as insertPluginRouteSchema, X as insertPluginSchema, a5 as insertSystemLogSchema, K as insertUserSchema, V as insertWorkflowHistorySchema, i as isCollectionManaged, a as loadCollectionConfig, l as loadCollectionConfigs, J as logConfig, z as media, H as pluginActivityLog, G as pluginAssets, E as pluginHooks, F as pluginRoutes, D as plugins, r as registerCollections, Q as selectCollectionSchema, S as selectContentSchema, a8 as selectLogConfigSchema, U as selectMediaSchema, a4 as selectPluginActivityLogSchema, a2 as selectPluginAssetSchema, _ as selectPluginHookSchema, a0 as selectPluginRouteSchema, Y as selectPluginSchema, a6 as selectSystemLogSchema, N as selectUserSchema, W as selectWorkflowHistorySchema, b as syncCollection, s as syncCollections, I as systemLogs, u as users, v as validateCollectionConfig, B as workflowHistory } from './plugin-bootstrap-C7Mj00Ud.js'; -export { AuthManager, Permission, PermissionManager, UserPermissions, bootstrapMiddleware, cacheHeaders, compressionMiddleware, detailedLoggingMiddleware, getActivePlugins, isPluginActive, logActivity, loggingMiddleware, optionalAuth, performanceLoggingMiddleware, requireActivePlugin, requireActivePlugins, requireAnyPermission, requireAuth, requirePermission, requireRole, securityHeaders, securityLoggingMiddleware } from './middleware.js'; -export { H as HookSystemImpl, a as HookUtils, b as PluginManagerClass, P as PluginRegistryImpl, c as PluginValidatorClass, S as ScopedHookSystemClass } from './plugin-manager-Baa6xXqB.js'; -export { ROUTES_INFO, adminApiRoutes, adminCheckboxRoutes, adminCodeExamplesRoutes, adminCollectionsRoutes, adminContentRoutes, adminDashboardRoutes, adminDesignRoutes, adminLogsRoutes, adminMediaRoutes, adminPluginRoutes, adminSettingsRoutes, adminTestimonialsRoutes, adminUsersRoutes, apiContentCrudRoutes, apiMediaRoutes, apiRoutes, apiSystemRoutes, authRoutes } from './routes.js'; -export { A as AlertData, C as ConfirmationDialogOptions, k as Filter, j as FilterBarData, l as FilterOption, h as FormData, F as FormField, P as PaginationData, T as TableColumn, i as TableData, g as getConfirmationDialogScript, d as renderAlert, e as renderConfirmationDialog, f as renderFilterBar, r as renderForm, a as renderFormField, c as renderPagination, b as renderTable } from './filter-bar.template-By4jeiw_.js'; -export { c as CollectionConfig, d as CollectionConfigModule, C as CollectionSchema, e as CollectionSyncResult, a as FieldConfig, F as FieldType } from './collection-config-BF95LgQb.js'; -export { A as AuthService, C as ContentService, v as HOOKS, k as HookContext, H as HookHandler, u as HookName, l as HookSystem, p as MediaService, P as Plugin, g as PluginAdminPage, r as PluginBuilderOptions, h as PluginComponent, b as PluginConfig, a as PluginContext, j as PluginHook, q as PluginLogger, n as PluginManager, i as PluginMenuItem, d as PluginMiddleware, e as PluginModel, m as PluginRegistry, c as PluginRoutes, f as PluginService, o as PluginStatus, t as PluginValidationResult, s as PluginValidator, S as ScopedHookSystem } from './plugin-zvZpaiP5.js'; -export { P as PluginManifest } from './plugin-manifest-Dpy8wxIB.js'; -export { c as FilterCondition, d as FilterGroup, F as FilterOperator, f as QueryFilter, Q as QueryFilterBuilder, h as QueryResult, S as SONICJS_VERSION, T as TemplateRenderer, b as buildQuery, e as escapeHtml, g as getCoreVersion, m as metricsTracker, r as renderTemplate, s as sanitizeInput, a as sanitizeObject, t as templateRenderer } from './version-vktVAxhe.js'; -import * as drizzle_orm_d1 from 'drizzle-orm/d1'; -import { Hono, MiddlewareHandler, Context } from 'hono'; -import { z } from 'zod'; -import { D1Database as D1Database$1, KVNamespace, R2Bucket } from '@cloudflare/workers-types'; -import 'drizzle-zod'; -import 'drizzle-orm/sqlite-core'; -import 'hono/types'; - -/** - * SonicJS Plugin System Types - * - * Defines the core interfaces and types for the plugin system - */ - -interface Plugin { - /** Unique plugin identifier */ - name: string; - /** Plugin version (semantic versioning) */ - version: string; - /** Human-readable description */ - description?: string; - /** Plugin author information */ - author?: { - name: string; - email?: string; - url?: string; - }; - /** Plugin dependencies (other plugins required) */ - dependencies?: string[]; - /** SonicJS version compatibility */ - compatibility?: string; - /** Plugin license */ - license?: string; - routes?: PluginRoutes[]; - middleware?: PluginMiddleware[]; - models?: PluginModel[]; - services?: PluginService[]; - adminPages?: PluginAdminPage[]; - adminComponents?: PluginComponent[]; - menuItems?: PluginMenuItem[]; - hooks?: PluginHook[]; - install?: (context: PluginContext) => Promise; - uninstall?: (context: PluginContext) => Promise; - activate?: (context: PluginContext) => Promise; - deactivate?: (context: PluginContext) => Promise; - configure?: (config: PluginConfig) => Promise; -} -interface PluginContext { - /** Database instance */ - db: D1Database$1; - /** Key-value storage */ - kv: KVNamespace; - /** R2 storage bucket */ - r2?: R2Bucket; - /** Plugin configuration */ - config: PluginConfig; - /** Core SonicJS services */ - services: { - auth: AuthService; - content: ContentService; - media: MediaService; - }; - /** Hook system for inter-plugin communication */ - hooks: HookSystem | ScopedHookSystem; - /** Logging utilities */ - logger: PluginLogger; -} -interface PluginConfig { - /** Plugin-specific configuration */ - [key: string]: any; - /** Whether plugin is enabled */ - enabled: boolean; - /** Plugin installation timestamp */ - installedAt?: number; - /** Plugin last update timestamp */ - updatedAt?: number; -} -interface PluginRoutes { - /** Route path prefix */ - path: string; - /** Hono route handler */ - handler: Hono; - /** Route description */ - description?: string; - /** Whether route requires authentication */ - requiresAuth?: boolean; - /** Required roles for access */ - roles?: string[]; - /** Route priority (for ordering) */ - priority?: number; -} -interface PluginMiddleware { - /** Middleware name */ - name: string; - /** Middleware handler function */ - handler: MiddlewareHandler; - /** Middleware description */ - description?: string; - /** Middleware priority (lower = earlier) */ - priority?: number; - /** Routes to apply middleware to */ - routes?: string[]; - /** Whether to apply globally */ - global?: boolean; -} -interface PluginModel { - /** Model name */ - name: string; - /** Database table name */ - tableName: string; - /** Zod schema for validation */ - schema: z.ZodSchema; - /** Database migrations */ - migrations: string[]; - /** Model relationships */ - relationships?: ModelRelationship[]; - /** Whether model extends core content */ - extendsContent?: boolean; -} -interface ModelRelationship { - type: 'oneToOne' | 'oneToMany' | 'manyToMany'; - target: string; - foreignKey?: string; - joinTable?: string; -} -interface PluginService { - /** Service name */ - name: string; - /** Service implementation */ - implementation: any; - /** Service description */ - description?: string; - /** Service dependencies */ - dependencies?: string[]; - /** Whether service is singleton */ - singleton?: boolean; -} -interface PluginAdminPage { - /** Page path (relative to /admin) */ - path: string; - /** Page title */ - title: string; - /** Page component/template */ - component: string; - /** Page description */ - description?: string; - /** Required permissions */ - permissions?: string[]; - /** Menu item configuration */ - menuItem?: PluginMenuItem; - /** Page icon */ - icon?: string; -} -interface PluginComponent { - /** Component name */ - name: string; - /** Component template function */ - template: (props: any) => string; - /** Component description */ - description?: string; - /** Component props schema */ - propsSchema?: z.ZodSchema; -} -interface PluginMenuItem { - /** Menu item label */ - label: string; - /** Menu item path */ - path: string; - /** Menu item icon */ - icon?: string; - /** Menu item order */ - order?: number; - /** Parent menu item */ - parent?: string; - /** Required permissions */ - permissions?: string[]; - /** Whether item is active */ - active?: boolean; -} -interface PluginHook { - /** Hook name */ - name: string; - /** Hook handler function */ - handler: HookHandler; - /** Hook priority */ - priority?: number; - /** Hook description */ - description?: string; -} -type HookHandler = (data: any, context: HookContext) => Promise; -interface HookContext { - /** Plugin that registered the hook */ - plugin: string; - /** Hook execution context */ - context: PluginContext; - /** Cancel hook execution */ - cancel?: () => void; -} -interface HookSystem { - /** Register a hook handler */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** Execute all handlers for a hook */ - execute(hookName: string, data: any, context?: any): Promise; - /** Remove a hook handler */ - unregister(hookName: string, handler: HookHandler): void; - /** Get all registered hooks */ - getHooks(hookName: string): PluginHook[]; - /** Create a scoped hook system (optional) */ - createScope?(pluginName: string): ScopedHookSystem; -} -interface ScopedHookSystem { - /** Register a hook handler */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** Execute all handlers for a hook */ - execute(hookName: string, data: any, context?: any): Promise; - /** Remove a hook handler */ - unregister(hookName: string, handler: HookHandler): void; - /** Remove all hooks for this scope */ - unregisterAll(): void; -} -interface AuthService { - /** Generate JWT token for a user */ - generateToken(userId: string, email: string, role: string): Promise; - /** Verify and decode JWT token */ - verifyToken(token: string): Promise; - /** Set authentication cookie (useful for alternative auth methods) */ - setAuthCookie(context: Context, token: string, options?: { - maxAge?: number; - secure?: boolean; - httpOnly?: boolean; - sameSite?: 'Strict' | 'Lax' | 'None'; - }): void; - /** Hash password */ - hashPassword(password: string): Promise; - /** Verify password against hash */ - verifyPassword(password: string, hash: string): Promise; -} -interface AuthService { - /** Verify user permissions */ - hasPermission(userId: string, permission: string): Promise; - /** Get current user */ - getCurrentUser(context: Context): Promise; - /** Create authentication middleware */ - createMiddleware(options?: any): MiddlewareHandler; -} -interface ContentService { - /** Get content by ID */ - getById(id: string): Promise; - /** Create new content */ - create(data: any): Promise; - /** Update content */ - update(id: string, data: any): Promise; - /** Delete content */ - delete(id: string): Promise; - /** Search content */ - search(query: string, options?: any): Promise; -} -interface MediaService { - /** Upload file */ - upload(file: File, options?: any): Promise; - /** Get media by ID */ - getById(id: string): Promise; - /** Delete media */ - delete(id: string): Promise; - /** Transform image */ - transform(id: string, options: any): Promise; -} -interface PluginLogger { - debug(message: string, data?: any): void; - info(message: string, data?: any): void; - warn(message: string, data?: any): void; - error(message: string, error?: Error, data?: any): void; -} -interface PluginBuilderOptions { - name: string; - version: string; - description?: string; - author?: Plugin['author']; - dependencies?: string[]; -} - -declare function createDb(d1: D1Database): drizzle_orm_d1.DrizzleD1Database & { - $client: D1Database; -}; - -/** - * Plugin Builder SDK - * - * Provides a fluent API for building SonicJS plugins - * - * @packageDocumentation - */ - -/** - * Fluent builder for creating SonicJS plugins. - * - * @beta This API is in beta and may change in future releases. - * - * @example - * ```typescript - * import { PluginBuilder } from '@sonicjs-cms/core' - * - * const plugin = PluginBuilder.create({ - * name: 'my-plugin', - * version: '1.0.0', - * description: 'My custom plugin' - * }) - * .addRoute('/api/my-plugin', routes) - * .addHook('content:save', handler) - * .lifecycle({ activate: async () => console.log('Activated!') }) - * .build() - * ``` - */ -declare class PluginBuilder { - private plugin; - constructor(options: PluginBuilderOptions); - /** - * Create a new plugin builder - */ - static create(options: PluginBuilderOptions): PluginBuilder; - /** - * Add metadata to the plugin - */ - metadata(metadata: { - description?: string; - author?: Plugin['author']; - license?: string; - compatibility?: string; - dependencies?: string[]; - }): PluginBuilder; - /** - * Add routes to plugin - */ - addRoutes(routes: PluginRoutes[]): PluginBuilder; - /** - * Add a single route to plugin - */ - addRoute(path: string, handler: Hono, options?: { - description?: string; - requiresAuth?: boolean; - roles?: string[]; - priority?: number; - }): PluginBuilder; - /** - * Add middleware to plugin - */ - addMiddleware(middleware: PluginMiddleware[]): PluginBuilder; - /** - * Add a single middleware to plugin - */ - addSingleMiddleware(name: string, handler: any, options?: { - description?: string; - priority?: number; - routes?: string[]; - global?: boolean; - }): PluginBuilder; - /** - * Add models to plugin - */ - addModels(models: PluginModel[]): PluginBuilder; - /** - * Add a single model to plugin - */ - addModel(name: string, options: { - tableName: string; - schema: z.ZodSchema; - migrations: string[]; - relationships?: PluginModel['relationships']; - extendsContent?: boolean; - }): PluginBuilder; - /** - * Add services to plugin - */ - addServices(services: PluginService[]): PluginBuilder; - /** - * Add a single service to plugin - */ - addService(name: string, implementation: any, options?: { - description?: string; - dependencies?: string[]; - singleton?: boolean; - }): PluginBuilder; - /** - * Add admin pages to plugin - */ - addAdminPages(pages: PluginAdminPage[]): PluginBuilder; - /** - * Add a single admin page to plugin - */ - addAdminPage(path: string, title: string, component: string, options?: { - description?: string; - permissions?: string[]; - icon?: string; - menuItem?: PluginMenuItem; - }): PluginBuilder; - /** - * Add admin components to plugin - */ - addComponents(components: PluginComponent[]): PluginBuilder; - /** - * Add a single admin component to plugin - */ - addComponent(name: string, template: (props: any) => string, options?: { - description?: string; - propsSchema?: z.ZodSchema; - }): PluginBuilder; - /** - * Add menu items to plugin - */ - addMenuItems(items: PluginMenuItem[]): PluginBuilder; - /** - * Add a single menu item to plugin - */ - addMenuItem(label: string, path: string, options?: { - icon?: string; - order?: number; - parent?: string; - permissions?: string[]; - }): PluginBuilder; - /** - * Add hooks to plugin - */ - addHooks(hooks: PluginHook[]): PluginBuilder; - /** - * Add a single hook to plugin - */ - addHook(name: string, handler: any, options?: { - priority?: number; - description?: string; - }): PluginBuilder; - /** - * Add lifecycle hooks - */ - lifecycle(hooks: { - install?: Plugin['install']; - uninstall?: Plugin['uninstall']; - activate?: Plugin['activate']; - deactivate?: Plugin['deactivate']; - configure?: Plugin['configure']; - }): PluginBuilder; - /** - * Build the plugin - */ - build(): Plugin; -} -/** - * Helper functions for common plugin patterns. - * - * @beta This API is in beta and may change in future releases. - */ -declare class PluginHelpers { - /** - * Create a REST API route for a model. - * - * @experimental This method returns placeholder routes. Full implementation coming soon. - */ - static createModelAPI(modelName: string, options?: { - basePath?: string; - permissions?: { - read?: string[]; - write?: string[]; - delete?: string[]; - }; - }): Hono; - /** - * Create an admin CRUD interface for a model. - * - * @experimental This method generates basic admin page structures. Full implementation coming soon. - */ - static createAdminInterface(modelName: string, options?: { - icon?: string; - permissions?: string[]; - fields?: Array<{ - name: string; - type: string; - label: string; - required?: boolean; - }>; - }): { - pages: PluginAdminPage[]; - menuItems: PluginMenuItem[]; - }; - /** - * Create a database migration for a model - */ - static createMigration(tableName: string, fields: Array<{ - name: string; - type: 'TEXT' | 'INTEGER' | 'REAL' | 'BLOB'; - nullable?: boolean; - primaryKey?: boolean; - unique?: boolean; - defaultValue?: string; - }>): string; - /** - * Create a Zod schema for a model - */ - static createSchema(fields: Array<{ - name: string; - type: 'string' | 'number' | 'boolean' | 'date' | 'array' | 'object'; - optional?: boolean; - required?: boolean; - validation?: any; - items?: any; - properties?: Record; - }>): z.ZodSchema; -} - -/** - * @sonicjs/core - Main Entry Point - * - * Core framework for SonicJS headless CMS - * Built for Cloudflare's edge platform with TypeScript - * - * Phase 2 Migration Status: - * - Week 1: Types, Utils, Database (COMPLETED ✓) - * - Week 2: Services, Middleware, Plugins (COMPLETED ✓) - * - Week 3: Routes, Templates (COMPLETED ✓) - * - Week 4: Integration & Testing (COMPLETED ✓) - * - * Test Coverage: - * - Utilities: 48 tests (sanitize, query-filter, metrics) - * - Middleware: 51 tests (auth, logging, security, performance) - * - Total: 99 tests passing - */ - -declare const VERSION: string; - -export { PluginBuilder, PluginHelpers, VERSION, createDb }; diff --git a/packages/core/dist/middleware.cjs b/packages/core/dist/middleware.cjs deleted file mode 100644 index 04f312187..000000000 --- a/packages/core/dist/middleware.cjs +++ /dev/null @@ -1,96 +0,0 @@ -'use strict'; - -var chunkDVQA5II3_cjs = require('./chunk-DVQA5II3.cjs'); -require('./chunk-MPT5PA6U.cjs'); -require('./chunk-FQSMNIY2.cjs'); -require('./chunk-RCQ2HIQD.cjs'); -require('./chunk-IGJUBJBW.cjs'); - - - -Object.defineProperty(exports, "AuthManager", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.AuthManager; } -}); -Object.defineProperty(exports, "PermissionManager", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.PermissionManager; } -}); -Object.defineProperty(exports, "bootstrapMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.bootstrapMiddleware; } -}); -Object.defineProperty(exports, "cacheHeaders", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.cacheHeaders; } -}); -Object.defineProperty(exports, "compressionMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.compressionMiddleware; } -}); -Object.defineProperty(exports, "detailedLoggingMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.detailedLoggingMiddleware; } -}); -Object.defineProperty(exports, "getActivePlugins", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.getActivePlugins; } -}); -Object.defineProperty(exports, "isPluginActive", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.isPluginActive; } -}); -Object.defineProperty(exports, "logActivity", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.logActivity; } -}); -Object.defineProperty(exports, "loggingMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.loggingMiddleware; } -}); -Object.defineProperty(exports, "metricsMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.metricsMiddleware; } -}); -Object.defineProperty(exports, "optionalAuth", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.optionalAuth; } -}); -Object.defineProperty(exports, "performanceLoggingMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.performanceLoggingMiddleware; } -}); -Object.defineProperty(exports, "requireActivePlugin", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requireActivePlugin; } -}); -Object.defineProperty(exports, "requireActivePlugins", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requireActivePlugins; } -}); -Object.defineProperty(exports, "requireAnyPermission", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requireAnyPermission; } -}); -Object.defineProperty(exports, "requireAuth", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requireAuth; } -}); -Object.defineProperty(exports, "requirePermission", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requirePermission; } -}); -Object.defineProperty(exports, "requireRole", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.requireRole; } -}); -Object.defineProperty(exports, "securityHeaders", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.securityHeaders; } -}); -Object.defineProperty(exports, "securityLoggingMiddleware", { - enumerable: true, - get: function () { return chunkDVQA5II3_cjs.securityLoggingMiddleware; } -}); -//# sourceMappingURL=middleware.cjs.map -//# sourceMappingURL=middleware.cjs.map \ No newline at end of file diff --git a/packages/core/dist/middleware.d.cts b/packages/core/dist/middleware.d.cts deleted file mode 100644 index 2d51b720b..000000000 --- a/packages/core/dist/middleware.d.cts +++ /dev/null @@ -1,89 +0,0 @@ -import * as hono from 'hono'; -import { Context, Next, MiddlewareHandler } from 'hono'; -import { S as SonicJSConfig } from './app-CYEm1ytG.cjs'; -import '@cloudflare/workers-types'; - -type Bindings = { - DB: D1Database; - KV: KVNamespace; -}; -/** - * Bootstrap middleware that ensures system initialization - * Runs once per worker instance - */ -declare function bootstrapMiddleware(config?: SonicJSConfig): (c: Context<{ - Bindings: Bindings; -}>, next: Next) => Promise; - -type JWTPayload = { - userId: string; - email: string; - role: string; - exp: number; - iat: number; -}; -declare class AuthManager { - static generateToken(userId: string, email: string, role: string): Promise; - static verifyToken(token: string): Promise; - static hashPassword(password: string): Promise; - static verifyPassword(password: string, hash: string): Promise; - /** - * Set authentication cookie - useful for plugins implementing alternative auth methods - * @param c - Hono context - * @param token - JWT token to set in cookie - * @param options - Optional cookie configuration - */ - static setAuthCookie(c: Context, token: string, options?: { - maxAge?: number; - secure?: boolean; - httpOnly?: boolean; - sameSite?: 'Strict' | 'Lax' | 'None'; - }): void; -} -declare const requireAuth: () => (c: Context, next: Next) => Promise) | (Response & hono.TypedResponse<{ - error: string; -}, 401, "json">)>; -declare const requireRole: (requiredRole: string | string[]) => (c: Context, next: Next) => Promise) | (Response & hono.TypedResponse<{ - error: string; -}, 401, "json">) | (Response & hono.TypedResponse<{ - error: string; -}, 403, "json">)>; -declare const optionalAuth: () => (c: Context, next: Next) => Promise; - -/** - * Middleware to track all HTTP requests for real-time analytics - * Excludes the metrics endpoint itself to avoid inflating the count - */ -declare const metricsMiddleware: () => MiddlewareHandler; - -/** - * Middleware Module Exports - * - * Request processing middleware for SonicJS - * - * Note: Most middleware is currently in the monolith and will be migrated later. - * For now, we only export the bootstrap middleware which is used for system initialization. - */ - -type Permission = string; -type UserPermissions = { - userId: string; - permissions: Permission[]; -}; -declare const loggingMiddleware: any; -declare const detailedLoggingMiddleware: any; -declare const securityLoggingMiddleware: any; -declare const performanceLoggingMiddleware: any; -declare const cacheHeaders: any; -declare const compressionMiddleware: any; -declare const securityHeaders: any; -declare const PermissionManager: any; -declare const requirePermission: any; -declare const requireAnyPermission: any; -declare const logActivity: any; -declare const requireActivePlugin: any; -declare const requireActivePlugins: any; -declare const getActivePlugins: any; -declare const isPluginActive: any; - -export { AuthManager, type Permission, PermissionManager, type UserPermissions, bootstrapMiddleware, cacheHeaders, compressionMiddleware, detailedLoggingMiddleware, getActivePlugins, isPluginActive, logActivity, loggingMiddleware, metricsMiddleware, optionalAuth, performanceLoggingMiddleware, requireActivePlugin, requireActivePlugins, requireAnyPermission, requireAuth, requirePermission, requireRole, securityHeaders, securityLoggingMiddleware }; diff --git a/packages/core/dist/middleware.d.ts b/packages/core/dist/middleware.d.ts deleted file mode 100644 index f8dcac637..000000000 --- a/packages/core/dist/middleware.d.ts +++ /dev/null @@ -1,89 +0,0 @@ -import * as hono from 'hono'; -import { Context, Next, MiddlewareHandler } from 'hono'; -import { S as SonicJSConfig } from './app-CYEm1ytG.js'; -import '@cloudflare/workers-types'; - -type Bindings = { - DB: D1Database; - KV: KVNamespace; -}; -/** - * Bootstrap middleware that ensures system initialization - * Runs once per worker instance - */ -declare function bootstrapMiddleware(config?: SonicJSConfig): (c: Context<{ - Bindings: Bindings; -}>, next: Next) => Promise; - -type JWTPayload = { - userId: string; - email: string; - role: string; - exp: number; - iat: number; -}; -declare class AuthManager { - static generateToken(userId: string, email: string, role: string): Promise; - static verifyToken(token: string): Promise; - static hashPassword(password: string): Promise; - static verifyPassword(password: string, hash: string): Promise; - /** - * Set authentication cookie - useful for plugins implementing alternative auth methods - * @param c - Hono context - * @param token - JWT token to set in cookie - * @param options - Optional cookie configuration - */ - static setAuthCookie(c: Context, token: string, options?: { - maxAge?: number; - secure?: boolean; - httpOnly?: boolean; - sameSite?: 'Strict' | 'Lax' | 'None'; - }): void; -} -declare const requireAuth: () => (c: Context, next: Next) => Promise) | (Response & hono.TypedResponse<{ - error: string; -}, 401, "json">)>; -declare const requireRole: (requiredRole: string | string[]) => (c: Context, next: Next) => Promise) | (Response & hono.TypedResponse<{ - error: string; -}, 401, "json">) | (Response & hono.TypedResponse<{ - error: string; -}, 403, "json">)>; -declare const optionalAuth: () => (c: Context, next: Next) => Promise; - -/** - * Middleware to track all HTTP requests for real-time analytics - * Excludes the metrics endpoint itself to avoid inflating the count - */ -declare const metricsMiddleware: () => MiddlewareHandler; - -/** - * Middleware Module Exports - * - * Request processing middleware for SonicJS - * - * Note: Most middleware is currently in the monolith and will be migrated later. - * For now, we only export the bootstrap middleware which is used for system initialization. - */ - -type Permission = string; -type UserPermissions = { - userId: string; - permissions: Permission[]; -}; -declare const loggingMiddleware: any; -declare const detailedLoggingMiddleware: any; -declare const securityLoggingMiddleware: any; -declare const performanceLoggingMiddleware: any; -declare const cacheHeaders: any; -declare const compressionMiddleware: any; -declare const securityHeaders: any; -declare const PermissionManager: any; -declare const requirePermission: any; -declare const requireAnyPermission: any; -declare const logActivity: any; -declare const requireActivePlugin: any; -declare const requireActivePlugins: any; -declare const getActivePlugins: any; -declare const isPluginActive: any; - -export { AuthManager, type Permission, PermissionManager, type UserPermissions, bootstrapMiddleware, cacheHeaders, compressionMiddleware, detailedLoggingMiddleware, getActivePlugins, isPluginActive, logActivity, loggingMiddleware, metricsMiddleware, optionalAuth, performanceLoggingMiddleware, requireActivePlugin, requireActivePlugins, requireAnyPermission, requireAuth, requirePermission, requireRole, securityHeaders, securityLoggingMiddleware }; diff --git a/packages/core/dist/migrations-VH7IQRJT.cjs b/packages/core/dist/migrations-VH7IQRJT.cjs deleted file mode 100644 index 6b7920b77..000000000 --- a/packages/core/dist/migrations-VH7IQRJT.cjs +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var chunkFQSMNIY2_cjs = require('./chunk-FQSMNIY2.cjs'); -require('./chunk-IGJUBJBW.cjs'); - - - -Object.defineProperty(exports, "MigrationService", { - enumerable: true, - get: function () { return chunkFQSMNIY2_cjs.MigrationService; } -}); -//# sourceMappingURL=migrations-VH7IQRJT.cjs.map -//# sourceMappingURL=migrations-VH7IQRJT.cjs.map \ No newline at end of file diff --git a/packages/core/dist/plugin-bootstrap-C7Mj00Ud.d.ts b/packages/core/dist/plugin-bootstrap-C7Mj00Ud.d.ts deleted file mode 100644 index 90f540ba9..000000000 --- a/packages/core/dist/plugin-bootstrap-C7Mj00Ud.d.ts +++ /dev/null @@ -1,10793 +0,0 @@ -import { c as CollectionConfig, e as CollectionSyncResult } from './collection-config-BF95LgQb.js'; -import { D1Database as D1Database$1 } from '@cloudflare/workers-types'; -import * as drizzle_zod from 'drizzle-zod'; -import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core'; - -/** - * Collection Loader Service - * - * Loads collection configuration files from the collections directory. - * Supports both development (reading from filesystem) and production (bundled). - */ - -/** - * Register collections from the application code - * This should be called before creating the app - */ -declare function registerCollections(collections: CollectionConfig[]): void; -/** - * Load all collection configurations from the collections directory - */ -declare function loadCollectionConfigs(): Promise; -/** - * Load a specific collection configuration by name - * Note: This function requires implementation in the consuming application - * as it depends on project-specific collection files - */ -declare function loadCollectionConfig(name: string): Promise; -/** - * Get list of all available collection config file names - */ -declare function getAvailableCollectionNames(): Promise; -/** - * Validate a collection configuration - */ -declare function validateCollectionConfig(config: CollectionConfig): { - valid: boolean; - errors: string[]; -}; - -/** - * Collection Sync Service - * - * Syncs collection configurations from code to the database. - * Handles create, update, and validation of config-managed collections. - */ - -/** - * Sync all collection configurations to the database - */ -declare function syncCollections(db: D1Database): Promise; -/** - * Sync a single collection configuration to the database - */ -declare function syncCollection(db: D1Database, config: CollectionConfig): Promise; -/** - * Check if a collection is managed by config - */ -declare function isCollectionManaged(db: D1Database, collectionName: string): Promise; -/** - * Get all managed collections from database - */ -declare function getManagedCollections(db: D1Database): Promise; -/** - * Remove collections that are no longer in config files - * (Only removes managed collections that aren't in the config) - */ -declare function cleanupRemovedCollections(db: D1Database): Promise; -/** - * Full sync: sync all configs and cleanup removed - */ -declare function fullCollectionSync(db: D1Database): Promise<{ - results: CollectionSyncResult[]; - removed: string[]; -}>; - -interface Migration { - id: string; - name: string; - filename: string; - description?: string; - applied: boolean; - appliedAt?: string; - size?: number; -} -interface MigrationStatus { - totalMigrations: number; - appliedMigrations: number; - pendingMigrations: number; - lastApplied?: string; - migrations: Migration[]; -} -declare class MigrationService { - private db; - constructor(db: D1Database$1); - /** - * Initialize the migrations tracking table - */ - initializeMigrationsTable(): Promise; - /** - * Get all available migrations from the bundled migrations - */ - getAvailableMigrations(): Promise; - /** - * Auto-detect applied migrations by checking if their tables exist - */ - private autoDetectAppliedMigrations; - /** - * Check if specific tables exist in the database - */ - private checkTablesExist; - /** - * Check if a specific column exists in a table - */ - private checkColumnExists; - /** - * Get migration status summary - */ - getMigrationStatus(): Promise; - /** - * Mark a migration as applied - */ - markMigrationApplied(migrationId: string, name: string, filename: string): Promise; - /** - * Remove a migration from the applied list (so it can be re-run) - */ - removeMigrationApplied(migrationId: string): Promise; - /** - * Check if a specific migration has been applied - */ - isMigrationApplied(migrationId: string): Promise; - /** - * Get the last applied migration - */ - getLastAppliedMigration(): Promise; - /** - * Run pending migrations - */ - runPendingMigrations(): Promise<{ - success: boolean; - message: string; - applied: string[]; - }>; - /** - * Apply a specific migration - */ - private applyMigration; - /** - * Split SQL into statements, handling CREATE TRIGGER properly - */ - private splitSQLStatements; - /** - * Validate database schema - */ - validateSchema(): Promise<{ - valid: boolean; - issues: string[]; - }>; -} - -declare const users: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "users"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - email: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "email"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - username: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "username"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - firstName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "first_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - lastName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - passwordHash: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "password_hash"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - role: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "role"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - avatar: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "avatar"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "users"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastLoginAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_login_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const collections: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "collections"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - schema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "schema"; - tableName: "collections"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const content: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "content"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - collectionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "collection_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - slug: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "slug"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - title: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "title"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "content"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - authorId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const contentVersions: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "content_versions"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "content_versions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - contentId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "content_id"; - tableName: "content_versions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - version: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "version"; - tableName: "content_versions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "content_versions"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - authorId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author_id"; - tableName: "content_versions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "content_versions"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const media: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "media"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - filename: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "filename"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - originalName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "original_name"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mimeType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "mime_type"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - size: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "size"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - width: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "width"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - height: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "height"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - folder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "folder"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - r2Key: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "r2_key"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publicUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "public_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - thumbnailUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "thumbnail_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - alt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "alt"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - caption: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "caption"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "media"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - uploadedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_by"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - scheduledAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "scheduled_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - archivedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "archived_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - deletedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "deleted_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const apiTokens: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "api_tokens"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "api_tokens"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "api_tokens"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - token: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "token"; - tableName: "api_tokens"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "api_tokens"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - permissions: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "permissions"; - tableName: "api_tokens"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - expiresAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "expires_at"; - tableName: "api_tokens"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastUsedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_used_at"; - tableName: "api_tokens"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "api_tokens"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const workflowHistory: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "workflow_history"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - contentId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "content_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fromStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "from_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - toStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "to_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - comment: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "comment"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "workflow_history"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const plugins: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "plugins"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - version: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "version"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - author: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isCore: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_core"; - tableName: "plugins"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - permissions: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "permissions"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - dependencies: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "dependencies"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - downloadCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "download_count"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - rating: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "rating"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - installedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "installed_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - activatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "activated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastUpdated: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_updated"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - errorMessage: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "error_message"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const pluginHooks: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "plugin_hooks"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - hookName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "hook_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - priority: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "priority"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_hooks"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const pluginRoutes: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "plugin_routes"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - path: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "path"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - middleware: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "middleware"; - tableName: "plugin_routes"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_routes"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_routes"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const pluginAssets: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "plugin_assets"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_type"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetPath: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_path"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - loadOrder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_order"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - loadLocation: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_location"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_assets"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const pluginActivityLog: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "plugin_activity_log"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - details: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "details"; - tableName: "plugin_activity_log"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - timestamp: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "timestamp"; - tableName: "plugin_activity_log"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const insertUserSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - email: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "email"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - username: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "username"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - firstName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "first_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - lastName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - passwordHash: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "password_hash"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - role: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "role"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - avatar: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "avatar"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "users"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastLoginAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_login_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - email: (schema: any) => any; - firstName: (schema: any) => any; - lastName: (schema: any) => any; - username: (schema: any) => any; -}, undefined>; -declare const selectUserSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - email: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "email"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - username: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "username"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - firstName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "first_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - lastName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - passwordHash: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "password_hash"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - role: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "role"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - avatar: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "avatar"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "users"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastLoginAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_login_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertCollectionSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - schema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "schema"; - tableName: "collections"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - name: (schema: any) => any; - displayName: (schema: any) => any; -}, undefined>; -declare const selectCollectionSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - schema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "schema"; - tableName: "collections"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertContentSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - collectionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "collection_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - slug: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "slug"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - title: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "title"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "content"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - authorId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - slug: (schema: any) => any; - title: (schema: any) => any; - status: (schema: any) => any; -}, undefined>; -declare const selectContentSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - collectionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "collection_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - slug: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "slug"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - title: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "title"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "content"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - authorId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertMediaSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - filename: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "filename"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - originalName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "original_name"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mimeType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "mime_type"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - size: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "size"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - width: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "width"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - height: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "height"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - folder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "folder"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - r2Key: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "r2_key"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publicUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "public_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - thumbnailUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "thumbnail_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - alt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "alt"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - caption: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "caption"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "media"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - uploadedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_by"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - scheduledAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "scheduled_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - archivedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "archived_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - deletedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "deleted_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - filename: (schema: any) => any; - originalName: (schema: any) => any; - mimeType: (schema: any) => any; - size: (schema: any) => any; - r2Key: (schema: any) => any; - publicUrl: (schema: any) => any; - folder: (schema: any) => any; -}, undefined>; -declare const selectMediaSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - filename: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "filename"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - originalName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "original_name"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mimeType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "mime_type"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - size: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "size"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - width: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "width"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - height: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "height"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - folder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "folder"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - r2Key: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "r2_key"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publicUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "public_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - thumbnailUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "thumbnail_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - alt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "alt"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - caption: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "caption"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "media"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - uploadedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_by"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - scheduledAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "scheduled_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - archivedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "archived_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - deletedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "deleted_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertWorkflowHistorySchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - contentId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "content_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fromStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "from_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - toStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "to_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - comment: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "comment"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "workflow_history"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - action: (schema: any) => any; - fromStatus: (schema: any) => any; - toStatus: (schema: any) => any; -}, undefined>; -declare const selectWorkflowHistorySchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - contentId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "content_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fromStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "from_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - toStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "to_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - comment: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "comment"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "workflow_history"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertPluginSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - version: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "version"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - author: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isCore: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_core"; - tableName: "plugins"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - permissions: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "permissions"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - dependencies: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "dependencies"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - downloadCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "download_count"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - rating: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "rating"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - installedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "installed_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - activatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "activated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastUpdated: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_updated"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - errorMessage: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "error_message"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - name: (schema: any) => any; - displayName: (schema: any) => any; - version: (schema: any) => any; - author: (schema: any) => any; - category: (schema: any) => any; -}, undefined>; -declare const selectPluginSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - version: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "version"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - author: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isCore: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_core"; - tableName: "plugins"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - permissions: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "permissions"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - dependencies: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "dependencies"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - downloadCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "download_count"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - rating: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "rating"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - installedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "installed_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - activatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "activated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastUpdated: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_updated"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - errorMessage: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "error_message"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertPluginHookSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - hookName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "hook_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - priority: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "priority"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_hooks"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - hookName: (schema: any) => any; - handlerName: (schema: any) => any; -}, undefined>; -declare const selectPluginHookSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - hookName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "hook_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - priority: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "priority"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_hooks"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertPluginRouteSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - path: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "path"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - middleware: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "middleware"; - tableName: "plugin_routes"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_routes"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_routes"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - path: (schema: any) => any; - method: (schema: any) => any; - handlerName: (schema: any) => any; -}, undefined>; -declare const selectPluginRouteSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - path: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "path"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - middleware: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "middleware"; - tableName: "plugin_routes"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_routes"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_routes"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertPluginAssetSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_type"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetPath: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_path"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - loadOrder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_order"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - loadLocation: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_location"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_assets"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - assetType: (schema: any) => any; - assetPath: (schema: any) => any; -}, undefined>; -declare const selectPluginAssetSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_type"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetPath: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_path"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - loadOrder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_order"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - loadLocation: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_location"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_assets"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertPluginActivityLogSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - details: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "details"; - tableName: "plugin_activity_log"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - timestamp: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "timestamp"; - tableName: "plugin_activity_log"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - action: (schema: any) => any; -}, undefined>; -declare const selectPluginActivityLogSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - details: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "details"; - tableName: "plugin_activity_log"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - timestamp: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "timestamp"; - tableName: "plugin_activity_log"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const systemLogs: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "system_logs"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - message: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "message"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - sessionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "session_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - requestId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "request_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - url: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "url"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - statusCode: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status_code"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - duration: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "duration"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - stackTrace: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "stack_trace"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - source: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "source"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "system_logs"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const logConfig: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "log_config"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - enabled: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "enabled"; - tableName: "log_config"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - retention: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "retention"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - maxSize: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "max_size"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const insertSystemLogSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - message: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "message"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - sessionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "session_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - requestId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "request_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - url: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "url"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - statusCode: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status_code"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - duration: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "duration"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - stackTrace: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "stack_trace"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - source: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "source"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "system_logs"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - level: (schema: any) => any; - category: (schema: any) => any; - message: (schema: any) => any; -}, undefined>; -declare const selectSystemLogSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - message: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "message"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - sessionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "session_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - requestId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "request_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - url: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "url"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - statusCode: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status_code"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - duration: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "duration"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - stackTrace: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "stack_trace"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - source: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "source"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "system_logs"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertLogConfigSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - enabled: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "enabled"; - tableName: "log_config"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - retention: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "retention"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - maxSize: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "max_size"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - category: (schema: any) => any; - level: (schema: any) => any; -}, undefined>; -declare const selectLogConfigSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - enabled: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "enabled"; - tableName: "log_config"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - retention: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "retention"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - maxSize: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "max_size"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -type User = typeof users.$inferSelect; -type NewUser = typeof users.$inferInsert; -type Collection = typeof collections.$inferSelect; -type NewCollection = typeof collections.$inferInsert; -type Content = typeof content.$inferSelect; -type NewContent = typeof content.$inferInsert; -type Media = typeof media.$inferSelect; -type NewMedia = typeof media.$inferInsert; -type WorkflowHistory = typeof workflowHistory.$inferSelect; -type NewWorkflowHistory = typeof workflowHistory.$inferInsert; -type Plugin = typeof plugins.$inferSelect; -type NewPlugin = typeof plugins.$inferInsert; -type PluginHook = typeof pluginHooks.$inferSelect; -type NewPluginHook = typeof pluginHooks.$inferInsert; -type PluginRoute = typeof pluginRoutes.$inferSelect; -type NewPluginRoute = typeof pluginRoutes.$inferInsert; -type PluginAsset = typeof pluginAssets.$inferSelect; -type NewPluginAsset = typeof pluginAssets.$inferInsert; -type PluginActivityLog = typeof pluginActivityLog.$inferSelect; -type NewPluginActivityLog = typeof pluginActivityLog.$inferInsert; -type SystemLog = typeof systemLogs.$inferSelect; -type NewSystemLog = typeof systemLogs.$inferInsert; -type LogConfig = typeof logConfig.$inferSelect; -type NewLogConfig = typeof logConfig.$inferInsert; -declare const forms: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "forms"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formioSchema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "formio_schema"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isPublic: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_public"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - color: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "color"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submissionCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - viewCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "view_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - updatedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const formSubmissions: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "form_submissions"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "form_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionData: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_data"; - tableName: "form_submissions"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionNumber: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_number"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userEmail: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_email"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - referrer: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "referrer"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmSource: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_source"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmMedium: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_medium"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmCampaign: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_campaign"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_by"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - reviewNotes: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "review_notes"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isSpam: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_spam"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isArchived: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_archived"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submittedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submitted_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const formFiles: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "form_files"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mediaId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "media_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fieldName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "field_name"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "form_files"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const insertFormSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formioSchema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "formio_schema"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isPublic: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_public"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - color: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "color"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submissionCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - viewCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "view_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - updatedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const selectFormSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formioSchema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "formio_schema"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isPublic: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_public"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - color: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "color"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submissionCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - viewCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "view_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - updatedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertFormSubmissionSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "form_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionData: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_data"; - tableName: "form_submissions"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionNumber: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_number"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userEmail: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_email"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - referrer: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "referrer"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmSource: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_source"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmMedium: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_medium"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmCampaign: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_campaign"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_by"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - reviewNotes: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "review_notes"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isSpam: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_spam"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isArchived: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_archived"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submittedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submitted_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const selectFormSubmissionSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "form_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionData: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_data"; - tableName: "form_submissions"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionNumber: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_number"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userEmail: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_email"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - referrer: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "referrer"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmSource: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_source"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmMedium: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_medium"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmCampaign: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_campaign"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_by"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - reviewNotes: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "review_notes"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isSpam: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_spam"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isArchived: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_archived"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submittedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submitted_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertFormFileSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mediaId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "media_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fieldName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "field_name"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "form_files"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const selectFormFileSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mediaId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "media_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fieldName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "field_name"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "form_files"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -type Form = typeof forms.$inferSelect; -type NewForm = typeof forms.$inferInsert; -type FormSubmission = typeof formSubmissions.$inferSelect; -type NewFormSubmission = typeof formSubmissions.$inferInsert; -type FormFile = typeof formFiles.$inferSelect; -type NewFormFile = typeof formFiles.$inferInsert; - -type schema_Collection = Collection; -type schema_Content = Content; -type schema_Form = Form; -type schema_FormFile = FormFile; -type schema_FormSubmission = FormSubmission; -type schema_LogConfig = LogConfig; -type schema_Media = Media; -type schema_NewCollection = NewCollection; -type schema_NewContent = NewContent; -type schema_NewForm = NewForm; -type schema_NewFormFile = NewFormFile; -type schema_NewFormSubmission = NewFormSubmission; -type schema_NewLogConfig = NewLogConfig; -type schema_NewMedia = NewMedia; -type schema_NewPlugin = NewPlugin; -type schema_NewPluginActivityLog = NewPluginActivityLog; -type schema_NewPluginAsset = NewPluginAsset; -type schema_NewPluginHook = NewPluginHook; -type schema_NewPluginRoute = NewPluginRoute; -type schema_NewSystemLog = NewSystemLog; -type schema_NewUser = NewUser; -type schema_NewWorkflowHistory = NewWorkflowHistory; -type schema_Plugin = Plugin; -type schema_PluginActivityLog = PluginActivityLog; -type schema_PluginAsset = PluginAsset; -type schema_PluginHook = PluginHook; -type schema_PluginRoute = PluginRoute; -type schema_SystemLog = SystemLog; -type schema_User = User; -type schema_WorkflowHistory = WorkflowHistory; -declare const schema_apiTokens: typeof apiTokens; -declare const schema_collections: typeof collections; -declare const schema_content: typeof content; -declare const schema_contentVersions: typeof contentVersions; -declare const schema_formFiles: typeof formFiles; -declare const schema_formSubmissions: typeof formSubmissions; -declare const schema_forms: typeof forms; -declare const schema_insertCollectionSchema: typeof insertCollectionSchema; -declare const schema_insertContentSchema: typeof insertContentSchema; -declare const schema_insertFormFileSchema: typeof insertFormFileSchema; -declare const schema_insertFormSchema: typeof insertFormSchema; -declare const schema_insertFormSubmissionSchema: typeof insertFormSubmissionSchema; -declare const schema_insertLogConfigSchema: typeof insertLogConfigSchema; -declare const schema_insertMediaSchema: typeof insertMediaSchema; -declare const schema_insertPluginActivityLogSchema: typeof insertPluginActivityLogSchema; -declare const schema_insertPluginAssetSchema: typeof insertPluginAssetSchema; -declare const schema_insertPluginHookSchema: typeof insertPluginHookSchema; -declare const schema_insertPluginRouteSchema: typeof insertPluginRouteSchema; -declare const schema_insertPluginSchema: typeof insertPluginSchema; -declare const schema_insertSystemLogSchema: typeof insertSystemLogSchema; -declare const schema_insertUserSchema: typeof insertUserSchema; -declare const schema_insertWorkflowHistorySchema: typeof insertWorkflowHistorySchema; -declare const schema_logConfig: typeof logConfig; -declare const schema_media: typeof media; -declare const schema_pluginActivityLog: typeof pluginActivityLog; -declare const schema_pluginAssets: typeof pluginAssets; -declare const schema_pluginHooks: typeof pluginHooks; -declare const schema_pluginRoutes: typeof pluginRoutes; -declare const schema_plugins: typeof plugins; -declare const schema_selectCollectionSchema: typeof selectCollectionSchema; -declare const schema_selectContentSchema: typeof selectContentSchema; -declare const schema_selectFormFileSchema: typeof selectFormFileSchema; -declare const schema_selectFormSchema: typeof selectFormSchema; -declare const schema_selectFormSubmissionSchema: typeof selectFormSubmissionSchema; -declare const schema_selectLogConfigSchema: typeof selectLogConfigSchema; -declare const schema_selectMediaSchema: typeof selectMediaSchema; -declare const schema_selectPluginActivityLogSchema: typeof selectPluginActivityLogSchema; -declare const schema_selectPluginAssetSchema: typeof selectPluginAssetSchema; -declare const schema_selectPluginHookSchema: typeof selectPluginHookSchema; -declare const schema_selectPluginRouteSchema: typeof selectPluginRouteSchema; -declare const schema_selectPluginSchema: typeof selectPluginSchema; -declare const schema_selectSystemLogSchema: typeof selectSystemLogSchema; -declare const schema_selectUserSchema: typeof selectUserSchema; -declare const schema_selectWorkflowHistorySchema: typeof selectWorkflowHistorySchema; -declare const schema_systemLogs: typeof systemLogs; -declare const schema_users: typeof users; -declare const schema_workflowHistory: typeof workflowHistory; -declare namespace schema { - export { type schema_Collection as Collection, type schema_Content as Content, type schema_Form as Form, type schema_FormFile as FormFile, type schema_FormSubmission as FormSubmission, type schema_LogConfig as LogConfig, type schema_Media as Media, type schema_NewCollection as NewCollection, type schema_NewContent as NewContent, type schema_NewForm as NewForm, type schema_NewFormFile as NewFormFile, type schema_NewFormSubmission as NewFormSubmission, type schema_NewLogConfig as NewLogConfig, type schema_NewMedia as NewMedia, type schema_NewPlugin as NewPlugin, type schema_NewPluginActivityLog as NewPluginActivityLog, type schema_NewPluginAsset as NewPluginAsset, type schema_NewPluginHook as NewPluginHook, type schema_NewPluginRoute as NewPluginRoute, type schema_NewSystemLog as NewSystemLog, type schema_NewUser as NewUser, type schema_NewWorkflowHistory as NewWorkflowHistory, type schema_Plugin as Plugin, type schema_PluginActivityLog as PluginActivityLog, type schema_PluginAsset as PluginAsset, type schema_PluginHook as PluginHook, type schema_PluginRoute as PluginRoute, type schema_SystemLog as SystemLog, type schema_User as User, type schema_WorkflowHistory as WorkflowHistory, schema_apiTokens as apiTokens, schema_collections as collections, schema_content as content, schema_contentVersions as contentVersions, schema_formFiles as formFiles, schema_formSubmissions as formSubmissions, schema_forms as forms, schema_insertCollectionSchema as insertCollectionSchema, schema_insertContentSchema as insertContentSchema, schema_insertFormFileSchema as insertFormFileSchema, schema_insertFormSchema as insertFormSchema, schema_insertFormSubmissionSchema as insertFormSubmissionSchema, schema_insertLogConfigSchema as insertLogConfigSchema, schema_insertMediaSchema as insertMediaSchema, schema_insertPluginActivityLogSchema as insertPluginActivityLogSchema, schema_insertPluginAssetSchema as insertPluginAssetSchema, schema_insertPluginHookSchema as insertPluginHookSchema, schema_insertPluginRouteSchema as insertPluginRouteSchema, schema_insertPluginSchema as insertPluginSchema, schema_insertSystemLogSchema as insertSystemLogSchema, schema_insertUserSchema as insertUserSchema, schema_insertWorkflowHistorySchema as insertWorkflowHistorySchema, schema_logConfig as logConfig, schema_media as media, schema_pluginActivityLog as pluginActivityLog, schema_pluginAssets as pluginAssets, schema_pluginHooks as pluginHooks, schema_pluginRoutes as pluginRoutes, schema_plugins as plugins, schema_selectCollectionSchema as selectCollectionSchema, schema_selectContentSchema as selectContentSchema, schema_selectFormFileSchema as selectFormFileSchema, schema_selectFormSchema as selectFormSchema, schema_selectFormSubmissionSchema as selectFormSubmissionSchema, schema_selectLogConfigSchema as selectLogConfigSchema, schema_selectMediaSchema as selectMediaSchema, schema_selectPluginActivityLogSchema as selectPluginActivityLogSchema, schema_selectPluginAssetSchema as selectPluginAssetSchema, schema_selectPluginHookSchema as selectPluginHookSchema, schema_selectPluginRouteSchema as selectPluginRouteSchema, schema_selectPluginSchema as selectPluginSchema, schema_selectSystemLogSchema as selectSystemLogSchema, schema_selectUserSchema as selectUserSchema, schema_selectWorkflowHistorySchema as selectWorkflowHistorySchema, schema_systemLogs as systemLogs, schema_users as users, schema_workflowHistory as workflowHistory }; -} - -type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal'; -type LogCategory = 'auth' | 'api' | 'workflow' | 'plugin' | 'media' | 'system' | 'security' | 'error'; -interface LogEntry { - level: LogLevel; - category: LogCategory; - message: string; - data?: any; - userId?: string; - sessionId?: string; - requestId?: string; - ipAddress?: string; - userAgent?: string; - method?: string; - url?: string; - statusCode?: number; - duration?: number; - stackTrace?: string; - tags?: string[]; - source?: string; -} -interface LogFilter { - level?: LogLevel[]; - category?: LogCategory[]; - userId?: string; - source?: string; - search?: string; - startDate?: Date; - endDate?: Date; - tags?: string[]; - limit?: number; - offset?: number; - sortBy?: 'created_at' | 'level' | 'category'; - sortOrder?: 'asc' | 'desc'; -} -declare class Logger { - private db; - private enabled; - private configCache; - private lastConfigRefresh; - private configRefreshInterval; - constructor(database: D1Database$1); - /** - * Log a debug message - */ - debug(category: LogCategory, message: string, data?: any, context?: Partial): Promise; - /** - * Log an info message - */ - info(category: LogCategory, message: string, data?: any, context?: Partial): Promise; - /** - * Log a warning message - */ - warn(category: LogCategory, message: string, data?: any, context?: Partial): Promise; - /** - * Log an error message - */ - error(category: LogCategory, message: string, error?: Error | any, context?: Partial): Promise; - /** - * Log a fatal message - */ - fatal(category: LogCategory, message: string, error?: Error | any, context?: Partial): Promise; - /** - * Log an API request - */ - logRequest(method: string, url: string, statusCode: number, duration: number, context?: Partial): Promise; - /** - * Log an authentication event - */ - logAuth(action: string, userId?: string, success?: boolean, context?: Partial): Promise; - /** - * Log a security event - */ - logSecurity(event: string, severity: 'low' | 'medium' | 'high' | 'critical', context?: Partial): Promise; - /** - * Core logging method - */ - private log; - /** - * Get logs with filtering and pagination - */ - getLogs(filter?: LogFilter): Promise<{ - logs: any[]; - total: number; - }>; - /** - * Get log configuration for a category - */ - private getConfig; - /** - * Update log configuration - */ - updateConfig(category: LogCategory, updates: Partial): Promise; - /** - * Get all log configurations - */ - getAllConfigs(): Promise; - /** - * Clean up old logs for a category - */ - private cleanupCategory; - /** - * Clean up logs based on retention policy - */ - cleanupByRetention(): Promise; - /** - * Check if a log level should be recorded based on configuration - */ - private shouldLog; - /** - * Enable or disable logging - */ - setEnabled(enabled: boolean): void; - /** - * Check if logging is enabled - */ - isEnabled(): boolean; -} -/** - * Get the logger instance - */ -declare function getLogger(database?: D1Database$1): Logger; -/** - * Initialize the logger with a database - */ -declare function initLogger(database: D1Database$1): Logger; - -interface PluginData { - id: string; - name: string; - display_name: string; - description: string; - version: string; - author: string; - category: string; - icon: string; - status: 'active' | 'inactive' | 'error'; - is_core: boolean; - settings?: any; - permissions?: string[]; - dependencies?: string[]; - download_count: number; - rating: number; - installed_at: number; - activated_at?: number; - last_updated: number; - error_message?: string; -} -interface PluginStats { - total: number; - active: number; - inactive: number; - errors: number; - uninstalled: number; -} -declare class PluginService { - private db; - constructor(db: D1Database$1); - getAllPlugins(): Promise; - /** - * Ensure all plugins from the registry exist in the database - * Auto-installs any newly detected plugins with inactive status - * - * Note: This method should be overridden or configured with a plugin registry - * in the consuming application - */ - private ensureAllPluginsExist; - getPlugin(pluginId: string): Promise; - getPluginByName(name: string): Promise; - getPluginStats(): Promise; - installPlugin(pluginData: Partial): Promise; - uninstallPlugin(pluginId: string): Promise; - activatePlugin(pluginId: string): Promise; - deactivatePlugin(pluginId: string): Promise; - updatePluginSettings(pluginId: string, settings: any): Promise; - setPluginError(pluginId: string, error: string): Promise; - getPluginActivity(pluginId: string, limit?: number): Promise; - registerHook(pluginId: string, hookName: string, handlerName: string, priority?: number): Promise; - registerRoute(pluginId: string, path: string, method: string, handlerName: string, middleware?: any[]): Promise; - getPluginHooks(pluginId: string): Promise; - getPluginRoutes(pluginId: string): Promise; - private checkDependencies; - private checkDependents; - private logActivity; - private mapPluginFromDb; -} - -interface CorePlugin { - id: string; - name: string; - display_name: string; - description: string; - version: string; - author: string; - category: string; - icon: string; - permissions: string[]; - dependencies: string[]; - settings?: any; -} -declare class PluginBootstrapService { - private db; - private pluginService; - constructor(db: D1Database$1); - /** - * Core plugins that should always be available in the system - */ - private readonly CORE_PLUGINS; - /** - * Bootstrap all core plugins - install them if they don't exist - */ - bootstrapCorePlugins(): Promise; - /** - * Ensure a specific plugin is installed - */ - private ensurePluginInstalled; - /** - * Update an existing plugin - */ - private updatePlugin; - /** - * Check if bootstrap is needed (first run detection) - */ - isBootstrapNeeded(): Promise; -} - -export { insertPluginRouteSchema as $, apiTokens as A, workflowHistory as B, type CorePlugin as C, plugins as D, pluginHooks as E, pluginRoutes as F, pluginAssets as G, pluginActivityLog as H, systemLogs as I, logConfig as J, insertUserSchema as K, Logger as L, MigrationService as M, selectUserSchema as N, insertCollectionSchema as O, PluginService as P, selectCollectionSchema as Q, insertContentSchema as R, selectContentSchema as S, insertMediaSchema as T, selectMediaSchema as U, insertWorkflowHistorySchema as V, selectWorkflowHistorySchema as W, insertPluginSchema as X, selectPluginSchema as Y, insertPluginHookSchema as Z, selectPluginHookSchema as _, loadCollectionConfig as a, selectPluginRouteSchema as a0, insertPluginAssetSchema as a1, selectPluginAssetSchema as a2, insertPluginActivityLogSchema as a3, selectPluginActivityLogSchema as a4, insertSystemLogSchema as a5, selectSystemLogSchema as a6, insertLogConfigSchema as a7, selectLogConfigSchema as a8, type User as a9, type NewUser as aa, type Collection as ab, type NewCollection as ac, type Content as ad, type NewContent as ae, type Media as af, type NewMedia as ag, type WorkflowHistory as ah, type NewWorkflowHistory as ai, type Plugin as aj, type NewPlugin as ak, type PluginHook as al, type NewPluginHook as am, type PluginRoute as an, type NewPluginRoute as ao, type PluginAsset as ap, type NewPluginAsset as aq, type PluginActivityLog as ar, type NewPluginActivityLog as as, type SystemLog as at, type NewSystemLog as au, type LogConfig as av, type NewLogConfig as aw, syncCollection as b, getManagedCollections as c, cleanupRemovedCollections as d, type Migration as e, fullCollectionSync as f, getAvailableCollectionNames as g, type MigrationStatus as h, isCollectionManaged as i, getLogger as j, initLogger as k, loadCollectionConfigs as l, type LogLevel as m, type LogCategory as n, type LogEntry as o, type LogFilter as p, PluginBootstrapService as q, registerCollections as r, syncCollections as s, schema as t, users as u, validateCollectionConfig as v, collections as w, content as x, contentVersions as y, media as z }; diff --git a/packages/core/dist/plugin-bootstrap-DKB5f8-E.d.cts b/packages/core/dist/plugin-bootstrap-DKB5f8-E.d.cts deleted file mode 100644 index e610d63c6..000000000 --- a/packages/core/dist/plugin-bootstrap-DKB5f8-E.d.cts +++ /dev/null @@ -1,10793 +0,0 @@ -import { c as CollectionConfig, e as CollectionSyncResult } from './collection-config-BF95LgQb.cjs'; -import { D1Database as D1Database$1 } from '@cloudflare/workers-types'; -import * as drizzle_zod from 'drizzle-zod'; -import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core'; - -/** - * Collection Loader Service - * - * Loads collection configuration files from the collections directory. - * Supports both development (reading from filesystem) and production (bundled). - */ - -/** - * Register collections from the application code - * This should be called before creating the app - */ -declare function registerCollections(collections: CollectionConfig[]): void; -/** - * Load all collection configurations from the collections directory - */ -declare function loadCollectionConfigs(): Promise; -/** - * Load a specific collection configuration by name - * Note: This function requires implementation in the consuming application - * as it depends on project-specific collection files - */ -declare function loadCollectionConfig(name: string): Promise; -/** - * Get list of all available collection config file names - */ -declare function getAvailableCollectionNames(): Promise; -/** - * Validate a collection configuration - */ -declare function validateCollectionConfig(config: CollectionConfig): { - valid: boolean; - errors: string[]; -}; - -/** - * Collection Sync Service - * - * Syncs collection configurations from code to the database. - * Handles create, update, and validation of config-managed collections. - */ - -/** - * Sync all collection configurations to the database - */ -declare function syncCollections(db: D1Database): Promise; -/** - * Sync a single collection configuration to the database - */ -declare function syncCollection(db: D1Database, config: CollectionConfig): Promise; -/** - * Check if a collection is managed by config - */ -declare function isCollectionManaged(db: D1Database, collectionName: string): Promise; -/** - * Get all managed collections from database - */ -declare function getManagedCollections(db: D1Database): Promise; -/** - * Remove collections that are no longer in config files - * (Only removes managed collections that aren't in the config) - */ -declare function cleanupRemovedCollections(db: D1Database): Promise; -/** - * Full sync: sync all configs and cleanup removed - */ -declare function fullCollectionSync(db: D1Database): Promise<{ - results: CollectionSyncResult[]; - removed: string[]; -}>; - -interface Migration { - id: string; - name: string; - filename: string; - description?: string; - applied: boolean; - appliedAt?: string; - size?: number; -} -interface MigrationStatus { - totalMigrations: number; - appliedMigrations: number; - pendingMigrations: number; - lastApplied?: string; - migrations: Migration[]; -} -declare class MigrationService { - private db; - constructor(db: D1Database$1); - /** - * Initialize the migrations tracking table - */ - initializeMigrationsTable(): Promise; - /** - * Get all available migrations from the bundled migrations - */ - getAvailableMigrations(): Promise; - /** - * Auto-detect applied migrations by checking if their tables exist - */ - private autoDetectAppliedMigrations; - /** - * Check if specific tables exist in the database - */ - private checkTablesExist; - /** - * Check if a specific column exists in a table - */ - private checkColumnExists; - /** - * Get migration status summary - */ - getMigrationStatus(): Promise; - /** - * Mark a migration as applied - */ - markMigrationApplied(migrationId: string, name: string, filename: string): Promise; - /** - * Remove a migration from the applied list (so it can be re-run) - */ - removeMigrationApplied(migrationId: string): Promise; - /** - * Check if a specific migration has been applied - */ - isMigrationApplied(migrationId: string): Promise; - /** - * Get the last applied migration - */ - getLastAppliedMigration(): Promise; - /** - * Run pending migrations - */ - runPendingMigrations(): Promise<{ - success: boolean; - message: string; - applied: string[]; - }>; - /** - * Apply a specific migration - */ - private applyMigration; - /** - * Split SQL into statements, handling CREATE TRIGGER properly - */ - private splitSQLStatements; - /** - * Validate database schema - */ - validateSchema(): Promise<{ - valid: boolean; - issues: string[]; - }>; -} - -declare const users: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "users"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - email: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "email"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - username: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "username"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - firstName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "first_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - lastName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - passwordHash: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "password_hash"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - role: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "role"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - avatar: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "avatar"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "users"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastLoginAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_login_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const collections: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "collections"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - schema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "schema"; - tableName: "collections"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const content: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "content"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - collectionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "collection_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - slug: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "slug"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - title: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "title"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "content"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - authorId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const contentVersions: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "content_versions"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "content_versions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - contentId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "content_id"; - tableName: "content_versions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - version: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "version"; - tableName: "content_versions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "content_versions"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - authorId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author_id"; - tableName: "content_versions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "content_versions"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const media: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "media"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - filename: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "filename"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - originalName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "original_name"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mimeType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "mime_type"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - size: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "size"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - width: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "width"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - height: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "height"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - folder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "folder"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - r2Key: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "r2_key"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publicUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "public_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - thumbnailUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "thumbnail_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - alt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "alt"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - caption: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "caption"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "media"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - uploadedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_by"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - scheduledAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "scheduled_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - archivedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "archived_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - deletedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "deleted_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const apiTokens: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "api_tokens"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "api_tokens"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "api_tokens"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - token: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "token"; - tableName: "api_tokens"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "api_tokens"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - permissions: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "permissions"; - tableName: "api_tokens"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - expiresAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "expires_at"; - tableName: "api_tokens"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastUsedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_used_at"; - tableName: "api_tokens"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "api_tokens"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const workflowHistory: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "workflow_history"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - contentId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "content_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fromStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "from_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - toStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "to_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - comment: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "comment"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "workflow_history"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const plugins: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "plugins"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - version: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "version"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - author: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isCore: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_core"; - tableName: "plugins"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - permissions: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "permissions"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - dependencies: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "dependencies"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - downloadCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "download_count"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - rating: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "rating"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - installedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "installed_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - activatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "activated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastUpdated: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_updated"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - errorMessage: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "error_message"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const pluginHooks: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "plugin_hooks"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - hookName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "hook_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - priority: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "priority"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_hooks"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const pluginRoutes: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "plugin_routes"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - path: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "path"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - middleware: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "middleware"; - tableName: "plugin_routes"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_routes"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_routes"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const pluginAssets: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "plugin_assets"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_type"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetPath: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_path"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - loadOrder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_order"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - loadLocation: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_location"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_assets"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const pluginActivityLog: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "plugin_activity_log"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - details: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "details"; - tableName: "plugin_activity_log"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - timestamp: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "timestamp"; - tableName: "plugin_activity_log"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const insertUserSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - email: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "email"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - username: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "username"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - firstName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "first_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - lastName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - passwordHash: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "password_hash"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - role: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "role"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - avatar: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "avatar"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "users"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastLoginAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_login_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - email: (schema: any) => any; - firstName: (schema: any) => any; - lastName: (schema: any) => any; - username: (schema: any) => any; -}, undefined>; -declare const selectUserSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - email: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "email"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - username: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "username"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - firstName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "first_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - lastName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_name"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - passwordHash: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "password_hash"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - role: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "role"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - avatar: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "avatar"; - tableName: "users"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "users"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastLoginAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_login_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "users"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertCollectionSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - schema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "schema"; - tableName: "collections"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - name: (schema: any) => any; - displayName: (schema: any) => any; -}, undefined>; -declare const selectCollectionSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "collections"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - schema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "schema"; - tableName: "collections"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "collections"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "collections"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertContentSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - collectionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "collection_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - slug: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "slug"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - title: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "title"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "content"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - authorId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - slug: (schema: any) => any; - title: (schema: any) => any; - status: (schema: any) => any; -}, undefined>; -declare const selectContentSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - collectionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "collection_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - slug: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "slug"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - title: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "title"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "content"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - authorId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author_id"; - tableName: "content"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "content"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertMediaSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - filename: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "filename"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - originalName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "original_name"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mimeType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "mime_type"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - size: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "size"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - width: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "width"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - height: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "height"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - folder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "folder"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - r2Key: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "r2_key"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publicUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "public_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - thumbnailUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "thumbnail_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - alt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "alt"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - caption: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "caption"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "media"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - uploadedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_by"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - scheduledAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "scheduled_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - archivedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "archived_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - deletedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "deleted_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - filename: (schema: any) => any; - originalName: (schema: any) => any; - mimeType: (schema: any) => any; - size: (schema: any) => any; - r2Key: (schema: any) => any; - publicUrl: (schema: any) => any; - folder: (schema: any) => any; -}, undefined>; -declare const selectMediaSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - filename: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "filename"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - originalName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "original_name"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mimeType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "mime_type"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - size: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "size"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - width: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "width"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - height: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "height"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - folder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "folder"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - r2Key: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "r2_key"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - publicUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "public_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - thumbnailUrl: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "thumbnail_url"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - alt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "alt"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - caption: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "caption"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "media"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - uploadedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_by"; - tableName: "media"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - publishedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "published_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - scheduledAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "scheduled_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - archivedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "archived_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - deletedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "deleted_at"; - tableName: "media"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertWorkflowHistorySchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - contentId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "content_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fromStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "from_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - toStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "to_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - comment: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "comment"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "workflow_history"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - action: (schema: any) => any; - fromStatus: (schema: any) => any; - toStatus: (schema: any) => any; -}, undefined>; -declare const selectWorkflowHistorySchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - contentId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "content_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fromStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "from_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - toStatus: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "to_status"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - comment: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "comment"; - tableName: "workflow_history"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "workflow_history"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertPluginSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - version: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "version"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - author: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isCore: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_core"; - tableName: "plugins"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - permissions: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "permissions"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - dependencies: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "dependencies"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - downloadCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "download_count"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - rating: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "rating"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - installedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "installed_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - activatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "activated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastUpdated: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_updated"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - errorMessage: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "error_message"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - name: (schema: any) => any; - displayName: (schema: any) => any; - version: (schema: any) => any; - author: (schema: any) => any; - category: (schema: any) => any; -}, undefined>; -declare const selectPluginSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - version: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "version"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - author: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "author"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isCore: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_core"; - tableName: "plugins"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - permissions: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "permissions"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - dependencies: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "dependencies"; - tableName: "plugins"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - downloadCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "download_count"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - rating: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "rating"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - installedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "installed_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - activatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "activated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - lastUpdated: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "last_updated"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - errorMessage: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "error_message"; - tableName: "plugins"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "plugins"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertPluginHookSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - hookName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "hook_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - priority: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "priority"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_hooks"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - hookName: (schema: any) => any; - handlerName: (schema: any) => any; -}, undefined>; -declare const selectPluginHookSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - hookName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "hook_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_hooks"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - priority: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "priority"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_hooks"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_hooks"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertPluginRouteSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - path: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "path"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - middleware: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "middleware"; - tableName: "plugin_routes"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_routes"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_routes"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - path: (schema: any) => any; - method: (schema: any) => any; - handlerName: (schema: any) => any; -}, undefined>; -declare const selectPluginRouteSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - path: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "path"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - handlerName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "handler_name"; - tableName: "plugin_routes"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - middleware: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "middleware"; - tableName: "plugin_routes"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_routes"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_routes"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertPluginAssetSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_type"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetPath: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_path"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - loadOrder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_order"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - loadLocation: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_location"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_assets"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - assetType: (schema: any) => any; - assetPath: (schema: any) => any; -}, undefined>; -declare const selectPluginAssetSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetType: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_type"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - assetPath: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "asset_path"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - loadOrder: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_order"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - loadLocation: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "load_location"; - tableName: "plugin_assets"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "plugin_assets"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "plugin_assets"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertPluginActivityLogSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - details: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "details"; - tableName: "plugin_activity_log"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - timestamp: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "timestamp"; - tableName: "plugin_activity_log"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - action: (schema: any) => any; -}, undefined>; -declare const selectPluginActivityLogSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - pluginId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "plugin_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - action: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "action"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "plugin_activity_log"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - details: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "details"; - tableName: "plugin_activity_log"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - timestamp: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "timestamp"; - tableName: "plugin_activity_log"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const systemLogs: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "system_logs"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - message: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "message"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - sessionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "session_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - requestId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "request_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - url: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "url"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - statusCode: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status_code"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - duration: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "duration"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - stackTrace: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "stack_trace"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - source: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "source"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "system_logs"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const logConfig: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "log_config"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - enabled: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "enabled"; - tableName: "log_config"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - retention: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "retention"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - maxSize: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "max_size"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const insertSystemLogSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - message: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "message"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - sessionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "session_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - requestId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "request_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - url: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "url"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - statusCode: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status_code"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - duration: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "duration"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - stackTrace: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "stack_trace"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - source: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "source"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "system_logs"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - level: (schema: any) => any; - category: (schema: any) => any; - message: (schema: any) => any; -}, undefined>; -declare const selectSystemLogSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - message: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "message"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - data: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "data"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - sessionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "session_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - requestId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "request_id"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - method: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "method"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - url: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "url"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - statusCode: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status_code"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - duration: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "duration"; - tableName: "system_logs"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - stackTrace: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "stack_trace"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "system_logs"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - source: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "source"; - tableName: "system_logs"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "system_logs"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertLogConfigSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - enabled: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "enabled"; - tableName: "log_config"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - retention: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "retention"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - maxSize: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "max_size"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, { - category: (schema: any) => any; - level: (schema: any) => any; -}, undefined>; -declare const selectLogConfigSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - enabled: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "enabled"; - tableName: "log_config"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - level: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "level"; - tableName: "log_config"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - retention: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "retention"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - maxSize: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "max_size"; - tableName: "log_config"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "log_config"; - dataType: "date"; - columnType: "SQLiteTimestamp"; - data: Date; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: true; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -type User = typeof users.$inferSelect; -type NewUser = typeof users.$inferInsert; -type Collection = typeof collections.$inferSelect; -type NewCollection = typeof collections.$inferInsert; -type Content = typeof content.$inferSelect; -type NewContent = typeof content.$inferInsert; -type Media = typeof media.$inferSelect; -type NewMedia = typeof media.$inferInsert; -type WorkflowHistory = typeof workflowHistory.$inferSelect; -type NewWorkflowHistory = typeof workflowHistory.$inferInsert; -type Plugin = typeof plugins.$inferSelect; -type NewPlugin = typeof plugins.$inferInsert; -type PluginHook = typeof pluginHooks.$inferSelect; -type NewPluginHook = typeof pluginHooks.$inferInsert; -type PluginRoute = typeof pluginRoutes.$inferSelect; -type NewPluginRoute = typeof pluginRoutes.$inferInsert; -type PluginAsset = typeof pluginAssets.$inferSelect; -type NewPluginAsset = typeof pluginAssets.$inferInsert; -type PluginActivityLog = typeof pluginActivityLog.$inferSelect; -type NewPluginActivityLog = typeof pluginActivityLog.$inferInsert; -type SystemLog = typeof systemLogs.$inferSelect; -type NewSystemLog = typeof systemLogs.$inferInsert; -type LogConfig = typeof logConfig.$inferSelect; -type NewLogConfig = typeof logConfig.$inferInsert; -declare const forms: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "forms"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formioSchema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "formio_schema"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isPublic: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_public"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - color: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "color"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submissionCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - viewCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "view_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - updatedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const formSubmissions: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "form_submissions"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "form_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionData: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_data"; - tableName: "form_submissions"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionNumber: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_number"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userEmail: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_email"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - referrer: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "referrer"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmSource: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_source"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmMedium: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_medium"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmCampaign: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_campaign"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_by"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - reviewNotes: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "review_notes"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isSpam: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_spam"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isArchived: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_archived"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submittedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submitted_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const formFiles: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{ - name: "form_files"; - schema: undefined; - columns: { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mediaId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "media_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fieldName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "field_name"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "form_files"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - }; - dialect: "sqlite"; -}>; -declare const insertFormSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formioSchema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "formio_schema"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isPublic: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_public"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - color: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "color"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submissionCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - viewCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "view_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - updatedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const selectFormSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - name: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - displayName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "display_name"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - description: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "description"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - category: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "category"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formioSchema: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "formio_schema"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - settings: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "settings"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isActive: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_active"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isPublic: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_public"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - managed: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "managed"; - tableName: "forms"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - icon: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "icon"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - color: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "color"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - tags: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "tags"; - tableName: "forms"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submissionCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - viewCount: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "view_count"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - createdBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - updatedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_by"; - tableName: "forms"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - createdAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "created_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "forms"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertFormSubmissionSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "form_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionData: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_data"; - tableName: "form_submissions"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionNumber: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_number"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userEmail: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_email"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - referrer: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "referrer"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmSource: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_source"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmMedium: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_medium"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmCampaign: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_campaign"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_by"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - reviewNotes: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "review_notes"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isSpam: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_spam"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isArchived: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_archived"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submittedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submitted_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const selectFormSubmissionSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - formId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "form_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionData: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_data"; - tableName: "form_submissions"; - dataType: "json"; - columnType: "SQLiteTextJson"; - data: unknown; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - status: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "status"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionNumber: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_number"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - userId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_id"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userEmail: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_email"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - ipAddress: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "ip_address"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - userAgent: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "user_agent"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - referrer: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "referrer"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmSource: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_source"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmMedium: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_medium"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - utmCampaign: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "utm_campaign"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedBy: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_by"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - reviewedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "reviewed_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - reviewNotes: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "review_notes"; - tableName: "form_submissions"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: false; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - isSpam: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_spam"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - isArchived: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "is_archived"; - tableName: "form_submissions"; - dataType: "boolean"; - columnType: "SQLiteBoolean"; - data: boolean; - driverParam: number; - notNull: true; - hasDefault: true; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - submittedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submitted_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; - updatedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "updated_at"; - tableName: "form_submissions"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const insertFormFileSchema: drizzle_zod.BuildSchema<"insert", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mediaId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "media_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fieldName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "field_name"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "form_files"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -declare const selectFormFileSchema: drizzle_zod.BuildSchema<"select", { - id: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: true; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - submissionId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "submission_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - mediaId: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "media_id"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - fieldName: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "field_name"; - tableName: "form_files"; - dataType: "string"; - columnType: "SQLiteText"; - data: string; - driverParam: string; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: [string, ...string[]]; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, { - length: number | undefined; - }>; - uploadedAt: drizzle_orm_sqlite_core.SQLiteColumn<{ - name: "uploaded_at"; - tableName: "form_files"; - dataType: "number"; - columnType: "SQLiteInteger"; - data: number; - driverParam: number; - notNull: true; - hasDefault: false; - isPrimaryKey: false; - isAutoincrement: false; - hasRuntimeDefault: false; - enumValues: undefined; - baseColumn: never; - identity: undefined; - generated: undefined; - }, {}, {}>; -}, undefined, undefined>; -type Form = typeof forms.$inferSelect; -type NewForm = typeof forms.$inferInsert; -type FormSubmission = typeof formSubmissions.$inferSelect; -type NewFormSubmission = typeof formSubmissions.$inferInsert; -type FormFile = typeof formFiles.$inferSelect; -type NewFormFile = typeof formFiles.$inferInsert; - -type schema_Collection = Collection; -type schema_Content = Content; -type schema_Form = Form; -type schema_FormFile = FormFile; -type schema_FormSubmission = FormSubmission; -type schema_LogConfig = LogConfig; -type schema_Media = Media; -type schema_NewCollection = NewCollection; -type schema_NewContent = NewContent; -type schema_NewForm = NewForm; -type schema_NewFormFile = NewFormFile; -type schema_NewFormSubmission = NewFormSubmission; -type schema_NewLogConfig = NewLogConfig; -type schema_NewMedia = NewMedia; -type schema_NewPlugin = NewPlugin; -type schema_NewPluginActivityLog = NewPluginActivityLog; -type schema_NewPluginAsset = NewPluginAsset; -type schema_NewPluginHook = NewPluginHook; -type schema_NewPluginRoute = NewPluginRoute; -type schema_NewSystemLog = NewSystemLog; -type schema_NewUser = NewUser; -type schema_NewWorkflowHistory = NewWorkflowHistory; -type schema_Plugin = Plugin; -type schema_PluginActivityLog = PluginActivityLog; -type schema_PluginAsset = PluginAsset; -type schema_PluginHook = PluginHook; -type schema_PluginRoute = PluginRoute; -type schema_SystemLog = SystemLog; -type schema_User = User; -type schema_WorkflowHistory = WorkflowHistory; -declare const schema_apiTokens: typeof apiTokens; -declare const schema_collections: typeof collections; -declare const schema_content: typeof content; -declare const schema_contentVersions: typeof contentVersions; -declare const schema_formFiles: typeof formFiles; -declare const schema_formSubmissions: typeof formSubmissions; -declare const schema_forms: typeof forms; -declare const schema_insertCollectionSchema: typeof insertCollectionSchema; -declare const schema_insertContentSchema: typeof insertContentSchema; -declare const schema_insertFormFileSchema: typeof insertFormFileSchema; -declare const schema_insertFormSchema: typeof insertFormSchema; -declare const schema_insertFormSubmissionSchema: typeof insertFormSubmissionSchema; -declare const schema_insertLogConfigSchema: typeof insertLogConfigSchema; -declare const schema_insertMediaSchema: typeof insertMediaSchema; -declare const schema_insertPluginActivityLogSchema: typeof insertPluginActivityLogSchema; -declare const schema_insertPluginAssetSchema: typeof insertPluginAssetSchema; -declare const schema_insertPluginHookSchema: typeof insertPluginHookSchema; -declare const schema_insertPluginRouteSchema: typeof insertPluginRouteSchema; -declare const schema_insertPluginSchema: typeof insertPluginSchema; -declare const schema_insertSystemLogSchema: typeof insertSystemLogSchema; -declare const schema_insertUserSchema: typeof insertUserSchema; -declare const schema_insertWorkflowHistorySchema: typeof insertWorkflowHistorySchema; -declare const schema_logConfig: typeof logConfig; -declare const schema_media: typeof media; -declare const schema_pluginActivityLog: typeof pluginActivityLog; -declare const schema_pluginAssets: typeof pluginAssets; -declare const schema_pluginHooks: typeof pluginHooks; -declare const schema_pluginRoutes: typeof pluginRoutes; -declare const schema_plugins: typeof plugins; -declare const schema_selectCollectionSchema: typeof selectCollectionSchema; -declare const schema_selectContentSchema: typeof selectContentSchema; -declare const schema_selectFormFileSchema: typeof selectFormFileSchema; -declare const schema_selectFormSchema: typeof selectFormSchema; -declare const schema_selectFormSubmissionSchema: typeof selectFormSubmissionSchema; -declare const schema_selectLogConfigSchema: typeof selectLogConfigSchema; -declare const schema_selectMediaSchema: typeof selectMediaSchema; -declare const schema_selectPluginActivityLogSchema: typeof selectPluginActivityLogSchema; -declare const schema_selectPluginAssetSchema: typeof selectPluginAssetSchema; -declare const schema_selectPluginHookSchema: typeof selectPluginHookSchema; -declare const schema_selectPluginRouteSchema: typeof selectPluginRouteSchema; -declare const schema_selectPluginSchema: typeof selectPluginSchema; -declare const schema_selectSystemLogSchema: typeof selectSystemLogSchema; -declare const schema_selectUserSchema: typeof selectUserSchema; -declare const schema_selectWorkflowHistorySchema: typeof selectWorkflowHistorySchema; -declare const schema_systemLogs: typeof systemLogs; -declare const schema_users: typeof users; -declare const schema_workflowHistory: typeof workflowHistory; -declare namespace schema { - export { type schema_Collection as Collection, type schema_Content as Content, type schema_Form as Form, type schema_FormFile as FormFile, type schema_FormSubmission as FormSubmission, type schema_LogConfig as LogConfig, type schema_Media as Media, type schema_NewCollection as NewCollection, type schema_NewContent as NewContent, type schema_NewForm as NewForm, type schema_NewFormFile as NewFormFile, type schema_NewFormSubmission as NewFormSubmission, type schema_NewLogConfig as NewLogConfig, type schema_NewMedia as NewMedia, type schema_NewPlugin as NewPlugin, type schema_NewPluginActivityLog as NewPluginActivityLog, type schema_NewPluginAsset as NewPluginAsset, type schema_NewPluginHook as NewPluginHook, type schema_NewPluginRoute as NewPluginRoute, type schema_NewSystemLog as NewSystemLog, type schema_NewUser as NewUser, type schema_NewWorkflowHistory as NewWorkflowHistory, type schema_Plugin as Plugin, type schema_PluginActivityLog as PluginActivityLog, type schema_PluginAsset as PluginAsset, type schema_PluginHook as PluginHook, type schema_PluginRoute as PluginRoute, type schema_SystemLog as SystemLog, type schema_User as User, type schema_WorkflowHistory as WorkflowHistory, schema_apiTokens as apiTokens, schema_collections as collections, schema_content as content, schema_contentVersions as contentVersions, schema_formFiles as formFiles, schema_formSubmissions as formSubmissions, schema_forms as forms, schema_insertCollectionSchema as insertCollectionSchema, schema_insertContentSchema as insertContentSchema, schema_insertFormFileSchema as insertFormFileSchema, schema_insertFormSchema as insertFormSchema, schema_insertFormSubmissionSchema as insertFormSubmissionSchema, schema_insertLogConfigSchema as insertLogConfigSchema, schema_insertMediaSchema as insertMediaSchema, schema_insertPluginActivityLogSchema as insertPluginActivityLogSchema, schema_insertPluginAssetSchema as insertPluginAssetSchema, schema_insertPluginHookSchema as insertPluginHookSchema, schema_insertPluginRouteSchema as insertPluginRouteSchema, schema_insertPluginSchema as insertPluginSchema, schema_insertSystemLogSchema as insertSystemLogSchema, schema_insertUserSchema as insertUserSchema, schema_insertWorkflowHistorySchema as insertWorkflowHistorySchema, schema_logConfig as logConfig, schema_media as media, schema_pluginActivityLog as pluginActivityLog, schema_pluginAssets as pluginAssets, schema_pluginHooks as pluginHooks, schema_pluginRoutes as pluginRoutes, schema_plugins as plugins, schema_selectCollectionSchema as selectCollectionSchema, schema_selectContentSchema as selectContentSchema, schema_selectFormFileSchema as selectFormFileSchema, schema_selectFormSchema as selectFormSchema, schema_selectFormSubmissionSchema as selectFormSubmissionSchema, schema_selectLogConfigSchema as selectLogConfigSchema, schema_selectMediaSchema as selectMediaSchema, schema_selectPluginActivityLogSchema as selectPluginActivityLogSchema, schema_selectPluginAssetSchema as selectPluginAssetSchema, schema_selectPluginHookSchema as selectPluginHookSchema, schema_selectPluginRouteSchema as selectPluginRouteSchema, schema_selectPluginSchema as selectPluginSchema, schema_selectSystemLogSchema as selectSystemLogSchema, schema_selectUserSchema as selectUserSchema, schema_selectWorkflowHistorySchema as selectWorkflowHistorySchema, schema_systemLogs as systemLogs, schema_users as users, schema_workflowHistory as workflowHistory }; -} - -type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal'; -type LogCategory = 'auth' | 'api' | 'workflow' | 'plugin' | 'media' | 'system' | 'security' | 'error'; -interface LogEntry { - level: LogLevel; - category: LogCategory; - message: string; - data?: any; - userId?: string; - sessionId?: string; - requestId?: string; - ipAddress?: string; - userAgent?: string; - method?: string; - url?: string; - statusCode?: number; - duration?: number; - stackTrace?: string; - tags?: string[]; - source?: string; -} -interface LogFilter { - level?: LogLevel[]; - category?: LogCategory[]; - userId?: string; - source?: string; - search?: string; - startDate?: Date; - endDate?: Date; - tags?: string[]; - limit?: number; - offset?: number; - sortBy?: 'created_at' | 'level' | 'category'; - sortOrder?: 'asc' | 'desc'; -} -declare class Logger { - private db; - private enabled; - private configCache; - private lastConfigRefresh; - private configRefreshInterval; - constructor(database: D1Database$1); - /** - * Log a debug message - */ - debug(category: LogCategory, message: string, data?: any, context?: Partial): Promise; - /** - * Log an info message - */ - info(category: LogCategory, message: string, data?: any, context?: Partial): Promise; - /** - * Log a warning message - */ - warn(category: LogCategory, message: string, data?: any, context?: Partial): Promise; - /** - * Log an error message - */ - error(category: LogCategory, message: string, error?: Error | any, context?: Partial): Promise; - /** - * Log a fatal message - */ - fatal(category: LogCategory, message: string, error?: Error | any, context?: Partial): Promise; - /** - * Log an API request - */ - logRequest(method: string, url: string, statusCode: number, duration: number, context?: Partial): Promise; - /** - * Log an authentication event - */ - logAuth(action: string, userId?: string, success?: boolean, context?: Partial): Promise; - /** - * Log a security event - */ - logSecurity(event: string, severity: 'low' | 'medium' | 'high' | 'critical', context?: Partial): Promise; - /** - * Core logging method - */ - private log; - /** - * Get logs with filtering and pagination - */ - getLogs(filter?: LogFilter): Promise<{ - logs: any[]; - total: number; - }>; - /** - * Get log configuration for a category - */ - private getConfig; - /** - * Update log configuration - */ - updateConfig(category: LogCategory, updates: Partial): Promise; - /** - * Get all log configurations - */ - getAllConfigs(): Promise; - /** - * Clean up old logs for a category - */ - private cleanupCategory; - /** - * Clean up logs based on retention policy - */ - cleanupByRetention(): Promise; - /** - * Check if a log level should be recorded based on configuration - */ - private shouldLog; - /** - * Enable or disable logging - */ - setEnabled(enabled: boolean): void; - /** - * Check if logging is enabled - */ - isEnabled(): boolean; -} -/** - * Get the logger instance - */ -declare function getLogger(database?: D1Database$1): Logger; -/** - * Initialize the logger with a database - */ -declare function initLogger(database: D1Database$1): Logger; - -interface PluginData { - id: string; - name: string; - display_name: string; - description: string; - version: string; - author: string; - category: string; - icon: string; - status: 'active' | 'inactive' | 'error'; - is_core: boolean; - settings?: any; - permissions?: string[]; - dependencies?: string[]; - download_count: number; - rating: number; - installed_at: number; - activated_at?: number; - last_updated: number; - error_message?: string; -} -interface PluginStats { - total: number; - active: number; - inactive: number; - errors: number; - uninstalled: number; -} -declare class PluginService { - private db; - constructor(db: D1Database$1); - getAllPlugins(): Promise; - /** - * Ensure all plugins from the registry exist in the database - * Auto-installs any newly detected plugins with inactive status - * - * Note: This method should be overridden or configured with a plugin registry - * in the consuming application - */ - private ensureAllPluginsExist; - getPlugin(pluginId: string): Promise; - getPluginByName(name: string): Promise; - getPluginStats(): Promise; - installPlugin(pluginData: Partial): Promise; - uninstallPlugin(pluginId: string): Promise; - activatePlugin(pluginId: string): Promise; - deactivatePlugin(pluginId: string): Promise; - updatePluginSettings(pluginId: string, settings: any): Promise; - setPluginError(pluginId: string, error: string): Promise; - getPluginActivity(pluginId: string, limit?: number): Promise; - registerHook(pluginId: string, hookName: string, handlerName: string, priority?: number): Promise; - registerRoute(pluginId: string, path: string, method: string, handlerName: string, middleware?: any[]): Promise; - getPluginHooks(pluginId: string): Promise; - getPluginRoutes(pluginId: string): Promise; - private checkDependencies; - private checkDependents; - private logActivity; - private mapPluginFromDb; -} - -interface CorePlugin { - id: string; - name: string; - display_name: string; - description: string; - version: string; - author: string; - category: string; - icon: string; - permissions: string[]; - dependencies: string[]; - settings?: any; -} -declare class PluginBootstrapService { - private db; - private pluginService; - constructor(db: D1Database$1); - /** - * Core plugins that should always be available in the system - */ - private readonly CORE_PLUGINS; - /** - * Bootstrap all core plugins - install them if they don't exist - */ - bootstrapCorePlugins(): Promise; - /** - * Ensure a specific plugin is installed - */ - private ensurePluginInstalled; - /** - * Update an existing plugin - */ - private updatePlugin; - /** - * Check if bootstrap is needed (first run detection) - */ - isBootstrapNeeded(): Promise; -} - -export { insertPluginRouteSchema as $, apiTokens as A, workflowHistory as B, type CorePlugin as C, plugins as D, pluginHooks as E, pluginRoutes as F, pluginAssets as G, pluginActivityLog as H, systemLogs as I, logConfig as J, insertUserSchema as K, Logger as L, MigrationService as M, selectUserSchema as N, insertCollectionSchema as O, PluginService as P, selectCollectionSchema as Q, insertContentSchema as R, selectContentSchema as S, insertMediaSchema as T, selectMediaSchema as U, insertWorkflowHistorySchema as V, selectWorkflowHistorySchema as W, insertPluginSchema as X, selectPluginSchema as Y, insertPluginHookSchema as Z, selectPluginHookSchema as _, loadCollectionConfig as a, selectPluginRouteSchema as a0, insertPluginAssetSchema as a1, selectPluginAssetSchema as a2, insertPluginActivityLogSchema as a3, selectPluginActivityLogSchema as a4, insertSystemLogSchema as a5, selectSystemLogSchema as a6, insertLogConfigSchema as a7, selectLogConfigSchema as a8, type User as a9, type NewUser as aa, type Collection as ab, type NewCollection as ac, type Content as ad, type NewContent as ae, type Media as af, type NewMedia as ag, type WorkflowHistory as ah, type NewWorkflowHistory as ai, type Plugin as aj, type NewPlugin as ak, type PluginHook as al, type NewPluginHook as am, type PluginRoute as an, type NewPluginRoute as ao, type PluginAsset as ap, type NewPluginAsset as aq, type PluginActivityLog as ar, type NewPluginActivityLog as as, type SystemLog as at, type NewSystemLog as au, type LogConfig as av, type NewLogConfig as aw, syncCollection as b, getManagedCollections as c, cleanupRemovedCollections as d, type Migration as e, fullCollectionSync as f, getAvailableCollectionNames as g, type MigrationStatus as h, isCollectionManaged as i, getLogger as j, initLogger as k, loadCollectionConfigs as l, type LogLevel as m, type LogCategory as n, type LogEntry as o, type LogFilter as p, PluginBootstrapService as q, registerCollections as r, syncCollections as s, schema as t, users as u, validateCollectionConfig as v, collections as w, content as x, contentVersions as y, media as z }; diff --git a/packages/core/dist/plugin-manager-Baa6xXqB.d.ts b/packages/core/dist/plugin-manager-Baa6xXqB.d.ts deleted file mode 100644 index c5503958c..000000000 --- a/packages/core/dist/plugin-manager-Baa6xXqB.d.ts +++ /dev/null @@ -1,328 +0,0 @@ -import { l as HookSystem, H as HookHandler, j as PluginHook, s as PluginValidator$1, P as Plugin, t as PluginValidationResult, m as PluginRegistry, b as PluginConfig, o as PluginStatus, n as PluginManager$1, a as PluginContext } from './plugin-zvZpaiP5.js'; -import { Hono } from 'hono'; - -/** - * Hook System Implementation - * - * Provides event-driven extensibility for plugins - */ - -declare class HookSystemImpl implements HookSystem { - private hooks; - private executing; - /** - * Register a hook handler - */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** - * Execute all handlers for a hook - */ - execute(hookName: string, data: any, context?: any): Promise; - /** - * Remove a hook handler - */ - unregister(hookName: string, handler: HookHandler): void; - /** - * Get all registered hooks for a name - */ - getHooks(hookName: string): PluginHook[]; - /** - * Get all registered hook names - */ - getHookNames(): string[]; - /** - * Get hook statistics - */ - getStats(): { - hookName: string; - handlerCount: number; - }[]; - /** - * Clear all hooks (useful for testing) - */ - clear(): void; - /** - * Create a scoped hook system for a plugin - */ - createScope(_pluginName: string): ScopedHookSystem; -} -/** - * Scoped hook system for individual plugins - */ -declare class ScopedHookSystem { - private parent; - private registeredHooks; - constructor(parent: HookSystemImpl); - /** - * Register a hook (scoped to this plugin) - */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** - * Execute a hook - */ - execute(hookName: string, data: any, context?: any): Promise; - /** - * Unregister a specific hook - */ - unregister(hookName: string, handler: HookHandler): void; - /** - * Unregister all hooks for this plugin - */ - unregisterAll(): void; - /** - * Get hooks registered by this plugin - */ - getRegisteredHooks(): { - hookName: string; - handler: HookHandler; - }[]; -} -/** - * Hook utilities - */ -declare class HookUtils { - /** - * Create a hook name with namespace - */ - static createHookName(namespace: string, event: string): string; - /** - * Parse a hook name to extract namespace and event - */ - static parseHookName(hookName: string): { - namespace: string; - event: string; - }; - /** - * Create a middleware that executes hooks - */ - static createHookMiddleware(hookSystem: HookSystem, beforeHook?: string, afterHook?: string): (c: any, next: any) => Promise; - /** - * Create a debounced hook handler - */ - static debounce(handler: HookHandler, delay: number): HookHandler; - /** - * Create a throttled hook handler - */ - static throttle(handler: HookHandler, limit: number): HookHandler; -} - -/** - * Plugin Validator - * - * Validates plugin definitions, dependencies, and compatibility - */ - -declare class PluginValidator implements PluginValidator$1 { - private static readonly RESERVED_NAMES; - private static readonly RESERVED_PATHS; - /** - * Validate plugin definition - */ - validate(plugin: Plugin): PluginValidationResult; - /** - * Validate plugin dependencies - */ - validateDependencies(plugin: Plugin, registry: PluginRegistry): PluginValidationResult; - /** - * Validate plugin compatibility with SonicJS version - */ - validateCompatibility(plugin: Plugin, sonicVersion: string): PluginValidationResult; - /** - * Check if two version ranges are compatible - */ - private isCompatible; - /** - * Validate plugin security constraints - */ - validateSecurity(plugin: Plugin): PluginValidationResult; -} - -/** - * Plugin Registry Implementation - * - * Manages plugin registration, activation, and lifecycle - */ - -declare class PluginRegistryImpl implements PluginRegistry { - private plugins; - private configs; - private statuses; - private validator; - constructor(validator?: PluginValidator); - /** - * Get plugin by name - */ - get(name: string): Plugin | undefined; - /** - * Get all registered plugins - */ - getAll(): Plugin[]; - /** - * Get active plugins - */ - getActive(): Plugin[]; - /** - * Register a plugin - */ - register(plugin: Plugin): Promise; - /** - * Unregister a plugin - */ - unregister(name: string): Promise; - /** - * Check if plugin is registered - */ - has(name: string): boolean; - /** - * Activate a plugin - */ - activate(name: string): Promise; - /** - * Deactivate a plugin - */ - deactivate(name: string): Promise; - /** - * Get plugin configuration - */ - getConfig(name: string): PluginConfig | undefined; - /** - * Set plugin configuration - */ - setConfig(name: string, config: PluginConfig): void; - /** - * Get plugin status - */ - getStatus(name: string): PluginStatus | undefined; - /** - * Get all plugin statuses - */ - getAllStatuses(): Map; - /** - * Update plugin status - */ - private updateStatus; - /** - * Get plugins that depend on the specified plugin - */ - private getDependents; - /** - * Get dependency graph - */ - getDependencyGraph(): Map; - /** - * Resolve plugin load order based on dependencies - */ - resolveLoadOrder(): string[]; - /** - * Export plugin configuration - */ - exportConfig(): { - plugins: PluginConfig[]; - }; - /** - * Import plugin configuration - */ - importConfig(config: { - plugins: PluginConfig[]; - }): void; - /** - * Clear all plugins (useful for testing) - */ - clear(): void; - /** - * Get registry statistics - */ - getStats(): { - total: number; - active: number; - inactive: number; - withErrors: number; - }; -} - -/** - * Plugin Manager - * - * Central orchestrator for the plugin system - */ - -declare class PluginManager implements PluginManager$1 { - readonly registry: PluginRegistry; - readonly hooks: HookSystem; - private validator; - private context?; - private scopedHooks; - private pluginRoutes; - constructor(); - /** - * Initialize plugin system - */ - initialize(context: PluginContext): Promise; - /** - * Load plugins from configuration - */ - loadPlugins(configs: PluginConfig[]): Promise; - /** - * Install a plugin - */ - install(plugin: Plugin, config?: PluginConfig): Promise; - /** - * Uninstall a plugin - */ - uninstall(name: string): Promise; - /** - * Get plugin status - */ - getStatus(name: string): PluginStatus; - /** - * Get all plugin statuses - */ - getAllStatuses(): PluginStatus[]; - /** - * Register plugin extensions (routes, middleware, etc.) - */ - private registerPluginExtensions; - /** - * Unregister plugin extensions - */ - private unregisterPluginExtensions; - /** - * Update plugin status - */ - private updatePluginStatus; - /** - * Create a logger for a plugin - */ - private createLogger; - /** - * Get plugin routes for mounting in main app - */ - getPluginRoutes(): Map; - /** - * Get plugin middleware for main app - */ - getPluginMiddleware(): Array<{ - name: string; - handler: any; - priority: number; - global: boolean; - }>; - /** - * Execute shutdown procedures - */ - shutdown(): Promise; - /** - * Get plugin system statistics - */ - getStats(): { - registry: ReturnType; - hooks: Array<{ - hookName: string; - handlerCount: number; - }>; - routes: number; - middleware: number; - }; -} - -export { HookSystemImpl as H, PluginRegistryImpl as P, ScopedHookSystem as S, HookUtils as a, PluginManager as b, PluginValidator as c }; diff --git a/packages/core/dist/plugin-manager-vBal9Zip.d.cts b/packages/core/dist/plugin-manager-vBal9Zip.d.cts deleted file mode 100644 index 4fb5b7aab..000000000 --- a/packages/core/dist/plugin-manager-vBal9Zip.d.cts +++ /dev/null @@ -1,328 +0,0 @@ -import { l as HookSystem, H as HookHandler, j as PluginHook, s as PluginValidator$1, P as Plugin, t as PluginValidationResult, m as PluginRegistry, b as PluginConfig, o as PluginStatus, n as PluginManager$1, a as PluginContext } from './plugin-zvZpaiP5.cjs'; -import { Hono } from 'hono'; - -/** - * Hook System Implementation - * - * Provides event-driven extensibility for plugins - */ - -declare class HookSystemImpl implements HookSystem { - private hooks; - private executing; - /** - * Register a hook handler - */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** - * Execute all handlers for a hook - */ - execute(hookName: string, data: any, context?: any): Promise; - /** - * Remove a hook handler - */ - unregister(hookName: string, handler: HookHandler): void; - /** - * Get all registered hooks for a name - */ - getHooks(hookName: string): PluginHook[]; - /** - * Get all registered hook names - */ - getHookNames(): string[]; - /** - * Get hook statistics - */ - getStats(): { - hookName: string; - handlerCount: number; - }[]; - /** - * Clear all hooks (useful for testing) - */ - clear(): void; - /** - * Create a scoped hook system for a plugin - */ - createScope(_pluginName: string): ScopedHookSystem; -} -/** - * Scoped hook system for individual plugins - */ -declare class ScopedHookSystem { - private parent; - private registeredHooks; - constructor(parent: HookSystemImpl); - /** - * Register a hook (scoped to this plugin) - */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** - * Execute a hook - */ - execute(hookName: string, data: any, context?: any): Promise; - /** - * Unregister a specific hook - */ - unregister(hookName: string, handler: HookHandler): void; - /** - * Unregister all hooks for this plugin - */ - unregisterAll(): void; - /** - * Get hooks registered by this plugin - */ - getRegisteredHooks(): { - hookName: string; - handler: HookHandler; - }[]; -} -/** - * Hook utilities - */ -declare class HookUtils { - /** - * Create a hook name with namespace - */ - static createHookName(namespace: string, event: string): string; - /** - * Parse a hook name to extract namespace and event - */ - static parseHookName(hookName: string): { - namespace: string; - event: string; - }; - /** - * Create a middleware that executes hooks - */ - static createHookMiddleware(hookSystem: HookSystem, beforeHook?: string, afterHook?: string): (c: any, next: any) => Promise; - /** - * Create a debounced hook handler - */ - static debounce(handler: HookHandler, delay: number): HookHandler; - /** - * Create a throttled hook handler - */ - static throttle(handler: HookHandler, limit: number): HookHandler; -} - -/** - * Plugin Validator - * - * Validates plugin definitions, dependencies, and compatibility - */ - -declare class PluginValidator implements PluginValidator$1 { - private static readonly RESERVED_NAMES; - private static readonly RESERVED_PATHS; - /** - * Validate plugin definition - */ - validate(plugin: Plugin): PluginValidationResult; - /** - * Validate plugin dependencies - */ - validateDependencies(plugin: Plugin, registry: PluginRegistry): PluginValidationResult; - /** - * Validate plugin compatibility with SonicJS version - */ - validateCompatibility(plugin: Plugin, sonicVersion: string): PluginValidationResult; - /** - * Check if two version ranges are compatible - */ - private isCompatible; - /** - * Validate plugin security constraints - */ - validateSecurity(plugin: Plugin): PluginValidationResult; -} - -/** - * Plugin Registry Implementation - * - * Manages plugin registration, activation, and lifecycle - */ - -declare class PluginRegistryImpl implements PluginRegistry { - private plugins; - private configs; - private statuses; - private validator; - constructor(validator?: PluginValidator); - /** - * Get plugin by name - */ - get(name: string): Plugin | undefined; - /** - * Get all registered plugins - */ - getAll(): Plugin[]; - /** - * Get active plugins - */ - getActive(): Plugin[]; - /** - * Register a plugin - */ - register(plugin: Plugin): Promise; - /** - * Unregister a plugin - */ - unregister(name: string): Promise; - /** - * Check if plugin is registered - */ - has(name: string): boolean; - /** - * Activate a plugin - */ - activate(name: string): Promise; - /** - * Deactivate a plugin - */ - deactivate(name: string): Promise; - /** - * Get plugin configuration - */ - getConfig(name: string): PluginConfig | undefined; - /** - * Set plugin configuration - */ - setConfig(name: string, config: PluginConfig): void; - /** - * Get plugin status - */ - getStatus(name: string): PluginStatus | undefined; - /** - * Get all plugin statuses - */ - getAllStatuses(): Map; - /** - * Update plugin status - */ - private updateStatus; - /** - * Get plugins that depend on the specified plugin - */ - private getDependents; - /** - * Get dependency graph - */ - getDependencyGraph(): Map; - /** - * Resolve plugin load order based on dependencies - */ - resolveLoadOrder(): string[]; - /** - * Export plugin configuration - */ - exportConfig(): { - plugins: PluginConfig[]; - }; - /** - * Import plugin configuration - */ - importConfig(config: { - plugins: PluginConfig[]; - }): void; - /** - * Clear all plugins (useful for testing) - */ - clear(): void; - /** - * Get registry statistics - */ - getStats(): { - total: number; - active: number; - inactive: number; - withErrors: number; - }; -} - -/** - * Plugin Manager - * - * Central orchestrator for the plugin system - */ - -declare class PluginManager implements PluginManager$1 { - readonly registry: PluginRegistry; - readonly hooks: HookSystem; - private validator; - private context?; - private scopedHooks; - private pluginRoutes; - constructor(); - /** - * Initialize plugin system - */ - initialize(context: PluginContext): Promise; - /** - * Load plugins from configuration - */ - loadPlugins(configs: PluginConfig[]): Promise; - /** - * Install a plugin - */ - install(plugin: Plugin, config?: PluginConfig): Promise; - /** - * Uninstall a plugin - */ - uninstall(name: string): Promise; - /** - * Get plugin status - */ - getStatus(name: string): PluginStatus; - /** - * Get all plugin statuses - */ - getAllStatuses(): PluginStatus[]; - /** - * Register plugin extensions (routes, middleware, etc.) - */ - private registerPluginExtensions; - /** - * Unregister plugin extensions - */ - private unregisterPluginExtensions; - /** - * Update plugin status - */ - private updatePluginStatus; - /** - * Create a logger for a plugin - */ - private createLogger; - /** - * Get plugin routes for mounting in main app - */ - getPluginRoutes(): Map; - /** - * Get plugin middleware for main app - */ - getPluginMiddleware(): Array<{ - name: string; - handler: any; - priority: number; - global: boolean; - }>; - /** - * Execute shutdown procedures - */ - shutdown(): Promise; - /** - * Get plugin system statistics - */ - getStats(): { - registry: ReturnType; - hooks: Array<{ - hookName: string; - handlerCount: number; - }>; - routes: number; - middleware: number; - }; -} - -export { HookSystemImpl as H, PluginRegistryImpl as P, ScopedHookSystem as S, HookUtils as a, PluginManager as b, PluginValidator as c }; diff --git a/packages/core/dist/plugin-manifest-Dpy8wxIB.d.cts b/packages/core/dist/plugin-manifest-Dpy8wxIB.d.cts deleted file mode 100644 index c792629c9..000000000 --- a/packages/core/dist/plugin-manifest-Dpy8wxIB.d.cts +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Plugin Manifest Types - * - * Defines the structure for plugin manifest.json files - */ -interface PluginManifest = Record> { - id: string; - name: string; - version: string; - description: string; - author: string; - homepage?: string; - repository?: string; - license?: string; - category: string; - tags?: string[]; - dependencies?: string[]; - settings?: Settings; - hooks?: Record; - routes?: Array<{ - path: string; - method: string; - handler: string; - description?: string; - }>; - permissions?: Record; - adminMenu?: { - label: string; - icon: string; - path: string; - order: number; - }; -} - -export type { PluginManifest as P }; diff --git a/packages/core/dist/plugin-manifest-Dpy8wxIB.d.ts b/packages/core/dist/plugin-manifest-Dpy8wxIB.d.ts deleted file mode 100644 index c792629c9..000000000 --- a/packages/core/dist/plugin-manifest-Dpy8wxIB.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Plugin Manifest Types - * - * Defines the structure for plugin manifest.json files - */ -interface PluginManifest = Record> { - id: string; - name: string; - version: string; - description: string; - author: string; - homepage?: string; - repository?: string; - license?: string; - category: string; - tags?: string[]; - dependencies?: string[]; - settings?: Settings; - hooks?: Record; - routes?: Array<{ - path: string; - method: string; - handler: string; - description?: string; - }>; - permissions?: Record; - adminMenu?: { - label: string; - icon: string; - path: string; - order: number; - }; -} - -export type { PluginManifest as P }; diff --git a/packages/core/dist/plugin-zvZpaiP5.d.cts b/packages/core/dist/plugin-zvZpaiP5.d.cts deleted file mode 100644 index 21650d3ab..000000000 --- a/packages/core/dist/plugin-zvZpaiP5.d.cts +++ /dev/null @@ -1,357 +0,0 @@ -import { Context, MiddlewareHandler, Hono } from 'hono'; -import { z } from 'zod'; -import { D1Database, KVNamespace, R2Bucket } from '@cloudflare/workers-types'; - -/** - * SonicJS Plugin System Types - * - * Defines the core interfaces and types for the plugin system - */ - -interface Plugin { - /** Unique plugin identifier */ - name: string; - /** Plugin version (semantic versioning) */ - version: string; - /** Human-readable description */ - description?: string; - /** Plugin author information */ - author?: { - name: string; - email?: string; - url?: string; - }; - /** Plugin dependencies (other plugins required) */ - dependencies?: string[]; - /** SonicJS version compatibility */ - compatibility?: string; - /** Plugin license */ - license?: string; - routes?: PluginRoutes[]; - middleware?: PluginMiddleware[]; - models?: PluginModel[]; - services?: PluginService[]; - adminPages?: PluginAdminPage[]; - adminComponents?: PluginComponent[]; - menuItems?: PluginMenuItem[]; - hooks?: PluginHook[]; - install?: (context: PluginContext) => Promise; - uninstall?: (context: PluginContext) => Promise; - activate?: (context: PluginContext) => Promise; - deactivate?: (context: PluginContext) => Promise; - configure?: (config: PluginConfig) => Promise; -} -interface PluginContext { - /** Database instance */ - db: D1Database; - /** Key-value storage */ - kv: KVNamespace; - /** R2 storage bucket */ - r2?: R2Bucket; - /** Plugin configuration */ - config: PluginConfig; - /** Core SonicJS services */ - services: { - auth: AuthService; - content: ContentService; - media: MediaService; - }; - /** Hook system for inter-plugin communication */ - hooks: HookSystem | ScopedHookSystem; - /** Logging utilities */ - logger: PluginLogger; -} -interface PluginConfig { - /** Plugin-specific configuration */ - [key: string]: any; - /** Whether plugin is enabled */ - enabled: boolean; - /** Plugin installation timestamp */ - installedAt?: number; - /** Plugin last update timestamp */ - updatedAt?: number; -} -interface PluginRoutes { - /** Route path prefix */ - path: string; - /** Hono route handler */ - handler: Hono; - /** Route description */ - description?: string; - /** Whether route requires authentication */ - requiresAuth?: boolean; - /** Required roles for access */ - roles?: string[]; - /** Route priority (for ordering) */ - priority?: number; -} -interface PluginMiddleware { - /** Middleware name */ - name: string; - /** Middleware handler function */ - handler: MiddlewareHandler; - /** Middleware description */ - description?: string; - /** Middleware priority (lower = earlier) */ - priority?: number; - /** Routes to apply middleware to */ - routes?: string[]; - /** Whether to apply globally */ - global?: boolean; -} -interface PluginModel { - /** Model name */ - name: string; - /** Database table name */ - tableName: string; - /** Zod schema for validation */ - schema: z.ZodSchema; - /** Database migrations */ - migrations: string[]; - /** Model relationships */ - relationships?: ModelRelationship[]; - /** Whether model extends core content */ - extendsContent?: boolean; -} -interface ModelRelationship { - type: 'oneToOne' | 'oneToMany' | 'manyToMany'; - target: string; - foreignKey?: string; - joinTable?: string; -} -interface PluginService { - /** Service name */ - name: string; - /** Service implementation */ - implementation: any; - /** Service description */ - description?: string; - /** Service dependencies */ - dependencies?: string[]; - /** Whether service is singleton */ - singleton?: boolean; -} -interface PluginAdminPage { - /** Page path (relative to /admin) */ - path: string; - /** Page title */ - title: string; - /** Page component/template */ - component: string; - /** Page description */ - description?: string; - /** Required permissions */ - permissions?: string[]; - /** Menu item configuration */ - menuItem?: PluginMenuItem; - /** Page icon */ - icon?: string; -} -interface PluginComponent { - /** Component name */ - name: string; - /** Component template function */ - template: (props: any) => string; - /** Component description */ - description?: string; - /** Component props schema */ - propsSchema?: z.ZodSchema; -} -interface PluginMenuItem { - /** Menu item label */ - label: string; - /** Menu item path */ - path: string; - /** Menu item icon */ - icon?: string; - /** Menu item order */ - order?: number; - /** Parent menu item */ - parent?: string; - /** Required permissions */ - permissions?: string[]; - /** Whether item is active */ - active?: boolean; -} -interface PluginHook { - /** Hook name */ - name: string; - /** Hook handler function */ - handler: HookHandler; - /** Hook priority */ - priority?: number; - /** Hook description */ - description?: string; -} -type HookHandler = (data: any, context: HookContext) => Promise; -interface HookContext { - /** Plugin that registered the hook */ - plugin: string; - /** Hook execution context */ - context: PluginContext; - /** Cancel hook execution */ - cancel?: () => void; -} -interface HookSystem { - /** Register a hook handler */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** Execute all handlers for a hook */ - execute(hookName: string, data: any, context?: any): Promise; - /** Remove a hook handler */ - unregister(hookName: string, handler: HookHandler): void; - /** Get all registered hooks */ - getHooks(hookName: string): PluginHook[]; - /** Create a scoped hook system (optional) */ - createScope?(pluginName: string): ScopedHookSystem; -} -interface ScopedHookSystem { - /** Register a hook handler */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** Execute all handlers for a hook */ - execute(hookName: string, data: any, context?: any): Promise; - /** Remove a hook handler */ - unregister(hookName: string, handler: HookHandler): void; - /** Remove all hooks for this scope */ - unregisterAll(): void; -} -interface PluginRegistry { - /** Get plugin by name */ - get(name: string): Plugin | undefined; - /** Get all registered plugins */ - getAll(): Plugin[]; - /** Get active plugins */ - getActive(): Plugin[]; - /** Register a plugin */ - register(plugin: Plugin): Promise; - /** Unregister a plugin */ - unregister(name: string): Promise; - /** Check if plugin is registered */ - has(name: string): boolean; - /** Activate a plugin */ - activate(name: string): Promise; - /** Deactivate a plugin */ - deactivate(name: string): Promise; - /** Get plugin configuration */ - getConfig(name: string): PluginConfig | undefined; - /** Set plugin configuration */ - setConfig(name: string, config: PluginConfig): void; - /** Get plugin status */ - getStatus(name: string): PluginStatus | undefined; - /** Get all plugin statuses */ - getAllStatuses(): Map; - /** Resolve plugin load order based on dependencies */ - resolveLoadOrder(): string[]; -} -interface PluginManager { - /** Plugin registry */ - registry: PluginRegistry; - /** Hook system */ - hooks: HookSystem; - /** Initialize plugin system */ - initialize(context: PluginContext): Promise; - /** Load plugins from configuration */ - loadPlugins(config: PluginConfig[]): Promise; - /** Install a plugin */ - install(plugin: Plugin, config?: PluginConfig): Promise; - /** Uninstall a plugin */ - uninstall(name: string): Promise; - /** Get plugin status */ - getStatus(name: string): PluginStatus; -} -interface PluginStatus { - name: string; - version: string; - active: boolean; - installed: boolean; - hasErrors: boolean; - errors?: string[]; - lastError?: string; -} -interface AuthService { - /** Verify user permissions */ - hasPermission(userId: string, permission: string): Promise; - /** Get current user */ - getCurrentUser(context: Context): Promise; - /** Create authentication middleware */ - createMiddleware(options?: any): MiddlewareHandler; -} -interface ContentService { - /** Get content by ID */ - getById(id: string): Promise; - /** Create new content */ - create(data: any): Promise; - /** Update content */ - update(id: string, data: any): Promise; - /** Delete content */ - delete(id: string): Promise; - /** Search content */ - search(query: string, options?: any): Promise; -} -interface MediaService { - /** Upload file */ - upload(file: File, options?: any): Promise; - /** Get media by ID */ - getById(id: string): Promise; - /** Delete media */ - delete(id: string): Promise; - /** Transform image */ - transform(id: string, options: any): Promise; -} -interface PluginLogger { - debug(message: string, data?: any): void; - info(message: string, data?: any): void; - warn(message: string, data?: any): void; - error(message: string, error?: Error, data?: any): void; -} -interface PluginBuilderOptions { - name: string; - version: string; - description?: string; - author?: Plugin['author']; - dependencies?: string[]; -} -interface PluginValidator { - /** Validate plugin definition */ - validate(plugin: Plugin): PluginValidationResult; - /** Validate plugin dependencies */ - validateDependencies(plugin: Plugin, registry: PluginRegistry): PluginValidationResult; - /** Validate plugin compatibility */ - validateCompatibility(plugin: Plugin, version: string): PluginValidationResult; -} -interface PluginValidationResult { - valid: boolean; - errors: string[]; - warnings: string[]; -} -declare const HOOKS: { - readonly APP_INIT: "app:init"; - readonly APP_READY: "app:ready"; - readonly APP_SHUTDOWN: "app:shutdown"; - readonly REQUEST_START: "request:start"; - readonly REQUEST_END: "request:end"; - readonly REQUEST_ERROR: "request:error"; - readonly AUTH_LOGIN: "auth:login"; - readonly AUTH_LOGOUT: "auth:logout"; - readonly AUTH_REGISTER: "auth:register"; - readonly USER_LOGIN: "user:login"; - readonly USER_LOGOUT: "user:logout"; - readonly CONTENT_CREATE: "content:create"; - readonly CONTENT_UPDATE: "content:update"; - readonly CONTENT_DELETE: "content:delete"; - readonly CONTENT_PUBLISH: "content:publish"; - readonly CONTENT_SAVE: "content:save"; - readonly MEDIA_UPLOAD: "media:upload"; - readonly MEDIA_DELETE: "media:delete"; - readonly MEDIA_TRANSFORM: "media:transform"; - readonly PLUGIN_INSTALL: "plugin:install"; - readonly PLUGIN_UNINSTALL: "plugin:uninstall"; - readonly PLUGIN_ACTIVATE: "plugin:activate"; - readonly PLUGIN_DEACTIVATE: "plugin:deactivate"; - readonly ADMIN_MENU_RENDER: "admin:menu:render"; - readonly ADMIN_PAGE_RENDER: "admin:page:render"; - readonly DB_MIGRATE: "db:migrate"; - readonly DB_SEED: "db:seed"; -}; -type HookName = typeof HOOKS[keyof typeof HOOKS]; - -export { type AuthService as A, type ContentService as C, type HookHandler as H, type ModelRelationship as M, type Plugin as P, type ScopedHookSystem as S, type PluginContext as a, type PluginConfig as b, type PluginRoutes as c, type PluginMiddleware as d, type PluginModel as e, type PluginService as f, type PluginAdminPage as g, type PluginComponent as h, type PluginMenuItem as i, type PluginHook as j, type HookContext as k, type HookSystem as l, type PluginRegistry as m, type PluginManager as n, type PluginStatus as o, type MediaService as p, type PluginLogger as q, type PluginBuilderOptions as r, type PluginValidator as s, type PluginValidationResult as t, type HookName as u, HOOKS as v }; diff --git a/packages/core/dist/plugin-zvZpaiP5.d.ts b/packages/core/dist/plugin-zvZpaiP5.d.ts deleted file mode 100644 index 21650d3ab..000000000 --- a/packages/core/dist/plugin-zvZpaiP5.d.ts +++ /dev/null @@ -1,357 +0,0 @@ -import { Context, MiddlewareHandler, Hono } from 'hono'; -import { z } from 'zod'; -import { D1Database, KVNamespace, R2Bucket } from '@cloudflare/workers-types'; - -/** - * SonicJS Plugin System Types - * - * Defines the core interfaces and types for the plugin system - */ - -interface Plugin { - /** Unique plugin identifier */ - name: string; - /** Plugin version (semantic versioning) */ - version: string; - /** Human-readable description */ - description?: string; - /** Plugin author information */ - author?: { - name: string; - email?: string; - url?: string; - }; - /** Plugin dependencies (other plugins required) */ - dependencies?: string[]; - /** SonicJS version compatibility */ - compatibility?: string; - /** Plugin license */ - license?: string; - routes?: PluginRoutes[]; - middleware?: PluginMiddleware[]; - models?: PluginModel[]; - services?: PluginService[]; - adminPages?: PluginAdminPage[]; - adminComponents?: PluginComponent[]; - menuItems?: PluginMenuItem[]; - hooks?: PluginHook[]; - install?: (context: PluginContext) => Promise; - uninstall?: (context: PluginContext) => Promise; - activate?: (context: PluginContext) => Promise; - deactivate?: (context: PluginContext) => Promise; - configure?: (config: PluginConfig) => Promise; -} -interface PluginContext { - /** Database instance */ - db: D1Database; - /** Key-value storage */ - kv: KVNamespace; - /** R2 storage bucket */ - r2?: R2Bucket; - /** Plugin configuration */ - config: PluginConfig; - /** Core SonicJS services */ - services: { - auth: AuthService; - content: ContentService; - media: MediaService; - }; - /** Hook system for inter-plugin communication */ - hooks: HookSystem | ScopedHookSystem; - /** Logging utilities */ - logger: PluginLogger; -} -interface PluginConfig { - /** Plugin-specific configuration */ - [key: string]: any; - /** Whether plugin is enabled */ - enabled: boolean; - /** Plugin installation timestamp */ - installedAt?: number; - /** Plugin last update timestamp */ - updatedAt?: number; -} -interface PluginRoutes { - /** Route path prefix */ - path: string; - /** Hono route handler */ - handler: Hono; - /** Route description */ - description?: string; - /** Whether route requires authentication */ - requiresAuth?: boolean; - /** Required roles for access */ - roles?: string[]; - /** Route priority (for ordering) */ - priority?: number; -} -interface PluginMiddleware { - /** Middleware name */ - name: string; - /** Middleware handler function */ - handler: MiddlewareHandler; - /** Middleware description */ - description?: string; - /** Middleware priority (lower = earlier) */ - priority?: number; - /** Routes to apply middleware to */ - routes?: string[]; - /** Whether to apply globally */ - global?: boolean; -} -interface PluginModel { - /** Model name */ - name: string; - /** Database table name */ - tableName: string; - /** Zod schema for validation */ - schema: z.ZodSchema; - /** Database migrations */ - migrations: string[]; - /** Model relationships */ - relationships?: ModelRelationship[]; - /** Whether model extends core content */ - extendsContent?: boolean; -} -interface ModelRelationship { - type: 'oneToOne' | 'oneToMany' | 'manyToMany'; - target: string; - foreignKey?: string; - joinTable?: string; -} -interface PluginService { - /** Service name */ - name: string; - /** Service implementation */ - implementation: any; - /** Service description */ - description?: string; - /** Service dependencies */ - dependencies?: string[]; - /** Whether service is singleton */ - singleton?: boolean; -} -interface PluginAdminPage { - /** Page path (relative to /admin) */ - path: string; - /** Page title */ - title: string; - /** Page component/template */ - component: string; - /** Page description */ - description?: string; - /** Required permissions */ - permissions?: string[]; - /** Menu item configuration */ - menuItem?: PluginMenuItem; - /** Page icon */ - icon?: string; -} -interface PluginComponent { - /** Component name */ - name: string; - /** Component template function */ - template: (props: any) => string; - /** Component description */ - description?: string; - /** Component props schema */ - propsSchema?: z.ZodSchema; -} -interface PluginMenuItem { - /** Menu item label */ - label: string; - /** Menu item path */ - path: string; - /** Menu item icon */ - icon?: string; - /** Menu item order */ - order?: number; - /** Parent menu item */ - parent?: string; - /** Required permissions */ - permissions?: string[]; - /** Whether item is active */ - active?: boolean; -} -interface PluginHook { - /** Hook name */ - name: string; - /** Hook handler function */ - handler: HookHandler; - /** Hook priority */ - priority?: number; - /** Hook description */ - description?: string; -} -type HookHandler = (data: any, context: HookContext) => Promise; -interface HookContext { - /** Plugin that registered the hook */ - plugin: string; - /** Hook execution context */ - context: PluginContext; - /** Cancel hook execution */ - cancel?: () => void; -} -interface HookSystem { - /** Register a hook handler */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** Execute all handlers for a hook */ - execute(hookName: string, data: any, context?: any): Promise; - /** Remove a hook handler */ - unregister(hookName: string, handler: HookHandler): void; - /** Get all registered hooks */ - getHooks(hookName: string): PluginHook[]; - /** Create a scoped hook system (optional) */ - createScope?(pluginName: string): ScopedHookSystem; -} -interface ScopedHookSystem { - /** Register a hook handler */ - register(hookName: string, handler: HookHandler, priority?: number): void; - /** Execute all handlers for a hook */ - execute(hookName: string, data: any, context?: any): Promise; - /** Remove a hook handler */ - unregister(hookName: string, handler: HookHandler): void; - /** Remove all hooks for this scope */ - unregisterAll(): void; -} -interface PluginRegistry { - /** Get plugin by name */ - get(name: string): Plugin | undefined; - /** Get all registered plugins */ - getAll(): Plugin[]; - /** Get active plugins */ - getActive(): Plugin[]; - /** Register a plugin */ - register(plugin: Plugin): Promise; - /** Unregister a plugin */ - unregister(name: string): Promise; - /** Check if plugin is registered */ - has(name: string): boolean; - /** Activate a plugin */ - activate(name: string): Promise; - /** Deactivate a plugin */ - deactivate(name: string): Promise; - /** Get plugin configuration */ - getConfig(name: string): PluginConfig | undefined; - /** Set plugin configuration */ - setConfig(name: string, config: PluginConfig): void; - /** Get plugin status */ - getStatus(name: string): PluginStatus | undefined; - /** Get all plugin statuses */ - getAllStatuses(): Map; - /** Resolve plugin load order based on dependencies */ - resolveLoadOrder(): string[]; -} -interface PluginManager { - /** Plugin registry */ - registry: PluginRegistry; - /** Hook system */ - hooks: HookSystem; - /** Initialize plugin system */ - initialize(context: PluginContext): Promise; - /** Load plugins from configuration */ - loadPlugins(config: PluginConfig[]): Promise; - /** Install a plugin */ - install(plugin: Plugin, config?: PluginConfig): Promise; - /** Uninstall a plugin */ - uninstall(name: string): Promise; - /** Get plugin status */ - getStatus(name: string): PluginStatus; -} -interface PluginStatus { - name: string; - version: string; - active: boolean; - installed: boolean; - hasErrors: boolean; - errors?: string[]; - lastError?: string; -} -interface AuthService { - /** Verify user permissions */ - hasPermission(userId: string, permission: string): Promise; - /** Get current user */ - getCurrentUser(context: Context): Promise; - /** Create authentication middleware */ - createMiddleware(options?: any): MiddlewareHandler; -} -interface ContentService { - /** Get content by ID */ - getById(id: string): Promise; - /** Create new content */ - create(data: any): Promise; - /** Update content */ - update(id: string, data: any): Promise; - /** Delete content */ - delete(id: string): Promise; - /** Search content */ - search(query: string, options?: any): Promise; -} -interface MediaService { - /** Upload file */ - upload(file: File, options?: any): Promise; - /** Get media by ID */ - getById(id: string): Promise; - /** Delete media */ - delete(id: string): Promise; - /** Transform image */ - transform(id: string, options: any): Promise; -} -interface PluginLogger { - debug(message: string, data?: any): void; - info(message: string, data?: any): void; - warn(message: string, data?: any): void; - error(message: string, error?: Error, data?: any): void; -} -interface PluginBuilderOptions { - name: string; - version: string; - description?: string; - author?: Plugin['author']; - dependencies?: string[]; -} -interface PluginValidator { - /** Validate plugin definition */ - validate(plugin: Plugin): PluginValidationResult; - /** Validate plugin dependencies */ - validateDependencies(plugin: Plugin, registry: PluginRegistry): PluginValidationResult; - /** Validate plugin compatibility */ - validateCompatibility(plugin: Plugin, version: string): PluginValidationResult; -} -interface PluginValidationResult { - valid: boolean; - errors: string[]; - warnings: string[]; -} -declare const HOOKS: { - readonly APP_INIT: "app:init"; - readonly APP_READY: "app:ready"; - readonly APP_SHUTDOWN: "app:shutdown"; - readonly REQUEST_START: "request:start"; - readonly REQUEST_END: "request:end"; - readonly REQUEST_ERROR: "request:error"; - readonly AUTH_LOGIN: "auth:login"; - readonly AUTH_LOGOUT: "auth:logout"; - readonly AUTH_REGISTER: "auth:register"; - readonly USER_LOGIN: "user:login"; - readonly USER_LOGOUT: "user:logout"; - readonly CONTENT_CREATE: "content:create"; - readonly CONTENT_UPDATE: "content:update"; - readonly CONTENT_DELETE: "content:delete"; - readonly CONTENT_PUBLISH: "content:publish"; - readonly CONTENT_SAVE: "content:save"; - readonly MEDIA_UPLOAD: "media:upload"; - readonly MEDIA_DELETE: "media:delete"; - readonly MEDIA_TRANSFORM: "media:transform"; - readonly PLUGIN_INSTALL: "plugin:install"; - readonly PLUGIN_UNINSTALL: "plugin:uninstall"; - readonly PLUGIN_ACTIVATE: "plugin:activate"; - readonly PLUGIN_DEACTIVATE: "plugin:deactivate"; - readonly ADMIN_MENU_RENDER: "admin:menu:render"; - readonly ADMIN_PAGE_RENDER: "admin:page:render"; - readonly DB_MIGRATE: "db:migrate"; - readonly DB_SEED: "db:seed"; -}; -type HookName = typeof HOOKS[keyof typeof HOOKS]; - -export { type AuthService as A, type ContentService as C, type HookHandler as H, type ModelRelationship as M, type Plugin as P, type ScopedHookSystem as S, type PluginContext as a, type PluginConfig as b, type PluginRoutes as c, type PluginMiddleware as d, type PluginModel as e, type PluginService as f, type PluginAdminPage as g, type PluginComponent as h, type PluginMenuItem as i, type PluginHook as j, type HookContext as k, type HookSystem as l, type PluginRegistry as m, type PluginManager as n, type PluginStatus as o, type MediaService as p, type PluginLogger as q, type PluginBuilderOptions as r, type PluginValidator as s, type PluginValidationResult as t, type HookName as u, HOOKS as v }; diff --git a/packages/core/dist/plugins.cjs b/packages/core/dist/plugins.cjs deleted file mode 100644 index 7ac9da02e..000000000 --- a/packages/core/dist/plugins.cjs +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -var chunkMNFY6DWY_cjs = require('./chunk-MNFY6DWY.cjs'); -var chunk6FHNRRJ3_cjs = require('./chunk-6FHNRRJ3.cjs'); -require('./chunk-KYGRJCZM.cjs'); -require('./chunk-IGJUBJBW.cjs'); - - - -Object.defineProperty(exports, "HookSystemImpl", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.HookSystemImpl; } -}); -Object.defineProperty(exports, "HookUtils", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.HookUtils; } -}); -Object.defineProperty(exports, "PluginManager", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.PluginManager; } -}); -Object.defineProperty(exports, "PluginRegistryImpl", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.PluginRegistryImpl; } -}); -Object.defineProperty(exports, "PluginValidator", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.PluginValidator; } -}); -Object.defineProperty(exports, "ScopedHookSystem", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.ScopedHookSystem; } -}); -Object.defineProperty(exports, "createTurnstileMiddleware", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.createTurnstileMiddleware; } -}); -Object.defineProperty(exports, "verifyTurnstile", { - enumerable: true, - get: function () { return chunkMNFY6DWY_cjs.verifyTurnstile; } -}); -Object.defineProperty(exports, "TurnstileService", { - enumerable: true, - get: function () { return chunk6FHNRRJ3_cjs.TurnstileService; } -}); -//# sourceMappingURL=plugins.cjs.map -//# sourceMappingURL=plugins.cjs.map \ No newline at end of file diff --git a/packages/core/dist/plugins.d.cts b/packages/core/dist/plugins.d.cts deleted file mode 100644 index a6712e783..000000000 --- a/packages/core/dist/plugins.d.cts +++ /dev/null @@ -1,73 +0,0 @@ -export { H as HookSystemImpl, a as HookUtils, b as PluginManager, P as PluginRegistryImpl, c as PluginValidator, S as ScopedHookSystem } from './plugin-manager-vBal9Zip.cjs'; -import { D1Database } from '@cloudflare/workers-types'; -import * as hono from 'hono'; -import { Context, Next } from 'hono'; -import './plugin-zvZpaiP5.cjs'; -import 'zod'; - -interface TurnstileSettings { - siteKey: string; - secretKey: string; - theme?: 'light' | 'dark' | 'auto'; - size?: 'normal' | 'compact'; - mode?: 'managed' | 'non-interactive' | 'invisible'; - appearance?: 'always' | 'execute' | 'interaction-only'; - preClearance?: boolean; - preClearanceLevel?: 'interactive' | 'managed' | 'non-interactive'; - enabled: boolean; -} -declare class TurnstileService { - private db; - private readonly VERIFY_URL; - constructor(db: D1Database); - /** - * Get Turnstile settings from database - */ - getSettings(): Promise; - /** - * Verify a Turnstile token with Cloudflare - */ - verifyToken(token: string, remoteIp?: string): Promise<{ - success: boolean; - error?: string; - }>; - /** - * Save Turnstile settings to database - */ - saveSettings(settings: TurnstileSettings): Promise; - /** - * Check if Turnstile is enabled - */ - isEnabled(): Promise; -} - -/** - * Middleware to verify Turnstile token on form submissions - * - * Usage: - * ```typescript - * import { verifyTurnstile } from '@sonicjs-cms/core/plugins' - * - * app.post('/api/contact', verifyTurnstile, async (c) => { - * // Token already verified, process form... - * }) - * ``` - */ -declare function verifyTurnstile(c: Context, next: Next): Promise) | (Response & hono.TypedResponse<{ - error: string; - message: string; -}, 400, "json">) | (Response & hono.TypedResponse<{ - error: string; - message: string; -}, 403, "json">)>; -/** - * Middleware factory that allows custom error handling - */ -declare function createTurnstileMiddleware(options?: { - onError?: (c: Context, error: string) => Response; - onMissing?: (c: Context) => Response; -}): (c: Context, next: Next) => Promise; - -export { TurnstileService, createTurnstileMiddleware, verifyTurnstile }; diff --git a/packages/core/dist/plugins.d.ts b/packages/core/dist/plugins.d.ts deleted file mode 100644 index 9ea848d64..000000000 --- a/packages/core/dist/plugins.d.ts +++ /dev/null @@ -1,73 +0,0 @@ -export { H as HookSystemImpl, a as HookUtils, b as PluginManager, P as PluginRegistryImpl, c as PluginValidator, S as ScopedHookSystem } from './plugin-manager-Baa6xXqB.js'; -import { D1Database } from '@cloudflare/workers-types'; -import * as hono from 'hono'; -import { Context, Next } from 'hono'; -import './plugin-zvZpaiP5.js'; -import 'zod'; - -interface TurnstileSettings { - siteKey: string; - secretKey: string; - theme?: 'light' | 'dark' | 'auto'; - size?: 'normal' | 'compact'; - mode?: 'managed' | 'non-interactive' | 'invisible'; - appearance?: 'always' | 'execute' | 'interaction-only'; - preClearance?: boolean; - preClearanceLevel?: 'interactive' | 'managed' | 'non-interactive'; - enabled: boolean; -} -declare class TurnstileService { - private db; - private readonly VERIFY_URL; - constructor(db: D1Database); - /** - * Get Turnstile settings from database - */ - getSettings(): Promise; - /** - * Verify a Turnstile token with Cloudflare - */ - verifyToken(token: string, remoteIp?: string): Promise<{ - success: boolean; - error?: string; - }>; - /** - * Save Turnstile settings to database - */ - saveSettings(settings: TurnstileSettings): Promise; - /** - * Check if Turnstile is enabled - */ - isEnabled(): Promise; -} - -/** - * Middleware to verify Turnstile token on form submissions - * - * Usage: - * ```typescript - * import { verifyTurnstile } from '@sonicjs-cms/core/plugins' - * - * app.post('/api/contact', verifyTurnstile, async (c) => { - * // Token already verified, process form... - * }) - * ``` - */ -declare function verifyTurnstile(c: Context, next: Next): Promise) | (Response & hono.TypedResponse<{ - error: string; - message: string; -}, 400, "json">) | (Response & hono.TypedResponse<{ - error: string; - message: string; -}, 403, "json">)>; -/** - * Middleware factory that allows custom error handling - */ -declare function createTurnstileMiddleware(options?: { - onError?: (c: Context, error: string) => Response; - onMissing?: (c: Context) => Response; -}): (c: Context, next: Next) => Promise; - -export { TurnstileService, createTurnstileMiddleware, verifyTurnstile }; diff --git a/packages/core/dist/routes.cjs b/packages/core/dist/routes.cjs deleted file mode 100644 index f0d610ef4..000000000 --- a/packages/core/dist/routes.cjs +++ /dev/null @@ -1,110 +0,0 @@ -'use strict'; - -var chunkVAPDSKKV_cjs = require('./chunk-VAPDSKKV.cjs'); -require('./chunk-VNLR35GO.cjs'); -require('./chunk-DVQA5II3.cjs'); -require('./chunk-MPT5PA6U.cjs'); -require('./chunk-FQSMNIY2.cjs'); -require('./chunk-SHCYIZAN.cjs'); -require('./chunk-6FHNRRJ3.cjs'); -require('./chunk-5HMR2SJW.cjs'); -require('./chunk-P3XDZL6Q.cjs'); -require('./chunk-RCQ2HIQD.cjs'); -require('./chunk-IGJUBJBW.cjs'); - - - -Object.defineProperty(exports, "ROUTES_INFO", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.ROUTES_INFO; } -}); -Object.defineProperty(exports, "adminApiReferenceRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.router2; } -}); -Object.defineProperty(exports, "adminApiRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.admin_api_default; } -}); -Object.defineProperty(exports, "adminCheckboxRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminCheckboxRoutes; } -}); -Object.defineProperty(exports, "adminCodeExamplesRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.admin_code_examples_default; } -}); -Object.defineProperty(exports, "adminCollectionsRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminCollectionsRoutes; } -}); -Object.defineProperty(exports, "adminContentRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.admin_content_default; } -}); -Object.defineProperty(exports, "adminDashboardRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.router; } -}); -Object.defineProperty(exports, "adminDesignRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminDesignRoutes; } -}); -Object.defineProperty(exports, "adminFormsRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminFormsRoutes; } -}); -Object.defineProperty(exports, "adminLogsRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminLogsRoutes; } -}); -Object.defineProperty(exports, "adminMediaRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminMediaRoutes; } -}); -Object.defineProperty(exports, "adminPluginRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminPluginRoutes; } -}); -Object.defineProperty(exports, "adminSettingsRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.adminSettingsRoutes; } -}); -Object.defineProperty(exports, "adminTestimonialsRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.admin_testimonials_default; } -}); -Object.defineProperty(exports, "adminUsersRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.userRoutes; } -}); -Object.defineProperty(exports, "apiContentCrudRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.api_content_crud_default; } -}); -Object.defineProperty(exports, "apiMediaRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.api_media_default; } -}); -Object.defineProperty(exports, "apiRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.api_default; } -}); -Object.defineProperty(exports, "apiSystemRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.api_system_default; } -}); -Object.defineProperty(exports, "authRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.auth_default; } -}); -Object.defineProperty(exports, "publicFormsRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.public_forms_default; } -}); -Object.defineProperty(exports, "testCleanupRoutes", { - enumerable: true, - get: function () { return chunkVAPDSKKV_cjs.test_cleanup_default; } -}); -//# sourceMappingURL=routes.cjs.map -//# sourceMappingURL=routes.cjs.map \ No newline at end of file diff --git a/packages/core/dist/routes.d.cts b/packages/core/dist/routes.d.cts deleted file mode 100644 index 3963d3ed6..000000000 --- a/packages/core/dist/routes.d.cts +++ /dev/null @@ -1,297 +0,0 @@ -import * as hono_types from 'hono/types'; -import { Hono } from 'hono'; -import { B as Bindings$a, V as Variables$b } from './app-CYEm1ytG.cjs'; -import { D1Database as D1Database$1, KVNamespace as KVNamespace$1, R2Bucket as R2Bucket$1 } from '@cloudflare/workers-types'; - -interface Variables$a extends Variables$b { - startTime: number; - cacheEnabled?: boolean; -} -declare const apiRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$a; -}, hono_types.BlankSchema, "/">; - -declare const apiContentCrudRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const apiMediaRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const apiSystemRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const adminApiRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const authRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const app: Hono; - -declare const adminContentRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const userRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const adminMediaRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const adminPluginRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const adminLogsRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -type Bindings$9 = { - DB: D1Database; - KV: KVNamespace; -}; -type Variables$9 = { - user: { - userId: string; - email: string; - role: string; - }; -}; -declare const adminDesignRoutes: Hono<{ - Bindings: Bindings$9; - Variables: Variables$9; -}, hono_types.BlankSchema, "/">; - -type Bindings$8 = { - DB: D1Database; - KV: KVNamespace; -}; -type Variables$8 = { - user: { - userId: string; - email: string; - role: string; - }; -}; -declare const adminCheckboxRoutes: Hono<{ - Bindings: Bindings$8; - Variables: Variables$8; -}, hono_types.BlankSchema, "/">; - -type Bindings$7 = { - DB: D1Database; - KV: KVNamespace; -}; -type Variables$7 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; -}; -declare const adminTestimonialsRoutes: Hono<{ - Bindings: Bindings$7; - Variables: Variables$7; -}, hono_types.BlankSchema, "/">; - -type Bindings$6 = { - DB: D1Database; - KV: KVNamespace; -}; -type Variables$6 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; -}; -declare const adminCodeExamplesRoutes: Hono<{ - Bindings: Bindings$6; - Variables: Variables$6; -}, hono_types.BlankSchema, "/">; - -type Bindings$5 = { - DB: D1Database$1; - CACHE_KV: KVNamespace$1; - MEDIA_BUCKET: R2Bucket$1; -}; -type Variables$5 = { - user?: { - userId: string; - email: string; - role: string; - }; -}; -declare const router$1: Hono<{ - Bindings: Bindings$5; - Variables: Variables$5; -}, hono_types.BlankSchema, "/">; - -type Bindings$4 = { - DB: D1Database; - CACHE_KV: KVNamespace; - MEDIA_BUCKET: R2Bucket; - ASSETS: Fetcher; - EMAIL_QUEUE?: Queue; - SENDGRID_API_KEY?: string; - DEFAULT_FROM_EMAIL?: string; - IMAGES_ACCOUNT_ID?: string; - IMAGES_API_TOKEN?: string; - ENVIRONMENT?: string; -}; -type Variables$4 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; - requestId?: string; - startTime?: number; - appVersion?: string; -}; -declare const adminCollectionsRoutes: Hono<{ - Bindings: Bindings$4; - Variables: Variables$4; -}, hono_types.BlankSchema, "/">; - -type Bindings$3 = { - DB: D1Database; - CACHE_KV: KVNamespace; - MEDIA_BUCKET: R2Bucket; - ASSETS: Fetcher; - EMAIL_QUEUE?: Queue; - SENDGRID_API_KEY?: string; - DEFAULT_FROM_EMAIL?: string; - IMAGES_ACCOUNT_ID?: string; - IMAGES_API_TOKEN?: string; - ENVIRONMENT?: string; -}; -type Variables$3 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; - requestId?: string; - startTime?: number; - appVersion?: string; -}; -declare const adminSettingsRoutes: Hono<{ - Bindings: Bindings$3; - Variables: Variables$3; -}, hono_types.BlankSchema, "/">; - -type Bindings$2 = { - DB: D1Database; - CACHE_KV: KVNamespace; - MEDIA_BUCKET: R2Bucket; - ASSETS: Fetcher; - EMAIL_QUEUE?: Queue; - SENDGRID_API_KEY?: string; - DEFAULT_FROM_EMAIL?: string; - ENVIRONMENT?: string; - GOOGLE_MAPS_API_KEY?: string; -}; -type Variables$2 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; - requestId?: string; - startTime?: number; - appVersion?: string; -}; -declare const adminFormsRoutes: Hono<{ - Bindings: Bindings$2; - Variables: Variables$2; -}, hono_types.BlankSchema, "/">; - -type Bindings$1 = { - DB: D1Database; - CACHE_KV: KVNamespace; - MEDIA_BUCKET: R2Bucket; - ASSETS: Fetcher; - EMAIL_QUEUE?: Queue; - SENDGRID_API_KEY?: string; - DEFAULT_FROM_EMAIL?: string; - ENVIRONMENT?: string; - GOOGLE_MAPS_API_KEY?: string; -}; -type Variables$1 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; - requestId?: string; - startTime?: number; - appVersion?: string; -}; -declare const publicFormsRoutes: Hono<{ - Bindings: Bindings$1; - Variables: Variables$1; -}, hono_types.BlankSchema, "/">; - -type Bindings = { - DB: D1Database$1; - CACHE_KV: KVNamespace$1; - MEDIA_BUCKET: R2Bucket$1; -}; -type Variables = { - user?: { - userId: string; - email: string; - role: string; - }; -}; -declare const router: Hono<{ - Bindings: Bindings; - Variables: Variables; -}, hono_types.BlankSchema, "/">; - -/** - * Routes Module Exports - * - * Routes are being migrated incrementally from the monolith. - * Each route is refactored to remove monolith-specific dependencies. - */ - -declare const ROUTES_INFO: { - readonly message: "Core routes available"; - readonly available: readonly ["apiRoutes", "apiContentCrudRoutes", "apiMediaRoutes", "apiSystemRoutes", "adminApiRoutes", "authRoutes", "testCleanupRoutes", "adminContentRoutes", "adminUsersRoutes", "adminMediaRoutes", "adminPluginRoutes", "adminLogsRoutes", "adminDesignRoutes", "adminCheckboxRoutes", "adminTestimonialsRoutes", "adminCodeExamplesRoutes", "adminDashboardRoutes", "adminCollectionsRoutes", "adminSettingsRoutes", "adminFormsRoutes", "publicFormsRoutes", "adminApiReferenceRoutes"]; - readonly status: "Core package routes ready"; - readonly reference: "https://github.com/sonicjs/sonicjs"; -}; - -export { ROUTES_INFO, router as adminApiReferenceRoutes, adminApiRoutes, adminCheckboxRoutes, adminCodeExamplesRoutes, adminCollectionsRoutes, adminContentRoutes, router$1 as adminDashboardRoutes, adminDesignRoutes, adminFormsRoutes, adminLogsRoutes, adminMediaRoutes, adminPluginRoutes, adminSettingsRoutes, adminTestimonialsRoutes, userRoutes as adminUsersRoutes, apiContentCrudRoutes, apiMediaRoutes, apiRoutes, apiSystemRoutes, authRoutes, publicFormsRoutes, app as testCleanupRoutes }; diff --git a/packages/core/dist/routes.d.ts b/packages/core/dist/routes.d.ts deleted file mode 100644 index 9cddf16b5..000000000 --- a/packages/core/dist/routes.d.ts +++ /dev/null @@ -1,297 +0,0 @@ -import * as hono_types from 'hono/types'; -import { Hono } from 'hono'; -import { B as Bindings$a, V as Variables$b } from './app-CYEm1ytG.js'; -import { D1Database as D1Database$1, KVNamespace as KVNamespace$1, R2Bucket as R2Bucket$1 } from '@cloudflare/workers-types'; - -interface Variables$a extends Variables$b { - startTime: number; - cacheEnabled?: boolean; -} -declare const apiRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$a; -}, hono_types.BlankSchema, "/">; - -declare const apiContentCrudRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const apiMediaRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const apiSystemRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const adminApiRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const authRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const app: Hono; - -declare const adminContentRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const userRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const adminMediaRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const adminPluginRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -declare const adminLogsRoutes: Hono<{ - Bindings: Bindings$a; - Variables: Variables$b; -}, hono_types.BlankSchema, "/">; - -type Bindings$9 = { - DB: D1Database; - KV: KVNamespace; -}; -type Variables$9 = { - user: { - userId: string; - email: string; - role: string; - }; -}; -declare const adminDesignRoutes: Hono<{ - Bindings: Bindings$9; - Variables: Variables$9; -}, hono_types.BlankSchema, "/">; - -type Bindings$8 = { - DB: D1Database; - KV: KVNamespace; -}; -type Variables$8 = { - user: { - userId: string; - email: string; - role: string; - }; -}; -declare const adminCheckboxRoutes: Hono<{ - Bindings: Bindings$8; - Variables: Variables$8; -}, hono_types.BlankSchema, "/">; - -type Bindings$7 = { - DB: D1Database; - KV: KVNamespace; -}; -type Variables$7 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; -}; -declare const adminTestimonialsRoutes: Hono<{ - Bindings: Bindings$7; - Variables: Variables$7; -}, hono_types.BlankSchema, "/">; - -type Bindings$6 = { - DB: D1Database; - KV: KVNamespace; -}; -type Variables$6 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; -}; -declare const adminCodeExamplesRoutes: Hono<{ - Bindings: Bindings$6; - Variables: Variables$6; -}, hono_types.BlankSchema, "/">; - -type Bindings$5 = { - DB: D1Database$1; - CACHE_KV: KVNamespace$1; - MEDIA_BUCKET: R2Bucket$1; -}; -type Variables$5 = { - user?: { - userId: string; - email: string; - role: string; - }; -}; -declare const router$1: Hono<{ - Bindings: Bindings$5; - Variables: Variables$5; -}, hono_types.BlankSchema, "/">; - -type Bindings$4 = { - DB: D1Database; - CACHE_KV: KVNamespace; - MEDIA_BUCKET: R2Bucket; - ASSETS: Fetcher; - EMAIL_QUEUE?: Queue; - SENDGRID_API_KEY?: string; - DEFAULT_FROM_EMAIL?: string; - IMAGES_ACCOUNT_ID?: string; - IMAGES_API_TOKEN?: string; - ENVIRONMENT?: string; -}; -type Variables$4 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; - requestId?: string; - startTime?: number; - appVersion?: string; -}; -declare const adminCollectionsRoutes: Hono<{ - Bindings: Bindings$4; - Variables: Variables$4; -}, hono_types.BlankSchema, "/">; - -type Bindings$3 = { - DB: D1Database; - CACHE_KV: KVNamespace; - MEDIA_BUCKET: R2Bucket; - ASSETS: Fetcher; - EMAIL_QUEUE?: Queue; - SENDGRID_API_KEY?: string; - DEFAULT_FROM_EMAIL?: string; - IMAGES_ACCOUNT_ID?: string; - IMAGES_API_TOKEN?: string; - ENVIRONMENT?: string; -}; -type Variables$3 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; - requestId?: string; - startTime?: number; - appVersion?: string; -}; -declare const adminSettingsRoutes: Hono<{ - Bindings: Bindings$3; - Variables: Variables$3; -}, hono_types.BlankSchema, "/">; - -type Bindings$2 = { - DB: D1Database; - CACHE_KV: KVNamespace; - MEDIA_BUCKET: R2Bucket; - ASSETS: Fetcher; - EMAIL_QUEUE?: Queue; - SENDGRID_API_KEY?: string; - DEFAULT_FROM_EMAIL?: string; - ENVIRONMENT?: string; - GOOGLE_MAPS_API_KEY?: string; -}; -type Variables$2 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; - requestId?: string; - startTime?: number; - appVersion?: string; -}; -declare const adminFormsRoutes: Hono<{ - Bindings: Bindings$2; - Variables: Variables$2; -}, hono_types.BlankSchema, "/">; - -type Bindings$1 = { - DB: D1Database; - CACHE_KV: KVNamespace; - MEDIA_BUCKET: R2Bucket; - ASSETS: Fetcher; - EMAIL_QUEUE?: Queue; - SENDGRID_API_KEY?: string; - DEFAULT_FROM_EMAIL?: string; - ENVIRONMENT?: string; - GOOGLE_MAPS_API_KEY?: string; -}; -type Variables$1 = { - user?: { - userId: string; - email: string; - role: string; - exp: number; - iat: number; - }; - requestId?: string; - startTime?: number; - appVersion?: string; -}; -declare const publicFormsRoutes: Hono<{ - Bindings: Bindings$1; - Variables: Variables$1; -}, hono_types.BlankSchema, "/">; - -type Bindings = { - DB: D1Database$1; - CACHE_KV: KVNamespace$1; - MEDIA_BUCKET: R2Bucket$1; -}; -type Variables = { - user?: { - userId: string; - email: string; - role: string; - }; -}; -declare const router: Hono<{ - Bindings: Bindings; - Variables: Variables; -}, hono_types.BlankSchema, "/">; - -/** - * Routes Module Exports - * - * Routes are being migrated incrementally from the monolith. - * Each route is refactored to remove monolith-specific dependencies. - */ - -declare const ROUTES_INFO: { - readonly message: "Core routes available"; - readonly available: readonly ["apiRoutes", "apiContentCrudRoutes", "apiMediaRoutes", "apiSystemRoutes", "adminApiRoutes", "authRoutes", "testCleanupRoutes", "adminContentRoutes", "adminUsersRoutes", "adminMediaRoutes", "adminPluginRoutes", "adminLogsRoutes", "adminDesignRoutes", "adminCheckboxRoutes", "adminTestimonialsRoutes", "adminCodeExamplesRoutes", "adminDashboardRoutes", "adminCollectionsRoutes", "adminSettingsRoutes", "adminFormsRoutes", "publicFormsRoutes", "adminApiReferenceRoutes"]; - readonly status: "Core package routes ready"; - readonly reference: "https://github.com/sonicjs/sonicjs"; -}; - -export { ROUTES_INFO, router as adminApiReferenceRoutes, adminApiRoutes, adminCheckboxRoutes, adminCodeExamplesRoutes, adminCollectionsRoutes, adminContentRoutes, router$1 as adminDashboardRoutes, adminDesignRoutes, adminFormsRoutes, adminLogsRoutes, adminMediaRoutes, adminPluginRoutes, adminSettingsRoutes, adminTestimonialsRoutes, userRoutes as adminUsersRoutes, apiContentCrudRoutes, apiMediaRoutes, apiRoutes, apiSystemRoutes, authRoutes, publicFormsRoutes, app as testCleanupRoutes }; diff --git a/packages/core/dist/services.cjs b/packages/core/dist/services.cjs deleted file mode 100644 index 0e979fbff..000000000 --- a/packages/core/dist/services.cjs +++ /dev/null @@ -1,112 +0,0 @@ -'use strict'; - -var chunkVNLR35GO_cjs = require('./chunk-VNLR35GO.cjs'); -var chunkMPT5PA6U_cjs = require('./chunk-MPT5PA6U.cjs'); -var chunkFQSMNIY2_cjs = require('./chunk-FQSMNIY2.cjs'); -require('./chunk-P3XDZL6Q.cjs'); -require('./chunk-IGJUBJBW.cjs'); - - - -Object.defineProperty(exports, "CACHE_CONFIGS", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.CACHE_CONFIGS; } -}); -Object.defineProperty(exports, "CacheService", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.CacheService; } -}); -Object.defineProperty(exports, "Logger", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.Logger; } -}); -Object.defineProperty(exports, "SettingsService", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.SettingsService; } -}); -Object.defineProperty(exports, "TelemetryService", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.TelemetryService; } -}); -Object.defineProperty(exports, "createInstallationIdentity", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.createInstallationIdentity; } -}); -Object.defineProperty(exports, "getCacheService", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.getCacheService; } -}); -Object.defineProperty(exports, "getLogger", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.getLogger; } -}); -Object.defineProperty(exports, "getTelemetryService", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.getTelemetryService; } -}); -Object.defineProperty(exports, "initLogger", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.initLogger; } -}); -Object.defineProperty(exports, "initTelemetry", { - enumerable: true, - get: function () { return chunkVNLR35GO_cjs.initTelemetry; } -}); -Object.defineProperty(exports, "PluginBootstrapService", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.PluginBootstrapService; } -}); -Object.defineProperty(exports, "PluginService", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.PluginService; } -}); -Object.defineProperty(exports, "cleanupRemovedCollections", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.cleanupRemovedCollections; } -}); -Object.defineProperty(exports, "fullCollectionSync", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.fullCollectionSync; } -}); -Object.defineProperty(exports, "getAvailableCollectionNames", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.getAvailableCollectionNames; } -}); -Object.defineProperty(exports, "getManagedCollections", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.getManagedCollections; } -}); -Object.defineProperty(exports, "isCollectionManaged", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.isCollectionManaged; } -}); -Object.defineProperty(exports, "loadCollectionConfig", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.loadCollectionConfig; } -}); -Object.defineProperty(exports, "loadCollectionConfigs", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.loadCollectionConfigs; } -}); -Object.defineProperty(exports, "registerCollections", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.registerCollections; } -}); -Object.defineProperty(exports, "syncCollection", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.syncCollection; } -}); -Object.defineProperty(exports, "syncCollections", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.syncCollections; } -}); -Object.defineProperty(exports, "validateCollectionConfig", { - enumerable: true, - get: function () { return chunkMPT5PA6U_cjs.validateCollectionConfig; } -}); -Object.defineProperty(exports, "MigrationService", { - enumerable: true, - get: function () { return chunkFQSMNIY2_cjs.MigrationService; } -}); -//# sourceMappingURL=services.cjs.map -//# sourceMappingURL=services.cjs.map \ No newline at end of file diff --git a/packages/core/dist/services.d.cts b/packages/core/dist/services.d.cts deleted file mode 100644 index b61269319..000000000 --- a/packages/core/dist/services.d.cts +++ /dev/null @@ -1,235 +0,0 @@ -export { C as CorePlugin, n as LogCategory, o as LogEntry, p as LogFilter, m as LogLevel, L as Logger, e as Migration, M as MigrationService, h as MigrationStatus, q as PluginBootstrapService, P as PluginService, d as cleanupRemovedCollections, f as fullCollectionSync, g as getAvailableCollectionNames, j as getLogger, c as getManagedCollections, k as initLogger, i as isCollectionManaged, a as loadCollectionConfig, l as loadCollectionConfigs, r as registerCollections, b as syncCollection, s as syncCollections, v as validateCollectionConfig } from './plugin-bootstrap-DKB5f8-E.cjs'; -import { b as TelemetryConfig, c as TelemetryIdentity, T as TelemetryEvent, a as TelemetryProperties } from './telemetry-UiD1i9GS.cjs'; -import './collection-config-BF95LgQb.cjs'; -import '@cloudflare/workers-types'; -import 'drizzle-zod'; -import 'drizzle-orm/sqlite-core'; - -/** - * Simple Cache Service - * - * Provides basic caching functionality for the core package - * Can be extended with KV or other storage backends - */ -interface CacheConfig { - ttl: number; - keyPrefix: string; -} -declare class CacheService { - private config; - private memoryCache; - constructor(config: CacheConfig); - /** - * Generate cache key with prefix - */ - generateKey(type: string, identifier?: string): string; - /** - * Get value from cache - */ - get(key: string): Promise; - /** - * Get value from cache with source information - */ - getWithSource(key: string): Promise<{ - hit: boolean; - data: T | null; - source: string; - ttl?: number; - }>; - /** - * Set value in cache - */ - set(key: string, value: any, ttl?: number): Promise; - /** - * Delete specific key from cache - */ - delete(key: string): Promise; - /** - * Invalidate cache keys matching a pattern - * For memory cache, we do simple string matching - */ - invalidate(pattern: string): Promise; - /** - * Clear all cache - */ - clear(): Promise; - /** - * Get value from cache or set it using a callback - */ - getOrSet(key: string, callback: () => Promise, ttl?: number): Promise; -} -/** - * Cache configurations for different data types - */ -declare const CACHE_CONFIGS: { - api: { - ttl: number; - keyPrefix: string; - }; - user: { - ttl: number; - keyPrefix: string; - }; - content: { - ttl: number; - keyPrefix: string; - }; - collection: { - ttl: number; - keyPrefix: string; - }; -}; -/** - * Get cache service instance for a config - */ -declare function getCacheService(config: CacheConfig): CacheService; - -interface Setting { - id: string; - category: string; - key: string; - value: string; - created_at: number; - updated_at: number; -} -interface GeneralSettings { - siteName: string; - siteDescription: string; - adminEmail: string; - timezone: string; - language: string; - maintenanceMode: boolean; -} -declare class SettingsService { - private db; - constructor(db: D1Database); - /** - * Get a setting value by category and key - */ - getSetting(category: string, key: string): Promise; - /** - * Get all settings for a category - */ - getCategorySettings(category: string): Promise>; - /** - * Set a setting value - */ - setSetting(category: string, key: string, value: any): Promise; - /** - * Set multiple settings at once - */ - setMultipleSettings(category: string, settings: Record): Promise; - /** - * Get general settings with defaults - */ - getGeneralSettings(userEmail?: string): Promise; - /** - * Save general settings - */ - saveGeneralSettings(settings: Partial): Promise; -} - -/** - * Telemetry Service - * - * Privacy-first telemetry service using custom SonicJS stats endpoint - * - No PII collection - * - Opt-out by default - * - Silent failures (never blocks app) - */ - -/** - * TelemetryService class - * - * Handles all telemetry tracking in a privacy-conscious way - */ -declare class TelemetryService { - private config; - private identity; - private enabled; - private eventQueue; - private isInitialized; - constructor(config?: Partial); - /** - * Initialize the telemetry service - */ - initialize(identity: TelemetryIdentity): Promise; - /** - * Track a telemetry event - */ - track(event: TelemetryEvent, properties?: TelemetryProperties): Promise; - /** - * Track installation started - */ - trackInstallationStarted(properties?: TelemetryProperties): Promise; - /** - * Track installation completed - */ - trackInstallationCompleted(properties?: TelemetryProperties): Promise; - /** - * Track installation failed - */ - trackInstallationFailed(error: Error | string, properties?: TelemetryProperties): Promise; - /** - * Track dev server started - */ - trackDevServerStarted(properties?: TelemetryProperties): Promise; - /** - * Track page view in admin UI - */ - trackPageView(route: string, properties?: TelemetryProperties): Promise; - /** - * Track error (sanitized) - */ - trackError(error: Error | string, properties?: TelemetryProperties): Promise; - /** - * Track plugin activation - */ - trackPluginActivated(properties?: TelemetryProperties): Promise; - /** - * Track migration run - */ - trackMigrationRun(properties?: TelemetryProperties): Promise; - /** - * Flush queued events - */ - private flushQueue; - /** - * Sanitize properties to ensure no PII - */ - private sanitizeProperties; - /** - * Get SonicJS version - */ - private getVersion; - /** - * Shutdown the telemetry service (no-op for fetch-based telemetry) - */ - shutdown(): Promise; - /** - * Enable telemetry - */ - enable(): void; - /** - * Disable telemetry - */ - disable(): void; - /** - * Check if telemetry is enabled - */ - isEnabled(): boolean; -} -/** - * Get the telemetry service instance - */ -declare function getTelemetryService(config?: Partial): TelemetryService; -/** - * Initialize telemetry service - */ -declare function initTelemetry(identity: TelemetryIdentity, config?: Partial): Promise; -/** - * Create a new installation identity - */ -declare function createInstallationIdentity(projectName?: string): TelemetryIdentity; - -export { CACHE_CONFIGS, type CacheConfig, CacheService, type GeneralSettings, type Setting, SettingsService, TelemetryService, createInstallationIdentity, getCacheService, getTelemetryService, initTelemetry }; diff --git a/packages/core/dist/services.d.ts b/packages/core/dist/services.d.ts deleted file mode 100644 index a25b770e5..000000000 --- a/packages/core/dist/services.d.ts +++ /dev/null @@ -1,235 +0,0 @@ -export { C as CorePlugin, n as LogCategory, o as LogEntry, p as LogFilter, m as LogLevel, L as Logger, e as Migration, M as MigrationService, h as MigrationStatus, q as PluginBootstrapService, P as PluginService, d as cleanupRemovedCollections, f as fullCollectionSync, g as getAvailableCollectionNames, j as getLogger, c as getManagedCollections, k as initLogger, i as isCollectionManaged, a as loadCollectionConfig, l as loadCollectionConfigs, r as registerCollections, b as syncCollection, s as syncCollections, v as validateCollectionConfig } from './plugin-bootstrap-C7Mj00Ud.js'; -import { b as TelemetryConfig, c as TelemetryIdentity, T as TelemetryEvent, a as TelemetryProperties } from './telemetry-UiD1i9GS.js'; -import './collection-config-BF95LgQb.js'; -import '@cloudflare/workers-types'; -import 'drizzle-zod'; -import 'drizzle-orm/sqlite-core'; - -/** - * Simple Cache Service - * - * Provides basic caching functionality for the core package - * Can be extended with KV or other storage backends - */ -interface CacheConfig { - ttl: number; - keyPrefix: string; -} -declare class CacheService { - private config; - private memoryCache; - constructor(config: CacheConfig); - /** - * Generate cache key with prefix - */ - generateKey(type: string, identifier?: string): string; - /** - * Get value from cache - */ - get(key: string): Promise; - /** - * Get value from cache with source information - */ - getWithSource(key: string): Promise<{ - hit: boolean; - data: T | null; - source: string; - ttl?: number; - }>; - /** - * Set value in cache - */ - set(key: string, value: any, ttl?: number): Promise; - /** - * Delete specific key from cache - */ - delete(key: string): Promise; - /** - * Invalidate cache keys matching a pattern - * For memory cache, we do simple string matching - */ - invalidate(pattern: string): Promise; - /** - * Clear all cache - */ - clear(): Promise; - /** - * Get value from cache or set it using a callback - */ - getOrSet(key: string, callback: () => Promise, ttl?: number): Promise; -} -/** - * Cache configurations for different data types - */ -declare const CACHE_CONFIGS: { - api: { - ttl: number; - keyPrefix: string; - }; - user: { - ttl: number; - keyPrefix: string; - }; - content: { - ttl: number; - keyPrefix: string; - }; - collection: { - ttl: number; - keyPrefix: string; - }; -}; -/** - * Get cache service instance for a config - */ -declare function getCacheService(config: CacheConfig): CacheService; - -interface Setting { - id: string; - category: string; - key: string; - value: string; - created_at: number; - updated_at: number; -} -interface GeneralSettings { - siteName: string; - siteDescription: string; - adminEmail: string; - timezone: string; - language: string; - maintenanceMode: boolean; -} -declare class SettingsService { - private db; - constructor(db: D1Database); - /** - * Get a setting value by category and key - */ - getSetting(category: string, key: string): Promise; - /** - * Get all settings for a category - */ - getCategorySettings(category: string): Promise>; - /** - * Set a setting value - */ - setSetting(category: string, key: string, value: any): Promise; - /** - * Set multiple settings at once - */ - setMultipleSettings(category: string, settings: Record): Promise; - /** - * Get general settings with defaults - */ - getGeneralSettings(userEmail?: string): Promise; - /** - * Save general settings - */ - saveGeneralSettings(settings: Partial): Promise; -} - -/** - * Telemetry Service - * - * Privacy-first telemetry service using custom SonicJS stats endpoint - * - No PII collection - * - Opt-out by default - * - Silent failures (never blocks app) - */ - -/** - * TelemetryService class - * - * Handles all telemetry tracking in a privacy-conscious way - */ -declare class TelemetryService { - private config; - private identity; - private enabled; - private eventQueue; - private isInitialized; - constructor(config?: Partial); - /** - * Initialize the telemetry service - */ - initialize(identity: TelemetryIdentity): Promise; - /** - * Track a telemetry event - */ - track(event: TelemetryEvent, properties?: TelemetryProperties): Promise; - /** - * Track installation started - */ - trackInstallationStarted(properties?: TelemetryProperties): Promise; - /** - * Track installation completed - */ - trackInstallationCompleted(properties?: TelemetryProperties): Promise; - /** - * Track installation failed - */ - trackInstallationFailed(error: Error | string, properties?: TelemetryProperties): Promise; - /** - * Track dev server started - */ - trackDevServerStarted(properties?: TelemetryProperties): Promise; - /** - * Track page view in admin UI - */ - trackPageView(route: string, properties?: TelemetryProperties): Promise; - /** - * Track error (sanitized) - */ - trackError(error: Error | string, properties?: TelemetryProperties): Promise; - /** - * Track plugin activation - */ - trackPluginActivated(properties?: TelemetryProperties): Promise; - /** - * Track migration run - */ - trackMigrationRun(properties?: TelemetryProperties): Promise; - /** - * Flush queued events - */ - private flushQueue; - /** - * Sanitize properties to ensure no PII - */ - private sanitizeProperties; - /** - * Get SonicJS version - */ - private getVersion; - /** - * Shutdown the telemetry service (no-op for fetch-based telemetry) - */ - shutdown(): Promise; - /** - * Enable telemetry - */ - enable(): void; - /** - * Disable telemetry - */ - disable(): void; - /** - * Check if telemetry is enabled - */ - isEnabled(): boolean; -} -/** - * Get the telemetry service instance - */ -declare function getTelemetryService(config?: Partial): TelemetryService; -/** - * Initialize telemetry service - */ -declare function initTelemetry(identity: TelemetryIdentity, config?: Partial): Promise; -/** - * Create a new installation identity - */ -declare function createInstallationIdentity(projectName?: string): TelemetryIdentity; - -export { CACHE_CONFIGS, type CacheConfig, CacheService, type GeneralSettings, type Setting, SettingsService, TelemetryService, createInstallationIdentity, getCacheService, getTelemetryService, initTelemetry }; diff --git a/packages/core/dist/telemetry-UiD1i9GS.d.cts b/packages/core/dist/telemetry-UiD1i9GS.d.cts deleted file mode 100644 index d40232cbf..000000000 --- a/packages/core/dist/telemetry-UiD1i9GS.d.cts +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Telemetry Types - * - * Privacy-first telemetry types for SonicJS - * No PII (Personally Identifiable Information) is collected - */ -type TelemetryEvent = 'installation_started' | 'installation_completed' | 'installation_failed' | 'setup_wizard_started' | 'setup_wizard_completed' | 'first_dev_server_start' | 'dev_server_started' | 'dev_server_stopped' | 'admin_login' | 'plugin_activated' | 'plugin_deactivated' | 'collection_created' | 'content_created' | 'page_viewed' | 'feature_used' | 'error_occurred' | 'migration_run' | 'deployment_triggered'; -interface TelemetryProperties { - os?: 'darwin' | 'linux' | 'win32' | string; - nodeVersion?: string; - packageManager?: 'npm' | 'yarn' | 'pnpm' | 'bun'; - installationDuration?: number; - success?: boolean; - errorType?: string; - sessionDuration?: number; - pluginsCount?: number; - collectionsCount?: number; - contentItemsCount?: number; - route?: string; - feature?: string; - migrationType?: 'initial' | 'update' | 'rollback'; - migrationSuccess?: boolean; - [key: string]: string | number | boolean | undefined; -} -interface TelemetryConfig { - enabled: boolean; - host?: string; - debug?: boolean; -} -interface TelemetryIdentity { - installationId: string; - projectId?: string; -} - -export type { TelemetryEvent as T, TelemetryProperties as a, TelemetryConfig as b, TelemetryIdentity as c }; diff --git a/packages/core/dist/telemetry-UiD1i9GS.d.ts b/packages/core/dist/telemetry-UiD1i9GS.d.ts deleted file mode 100644 index d40232cbf..000000000 --- a/packages/core/dist/telemetry-UiD1i9GS.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Telemetry Types - * - * Privacy-first telemetry types for SonicJS - * No PII (Personally Identifiable Information) is collected - */ -type TelemetryEvent = 'installation_started' | 'installation_completed' | 'installation_failed' | 'setup_wizard_started' | 'setup_wizard_completed' | 'first_dev_server_start' | 'dev_server_started' | 'dev_server_stopped' | 'admin_login' | 'plugin_activated' | 'plugin_deactivated' | 'collection_created' | 'content_created' | 'page_viewed' | 'feature_used' | 'error_occurred' | 'migration_run' | 'deployment_triggered'; -interface TelemetryProperties { - os?: 'darwin' | 'linux' | 'win32' | string; - nodeVersion?: string; - packageManager?: 'npm' | 'yarn' | 'pnpm' | 'bun'; - installationDuration?: number; - success?: boolean; - errorType?: string; - sessionDuration?: number; - pluginsCount?: number; - collectionsCount?: number; - contentItemsCount?: number; - route?: string; - feature?: string; - migrationType?: 'initial' | 'update' | 'rollback'; - migrationSuccess?: boolean; - [key: string]: string | number | boolean | undefined; -} -interface TelemetryConfig { - enabled: boolean; - host?: string; - debug?: boolean; -} -interface TelemetryIdentity { - installationId: string; - projectId?: string; -} - -export type { TelemetryEvent as T, TelemetryProperties as a, TelemetryConfig as b, TelemetryIdentity as c }; diff --git a/packages/core/dist/templates.cjs b/packages/core/dist/templates.cjs deleted file mode 100644 index f48bc70bb..000000000 --- a/packages/core/dist/templates.cjs +++ /dev/null @@ -1,78 +0,0 @@ -'use strict'; - -var chunkS6K2H2TS_cjs = require('./chunk-S6K2H2TS.cjs'); -var chunkSHCYIZAN_cjs = require('./chunk-SHCYIZAN.cjs'); -require('./chunk-IGJUBJBW.cjs'); - - - -Object.defineProperty(exports, "renderFilterBar", { - enumerable: true, - get: function () { return chunkS6K2H2TS_cjs.renderFilterBar; } -}); -Object.defineProperty(exports, "renderFormsDocsPage", { - enumerable: true, - get: function () { return chunkS6K2H2TS_cjs.renderFormsDocsPage; } -}); -Object.defineProperty(exports, "renderFormsExamplesPage", { - enumerable: true, - get: function () { return chunkS6K2H2TS_cjs.renderFormsExamplesPage; } -}); -Object.defineProperty(exports, "getConfirmationDialogScript", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.getConfirmationDialogScript; } -}); -Object.defineProperty(exports, "renderAdminLayout", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderAdminLayout; } -}); -Object.defineProperty(exports, "renderAdminLayoutCatalyst", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderAdminLayoutCatalyst; } -}); -Object.defineProperty(exports, "renderAlert", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderAlert; } -}); -Object.defineProperty(exports, "renderCheckboxPage", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderCheckboxPage; } -}); -Object.defineProperty(exports, "renderCodeExamplesList", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderCodeExamplesList; } -}); -Object.defineProperty(exports, "renderConfirmationDialog", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderConfirmationDialog; } -}); -Object.defineProperty(exports, "renderDesignPage", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderDesignPage; } -}); -Object.defineProperty(exports, "renderForm", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderForm; } -}); -Object.defineProperty(exports, "renderFormField", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderFormField; } -}); -Object.defineProperty(exports, "renderLogo", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderLogo; } -}); -Object.defineProperty(exports, "renderPagination", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderPagination; } -}); -Object.defineProperty(exports, "renderTable", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderTable; } -}); -Object.defineProperty(exports, "renderTestimonialsList", { - enumerable: true, - get: function () { return chunkSHCYIZAN_cjs.renderTestimonialsList; } -}); -//# sourceMappingURL=templates.cjs.map -//# sourceMappingURL=templates.cjs.map \ No newline at end of file diff --git a/packages/core/dist/templates.d.cts b/packages/core/dist/templates.d.cts deleted file mode 100644 index 18f281c1c..000000000 --- a/packages/core/dist/templates.d.cts +++ /dev/null @@ -1,153 +0,0 @@ -export { A as AlertData, C as ConfirmationDialogOptions, k as Filter, j as FilterBarData, l as FilterOption, h as FormData, F as FormField, P as PaginationData, T as TableColumn, i as TableData, g as getConfirmationDialogScript, d as renderAlert, e as renderConfirmationDialog, f as renderFilterBar, r as renderForm, a as renderFormField, c as renderPagination, b as renderTable } from './filter-bar.template-By4jeiw_.cjs'; -import { HtmlEscapedString } from 'hono/utils/html'; - -interface AdminLayoutData { - title: string; - pageTitle?: string; - currentPath?: string; - version?: string; - enableExperimentalFeatures?: boolean; - user?: { - name: string; - email: string; - role: string; - }; - scripts?: string[]; - styles?: string[]; - content: string | HtmlEscapedString; - dynamicMenuItems?: Array<{ - label: string; - path: string; - icon: string; - }>; -} -declare function renderAdminLayout(data: AdminLayoutData): string; - -interface AdminLayoutCatalystData { - title: string; - pageTitle?: string; - currentPath?: string; - version?: string; - enableExperimentalFeatures?: boolean; - user?: { - name: string; - email: string; - role: string; - }; - scripts?: string[]; - styles?: string[]; - content: string | HtmlEscapedString; - dynamicMenuItems?: Array<{ - label: string; - path: string; - icon: string; - }>; -} -declare function renderAdminLayoutCatalyst(data: AdminLayoutCatalystData): string; - -interface LogoData { - size?: 'sm' | 'md' | 'lg' | 'xl'; - variant?: 'default' | 'white' | 'dark'; - showText?: boolean; - showVersion?: boolean; - version?: string; - className?: string; - href?: string; -} -declare function renderLogo(data?: LogoData): string; - -interface DesignPageData { - user?: { - name: string; - email: string; - role: string; - }; - version?: string; -} -declare function renderDesignPage(data: DesignPageData): string; - -interface CheckboxPageData { - user?: { - name: string; - email: string; - role: string; - }; -} -declare function renderCheckboxPage(data: CheckboxPageData): string; - -interface Testimonial { - id: number; - author_name: string; - author_title?: string; - author_company?: string; - testimonial_text: string; - rating?: number; - isPublished: boolean; - sortOrder: number; - created_at: number; - updated_at: number; -} -interface TestimonialsListData { - testimonials: Testimonial[]; - totalCount: number; - currentPage: number; - totalPages: number; - user?: { - name: string; - email: string; - role: string; - }; - message?: string; - messageType?: 'success' | 'error' | 'warning' | 'info'; -} -declare function renderTestimonialsList(data: TestimonialsListData): string; - -interface CodeExample { - id: number; - title: string; - description?: string; - code: string; - language: string; - category?: string; - tags?: string; - isPublished: boolean; - sortOrder: number; - created_at: number; - updated_at: number; -} -interface CodeExamplesListData { - codeExamples: CodeExample[]; - totalCount: number; - currentPage: number; - totalPages: number; - user?: { - name: string; - email: string; - role: string; - }; - message?: string; - messageType?: 'success' | 'error' | 'warning' | 'info'; -} -declare function renderCodeExamplesList(data: CodeExamplesListData): string; - -interface FormsDocsPageData { - user?: { - name: string; - email: string; - role: string; - }; - version?: string; -} -declare function renderFormsDocsPage(data: FormsDocsPageData): string; - -interface FormsExamplesPageData { - user?: { - name: string; - email: string; - role: string; - }; - version?: string; -} -declare function renderFormsExamplesPage(data: FormsExamplesPageData): string; - -export { type AdminLayoutCatalystData, type AdminLayoutData, type CheckboxPageData, type DesignPageData, type FormsDocsPageData, type FormsExamplesPageData, renderAdminLayout, renderAdminLayoutCatalyst, renderCheckboxPage, renderCodeExamplesList, renderDesignPage, renderFormsDocsPage, renderFormsExamplesPage, renderLogo, renderTestimonialsList }; diff --git a/packages/core/dist/templates.d.ts b/packages/core/dist/templates.d.ts deleted file mode 100644 index a3a9da61d..000000000 --- a/packages/core/dist/templates.d.ts +++ /dev/null @@ -1,153 +0,0 @@ -export { A as AlertData, C as ConfirmationDialogOptions, k as Filter, j as FilterBarData, l as FilterOption, h as FormData, F as FormField, P as PaginationData, T as TableColumn, i as TableData, g as getConfirmationDialogScript, d as renderAlert, e as renderConfirmationDialog, f as renderFilterBar, r as renderForm, a as renderFormField, c as renderPagination, b as renderTable } from './filter-bar.template-By4jeiw_.js'; -import { HtmlEscapedString } from 'hono/utils/html'; - -interface AdminLayoutData { - title: string; - pageTitle?: string; - currentPath?: string; - version?: string; - enableExperimentalFeatures?: boolean; - user?: { - name: string; - email: string; - role: string; - }; - scripts?: string[]; - styles?: string[]; - content: string | HtmlEscapedString; - dynamicMenuItems?: Array<{ - label: string; - path: string; - icon: string; - }>; -} -declare function renderAdminLayout(data: AdminLayoutData): string; - -interface AdminLayoutCatalystData { - title: string; - pageTitle?: string; - currentPath?: string; - version?: string; - enableExperimentalFeatures?: boolean; - user?: { - name: string; - email: string; - role: string; - }; - scripts?: string[]; - styles?: string[]; - content: string | HtmlEscapedString; - dynamicMenuItems?: Array<{ - label: string; - path: string; - icon: string; - }>; -} -declare function renderAdminLayoutCatalyst(data: AdminLayoutCatalystData): string; - -interface LogoData { - size?: 'sm' | 'md' | 'lg' | 'xl'; - variant?: 'default' | 'white' | 'dark'; - showText?: boolean; - showVersion?: boolean; - version?: string; - className?: string; - href?: string; -} -declare function renderLogo(data?: LogoData): string; - -interface DesignPageData { - user?: { - name: string; - email: string; - role: string; - }; - version?: string; -} -declare function renderDesignPage(data: DesignPageData): string; - -interface CheckboxPageData { - user?: { - name: string; - email: string; - role: string; - }; -} -declare function renderCheckboxPage(data: CheckboxPageData): string; - -interface Testimonial { - id: number; - author_name: string; - author_title?: string; - author_company?: string; - testimonial_text: string; - rating?: number; - isPublished: boolean; - sortOrder: number; - created_at: number; - updated_at: number; -} -interface TestimonialsListData { - testimonials: Testimonial[]; - totalCount: number; - currentPage: number; - totalPages: number; - user?: { - name: string; - email: string; - role: string; - }; - message?: string; - messageType?: 'success' | 'error' | 'warning' | 'info'; -} -declare function renderTestimonialsList(data: TestimonialsListData): string; - -interface CodeExample { - id: number; - title: string; - description?: string; - code: string; - language: string; - category?: string; - tags?: string; - isPublished: boolean; - sortOrder: number; - created_at: number; - updated_at: number; -} -interface CodeExamplesListData { - codeExamples: CodeExample[]; - totalCount: number; - currentPage: number; - totalPages: number; - user?: { - name: string; - email: string; - role: string; - }; - message?: string; - messageType?: 'success' | 'error' | 'warning' | 'info'; -} -declare function renderCodeExamplesList(data: CodeExamplesListData): string; - -interface FormsDocsPageData { - user?: { - name: string; - email: string; - role: string; - }; - version?: string; -} -declare function renderFormsDocsPage(data: FormsDocsPageData): string; - -interface FormsExamplesPageData { - user?: { - name: string; - email: string; - role: string; - }; - version?: string; -} -declare function renderFormsExamplesPage(data: FormsExamplesPageData): string; - -export { type AdminLayoutCatalystData, type AdminLayoutData, type CheckboxPageData, type DesignPageData, type FormsDocsPageData, type FormsExamplesPageData, renderAdminLayout, renderAdminLayoutCatalyst, renderCheckboxPage, renderCodeExamplesList, renderDesignPage, renderFormsDocsPage, renderFormsExamplesPage, renderLogo, renderTestimonialsList }; diff --git a/packages/core/dist/types.cjs b/packages/core/dist/types.cjs deleted file mode 100644 index 48ee3af89..000000000 --- a/packages/core/dist/types.cjs +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var chunkKYGRJCZM_cjs = require('./chunk-KYGRJCZM.cjs'); -require('./chunk-IGJUBJBW.cjs'); - - - -Object.defineProperty(exports, "HOOKS", { - enumerable: true, - get: function () { return chunkKYGRJCZM_cjs.HOOKS; } -}); -//# sourceMappingURL=types.cjs.map -//# sourceMappingURL=types.cjs.map \ No newline at end of file diff --git a/packages/core/dist/types.d.cts b/packages/core/dist/types.d.cts deleted file mode 100644 index f8d4d6c2d..000000000 --- a/packages/core/dist/types.d.cts +++ /dev/null @@ -1,7 +0,0 @@ -export { B as BlockDefinition, b as BlockDefinitions, c as CollectionConfig, d as CollectionConfigModule, C as CollectionSchema, e as CollectionSyncResult, a as FieldConfig, F as FieldType } from './collection-config-BF95LgQb.cjs'; -export { A as AuthService, C as ContentService, v as HOOKS, k as HookContext, H as HookHandler, u as HookName, l as HookSystem, p as MediaService, M as ModelRelationship, P as Plugin, g as PluginAdminPage, r as PluginBuilderOptions, h as PluginComponent, b as PluginConfig, a as PluginContext, j as PluginHook, q as PluginLogger, n as PluginManager, i as PluginMenuItem, d as PluginMiddleware, e as PluginModel, m as PluginRegistry, c as PluginRoutes, f as PluginService, o as PluginStatus, t as PluginValidationResult, s as PluginValidator, S as ScopedHookSystem } from './plugin-zvZpaiP5.cjs'; -export { P as PluginManifest } from './plugin-manifest-Dpy8wxIB.cjs'; -export { b as TelemetryConfig, T as TelemetryEvent, c as TelemetryIdentity, a as TelemetryProperties } from './telemetry-UiD1i9GS.cjs'; -import 'hono'; -import 'zod'; -import '@cloudflare/workers-types'; diff --git a/packages/core/dist/types.d.ts b/packages/core/dist/types.d.ts deleted file mode 100644 index 51a61e358..000000000 --- a/packages/core/dist/types.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export { B as BlockDefinition, b as BlockDefinitions, c as CollectionConfig, d as CollectionConfigModule, C as CollectionSchema, e as CollectionSyncResult, a as FieldConfig, F as FieldType } from './collection-config-BF95LgQb.js'; -export { A as AuthService, C as ContentService, v as HOOKS, k as HookContext, H as HookHandler, u as HookName, l as HookSystem, p as MediaService, M as ModelRelationship, P as Plugin, g as PluginAdminPage, r as PluginBuilderOptions, h as PluginComponent, b as PluginConfig, a as PluginContext, j as PluginHook, q as PluginLogger, n as PluginManager, i as PluginMenuItem, d as PluginMiddleware, e as PluginModel, m as PluginRegistry, c as PluginRoutes, f as PluginService, o as PluginStatus, t as PluginValidationResult, s as PluginValidator, S as ScopedHookSystem } from './plugin-zvZpaiP5.js'; -export { P as PluginManifest } from './plugin-manifest-Dpy8wxIB.js'; -export { b as TelemetryConfig, T as TelemetryEvent, c as TelemetryIdentity, a as TelemetryProperties } from './telemetry-UiD1i9GS.js'; -import 'hono'; -import 'zod'; -import '@cloudflare/workers-types'; diff --git a/packages/core/dist/utils.cjs b/packages/core/dist/utils.cjs deleted file mode 100644 index cb93ca7af..000000000 --- a/packages/core/dist/utils.cjs +++ /dev/null @@ -1,99 +0,0 @@ -'use strict'; - -var chunk5HMR2SJW_cjs = require('./chunk-5HMR2SJW.cjs'); -var chunkP3XDZL6Q_cjs = require('./chunk-P3XDZL6Q.cjs'); -var chunkRCQ2HIQD_cjs = require('./chunk-RCQ2HIQD.cjs'); -require('./chunk-IGJUBJBW.cjs'); - - - -Object.defineProperty(exports, "QueryFilterBuilder", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.QueryFilterBuilder; } -}); -Object.defineProperty(exports, "SONICJS_VERSION", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.SONICJS_VERSION; } -}); -Object.defineProperty(exports, "TemplateRenderer", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.TemplateRenderer; } -}); -Object.defineProperty(exports, "buildQuery", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.buildQuery; } -}); -Object.defineProperty(exports, "escapeHtml", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.escapeHtml; } -}); -Object.defineProperty(exports, "generateSlug", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.generateSlug; } -}); -Object.defineProperty(exports, "getBlocksFieldConfig", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.getBlocksFieldConfig; } -}); -Object.defineProperty(exports, "getCoreVersion", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.getCoreVersion; } -}); -Object.defineProperty(exports, "parseBlocksValue", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.parseBlocksValue; } -}); -Object.defineProperty(exports, "renderTemplate", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.renderTemplate; } -}); -Object.defineProperty(exports, "sanitizeInput", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.sanitizeInput; } -}); -Object.defineProperty(exports, "sanitizeObject", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.sanitizeObject; } -}); -Object.defineProperty(exports, "templateRenderer", { - enumerable: true, - get: function () { return chunk5HMR2SJW_cjs.templateRenderer; } -}); -Object.defineProperty(exports, "generateInstallationId", { - enumerable: true, - get: function () { return chunkP3XDZL6Q_cjs.generateInstallationId; } -}); -Object.defineProperty(exports, "generateProjectId", { - enumerable: true, - get: function () { return chunkP3XDZL6Q_cjs.generateProjectId; } -}); -Object.defineProperty(exports, "getDefaultTelemetryConfig", { - enumerable: true, - get: function () { return chunkP3XDZL6Q_cjs.getDefaultTelemetryConfig; } -}); -Object.defineProperty(exports, "getTelemetryConfig", { - enumerable: true, - get: function () { return chunkP3XDZL6Q_cjs.getTelemetryConfig; } -}); -Object.defineProperty(exports, "isTelemetryEnabled", { - enumerable: true, - get: function () { return chunkP3XDZL6Q_cjs.isTelemetryEnabled; } -}); -Object.defineProperty(exports, "sanitizeErrorMessage", { - enumerable: true, - get: function () { return chunkP3XDZL6Q_cjs.sanitizeErrorMessage; } -}); -Object.defineProperty(exports, "sanitizeRoute", { - enumerable: true, - get: function () { return chunkP3XDZL6Q_cjs.sanitizeRoute; } -}); -Object.defineProperty(exports, "shouldSkipEvent", { - enumerable: true, - get: function () { return chunkP3XDZL6Q_cjs.shouldSkipEvent; } -}); -Object.defineProperty(exports, "metricsTracker", { - enumerable: true, - get: function () { return chunkRCQ2HIQD_cjs.metricsTracker; } -}); -//# sourceMappingURL=utils.cjs.map -//# sourceMappingURL=utils.cjs.map \ No newline at end of file diff --git a/packages/core/dist/utils.d.cts b/packages/core/dist/utils.d.cts deleted file mode 100644 index 94750e365..000000000 --- a/packages/core/dist/utils.d.cts +++ /dev/null @@ -1,90 +0,0 @@ -export { c as FilterCondition, d as FilterGroup, F as FilterOperator, f as QueryFilter, Q as QueryFilterBuilder, h as QueryResult, S as SONICJS_VERSION, T as TemplateRenderer, b as buildQuery, e as escapeHtml, g as getCoreVersion, m as metricsTracker, r as renderTemplate, s as sanitizeInput, a as sanitizeObject, t as templateRenderer } from './version-vktVAxhe.cjs'; -import { b as TelemetryConfig } from './telemetry-UiD1i9GS.cjs'; -import { b as BlockDefinitions } from './collection-config-BF95LgQb.cjs'; - -/** - * Slug generation utilities for creating URL-friendly slugs - */ -/** - * Generate URL-friendly slug from text - * - * Features: - * - Converts to lowercase - * - Handles accented characters (NFD normalization) - * - Removes diacritics - * - Keeps only alphanumeric, spaces, underscores, and hyphens - * - Replaces spaces with hyphens - * - Collapses multiple hyphens/underscores - * - Trims leading/trailing hyphens/underscores - * - Limits length to 100 characters - * - * @param text - Text to slugify - * @returns URL-safe slug - * - * @example - * generateSlug('Hello World!') // 'hello-world' - * generateSlug('Café París 2024') // 'cafe-paris-2024' - * generateSlug('Multiple Spaces') // 'multiple-spaces' - */ -declare function generateSlug(text: string): string; - -/** - * Telemetry ID Utilities - * - * Generates and manages anonymous installation IDs - */ -/** - * Generate a new anonymous installation ID - * Uses globalThis.crypto for Cloudflare Workers compatibility - */ -declare function generateInstallationId(): string; -/** - * Generate a project-specific ID from project name - * Uses a simple hash to anonymize while maintaining consistency - */ -declare function generateProjectId(projectName: string): string; -/** - * Sanitize error messages to remove any potential PII - */ -declare function sanitizeErrorMessage(error: Error | string): string; -/** - * Sanitize route to remove any user-specific data - */ -declare function sanitizeRoute(route: string): string; - -/** - * Telemetry Configuration Utilities - * - * Manages telemetry settings and opt-out mechanisms - */ - -/** - * Get default telemetry configuration - * Uses lazy evaluation to avoid accessing process.env at module load time - */ -declare function getDefaultTelemetryConfig(): TelemetryConfig; -/** - * Check if telemetry is enabled via environment variables - */ -declare function isTelemetryEnabled(): boolean; -/** - * Get telemetry configuration from environment - */ -declare function getTelemetryConfig(): TelemetryConfig; -/** - * Check if telemetry should be skipped for this event - * Used to implement sampling or rate limiting if needed - */ -declare function shouldSkipEvent(eventName: string, sampleRate?: number): boolean; - -type BlocksFieldConfig = { - blocks: BlockDefinitions; - discriminator: string; -}; -declare function getBlocksFieldConfig(fieldOptions: any): BlocksFieldConfig | null; -declare function parseBlocksValue(value: unknown, config: BlocksFieldConfig): { - value: any[]; - errors: string[]; -}; - -export { generateInstallationId, generateProjectId, generateSlug, getBlocksFieldConfig, getDefaultTelemetryConfig, getTelemetryConfig, isTelemetryEnabled, parseBlocksValue, sanitizeErrorMessage, sanitizeRoute, shouldSkipEvent }; diff --git a/packages/core/dist/utils.d.ts b/packages/core/dist/utils.d.ts deleted file mode 100644 index c823c07de..000000000 --- a/packages/core/dist/utils.d.ts +++ /dev/null @@ -1,90 +0,0 @@ -export { c as FilterCondition, d as FilterGroup, F as FilterOperator, f as QueryFilter, Q as QueryFilterBuilder, h as QueryResult, S as SONICJS_VERSION, T as TemplateRenderer, b as buildQuery, e as escapeHtml, g as getCoreVersion, m as metricsTracker, r as renderTemplate, s as sanitizeInput, a as sanitizeObject, t as templateRenderer } from './version-vktVAxhe.js'; -import { b as TelemetryConfig } from './telemetry-UiD1i9GS.js'; -import { b as BlockDefinitions } from './collection-config-BF95LgQb.js'; - -/** - * Slug generation utilities for creating URL-friendly slugs - */ -/** - * Generate URL-friendly slug from text - * - * Features: - * - Converts to lowercase - * - Handles accented characters (NFD normalization) - * - Removes diacritics - * - Keeps only alphanumeric, spaces, underscores, and hyphens - * - Replaces spaces with hyphens - * - Collapses multiple hyphens/underscores - * - Trims leading/trailing hyphens/underscores - * - Limits length to 100 characters - * - * @param text - Text to slugify - * @returns URL-safe slug - * - * @example - * generateSlug('Hello World!') // 'hello-world' - * generateSlug('Café París 2024') // 'cafe-paris-2024' - * generateSlug('Multiple Spaces') // 'multiple-spaces' - */ -declare function generateSlug(text: string): string; - -/** - * Telemetry ID Utilities - * - * Generates and manages anonymous installation IDs - */ -/** - * Generate a new anonymous installation ID - * Uses globalThis.crypto for Cloudflare Workers compatibility - */ -declare function generateInstallationId(): string; -/** - * Generate a project-specific ID from project name - * Uses a simple hash to anonymize while maintaining consistency - */ -declare function generateProjectId(projectName: string): string; -/** - * Sanitize error messages to remove any potential PII - */ -declare function sanitizeErrorMessage(error: Error | string): string; -/** - * Sanitize route to remove any user-specific data - */ -declare function sanitizeRoute(route: string): string; - -/** - * Telemetry Configuration Utilities - * - * Manages telemetry settings and opt-out mechanisms - */ - -/** - * Get default telemetry configuration - * Uses lazy evaluation to avoid accessing process.env at module load time - */ -declare function getDefaultTelemetryConfig(): TelemetryConfig; -/** - * Check if telemetry is enabled via environment variables - */ -declare function isTelemetryEnabled(): boolean; -/** - * Get telemetry configuration from environment - */ -declare function getTelemetryConfig(): TelemetryConfig; -/** - * Check if telemetry should be skipped for this event - * Used to implement sampling or rate limiting if needed - */ -declare function shouldSkipEvent(eventName: string, sampleRate?: number): boolean; - -type BlocksFieldConfig = { - blocks: BlockDefinitions; - discriminator: string; -}; -declare function getBlocksFieldConfig(fieldOptions: any): BlocksFieldConfig | null; -declare function parseBlocksValue(value: unknown, config: BlocksFieldConfig): { - value: any[]; - errors: string[]; -}; - -export { generateInstallationId, generateProjectId, generateSlug, getBlocksFieldConfig, getDefaultTelemetryConfig, getTelemetryConfig, isTelemetryEnabled, parseBlocksValue, sanitizeErrorMessage, sanitizeRoute, shouldSkipEvent }; diff --git a/packages/core/dist/version-vktVAxhe.d.cts b/packages/core/dist/version-vktVAxhe.d.cts deleted file mode 100644 index 751f10377..000000000 --- a/packages/core/dist/version-vktVAxhe.d.cts +++ /dev/null @@ -1,195 +0,0 @@ -/** - * HTML sanitization utilities for preventing XSS attacks - */ -/** - * Escapes HTML special characters to prevent XSS attacks - * @param text - The text to escape - * @returns The escaped text safe for HTML output - */ -declare function escapeHtml(text: string): string; -/** - * Sanitizes user input by escaping HTML special characters - * This should be used for all user-provided text fields to prevent XSS - * @param input - The input string to sanitize - * @returns The sanitized string - */ -declare function sanitizeInput(input: string | null | undefined): string; -/** - * Sanitizes an object's string properties - * @param obj - Object with string properties to sanitize - * @param fields - Array of field names to sanitize - * @returns New object with sanitized fields - */ -declare function sanitizeObject>(obj: T, fields: (keyof T)[]): T; - -interface TemplateData { - [key: string]: any; -} -declare class TemplateRenderer { - private templateCache; - constructor(); - /** - * Simple Handlebars-like template engine - */ - private renderTemplate; - /** - * Get nested value from object using dot notation - */ - private getNestedValue; - /** - * Title case helper function - */ - private titleCase; - /** - * Render a template string with data - */ - render(template: string, data?: TemplateData): string; - /** - * Clear template cache (useful for development) - */ - clearCache(): void; -} -declare const templateRenderer: TemplateRenderer; -declare function renderTemplate(template: string, data?: TemplateData): string; - -/** - * Query Filter Builder for SonicJS AI - * Supports comprehensive filtering with AND/OR logic - * Compatible with D1 Database (SQLite) - */ -type FilterOperator = 'equals' | 'not_equals' | 'greater_than' | 'greater_than_equal' | 'less_than' | 'less_than_equal' | 'like' | 'contains' | 'in' | 'not_in' | 'all' | 'exists' | 'near' | 'within' | 'intersects'; -interface FilterCondition { - field: string; - operator: FilterOperator; - value: any; -} -interface FilterGroup { - and?: FilterCondition[]; - or?: FilterCondition[]; -} -interface QueryFilter { - where?: FilterGroup; - limit?: number; - offset?: number; - sort?: { - field: string; - order: 'asc' | 'desc'; - }[]; -} -interface QueryResult { - sql: string; - params: any[]; - errors: string[]; -} -/** - * Query Filter Builder - * Converts filter objects into SQL WHERE clauses with parameterized queries - */ -declare class QueryFilterBuilder { - private params; - private errors; - /** - * Build a complete SQL query from filter object - */ - build(baseTable: string, filter: QueryFilter): QueryResult; - /** - * Build WHERE clause from filter group - */ - private buildWhereClause; - /** - * Build a single condition - */ - private buildCondition; - /** - * Build equals condition - */ - private buildEquals; - /** - * Build not equals condition - */ - private buildNotEquals; - /** - * Build comparison condition (>, >=, <, <=) - */ - private buildComparison; - /** - * Build LIKE condition (case-insensitive, all words must be present) - */ - private buildLike; - /** - * Build CONTAINS condition (case-insensitive substring) - */ - private buildContains; - /** - * Build IN condition - */ - private buildIn; - /** - * Build NOT IN condition - */ - private buildNotIn; - /** - * Build ALL condition (value must contain all items in list) - * For SQLite, we'll check if a JSON array contains all values - */ - private buildAll; - /** - * Build EXISTS condition - */ - private buildExists; - /** - * Sanitize field names to prevent SQL injection - */ - private sanitizeFieldName; - /** - * Parse filter from query string - */ - static parseFromQuery(query: Record): QueryFilter; -} -/** - * Helper function to build query from filter - */ -declare function buildQuery(table: string, filter: QueryFilter): QueryResult; - -/** - * Simple in-memory metrics tracker for real-time analytics - * Tracks requests per second using a sliding window - */ -declare class MetricsTracker { - private requests; - private readonly windowSize; - /** - * Record a new request - */ - recordRequest(): void; - /** - * Clean up old requests outside the window - */ - private cleanup; - /** - * Get current requests per second - */ - getRequestsPerSecond(): number; - /** - * Get total requests in the current window - */ - getTotalRequests(): number; - /** - * Get average requests per second over the window - */ - getAverageRPS(): number; -} -declare const metricsTracker: MetricsTracker; - -/** - * Version utility - * - * Provides the current version of @sonicjs-cms/core package - */ -declare const SONICJS_VERSION: string; -/** - * Get the current SonicJS core version - */ -declare function getCoreVersion(): string; - -export { type FilterOperator as F, QueryFilterBuilder as Q, SONICJS_VERSION as S, TemplateRenderer as T, sanitizeObject as a, buildQuery as b, type FilterCondition as c, type FilterGroup as d, escapeHtml as e, type QueryFilter as f, getCoreVersion as g, type QueryResult as h, metricsTracker as m, renderTemplate as r, sanitizeInput as s, templateRenderer as t }; diff --git a/packages/core/dist/version-vktVAxhe.d.ts b/packages/core/dist/version-vktVAxhe.d.ts deleted file mode 100644 index 751f10377..000000000 --- a/packages/core/dist/version-vktVAxhe.d.ts +++ /dev/null @@ -1,195 +0,0 @@ -/** - * HTML sanitization utilities for preventing XSS attacks - */ -/** - * Escapes HTML special characters to prevent XSS attacks - * @param text - The text to escape - * @returns The escaped text safe for HTML output - */ -declare function escapeHtml(text: string): string; -/** - * Sanitizes user input by escaping HTML special characters - * This should be used for all user-provided text fields to prevent XSS - * @param input - The input string to sanitize - * @returns The sanitized string - */ -declare function sanitizeInput(input: string | null | undefined): string; -/** - * Sanitizes an object's string properties - * @param obj - Object with string properties to sanitize - * @param fields - Array of field names to sanitize - * @returns New object with sanitized fields - */ -declare function sanitizeObject>(obj: T, fields: (keyof T)[]): T; - -interface TemplateData { - [key: string]: any; -} -declare class TemplateRenderer { - private templateCache; - constructor(); - /** - * Simple Handlebars-like template engine - */ - private renderTemplate; - /** - * Get nested value from object using dot notation - */ - private getNestedValue; - /** - * Title case helper function - */ - private titleCase; - /** - * Render a template string with data - */ - render(template: string, data?: TemplateData): string; - /** - * Clear template cache (useful for development) - */ - clearCache(): void; -} -declare const templateRenderer: TemplateRenderer; -declare function renderTemplate(template: string, data?: TemplateData): string; - -/** - * Query Filter Builder for SonicJS AI - * Supports comprehensive filtering with AND/OR logic - * Compatible with D1 Database (SQLite) - */ -type FilterOperator = 'equals' | 'not_equals' | 'greater_than' | 'greater_than_equal' | 'less_than' | 'less_than_equal' | 'like' | 'contains' | 'in' | 'not_in' | 'all' | 'exists' | 'near' | 'within' | 'intersects'; -interface FilterCondition { - field: string; - operator: FilterOperator; - value: any; -} -interface FilterGroup { - and?: FilterCondition[]; - or?: FilterCondition[]; -} -interface QueryFilter { - where?: FilterGroup; - limit?: number; - offset?: number; - sort?: { - field: string; - order: 'asc' | 'desc'; - }[]; -} -interface QueryResult { - sql: string; - params: any[]; - errors: string[]; -} -/** - * Query Filter Builder - * Converts filter objects into SQL WHERE clauses with parameterized queries - */ -declare class QueryFilterBuilder { - private params; - private errors; - /** - * Build a complete SQL query from filter object - */ - build(baseTable: string, filter: QueryFilter): QueryResult; - /** - * Build WHERE clause from filter group - */ - private buildWhereClause; - /** - * Build a single condition - */ - private buildCondition; - /** - * Build equals condition - */ - private buildEquals; - /** - * Build not equals condition - */ - private buildNotEquals; - /** - * Build comparison condition (>, >=, <, <=) - */ - private buildComparison; - /** - * Build LIKE condition (case-insensitive, all words must be present) - */ - private buildLike; - /** - * Build CONTAINS condition (case-insensitive substring) - */ - private buildContains; - /** - * Build IN condition - */ - private buildIn; - /** - * Build NOT IN condition - */ - private buildNotIn; - /** - * Build ALL condition (value must contain all items in list) - * For SQLite, we'll check if a JSON array contains all values - */ - private buildAll; - /** - * Build EXISTS condition - */ - private buildExists; - /** - * Sanitize field names to prevent SQL injection - */ - private sanitizeFieldName; - /** - * Parse filter from query string - */ - static parseFromQuery(query: Record): QueryFilter; -} -/** - * Helper function to build query from filter - */ -declare function buildQuery(table: string, filter: QueryFilter): QueryResult; - -/** - * Simple in-memory metrics tracker for real-time analytics - * Tracks requests per second using a sliding window - */ -declare class MetricsTracker { - private requests; - private readonly windowSize; - /** - * Record a new request - */ - recordRequest(): void; - /** - * Clean up old requests outside the window - */ - private cleanup; - /** - * Get current requests per second - */ - getRequestsPerSecond(): number; - /** - * Get total requests in the current window - */ - getTotalRequests(): number; - /** - * Get average requests per second over the window - */ - getAverageRPS(): number; -} -declare const metricsTracker: MetricsTracker; - -/** - * Version utility - * - * Provides the current version of @sonicjs-cms/core package - */ -declare const SONICJS_VERSION: string; -/** - * Get the current SonicJS core version - */ -declare function getCoreVersion(): string; - -export { type FilterOperator as F, QueryFilterBuilder as Q, SONICJS_VERSION as S, TemplateRenderer as T, sanitizeObject as a, buildQuery as b, type FilterCondition as c, type FilterGroup as d, escapeHtml as e, type QueryFilter as f, getCoreVersion as g, type QueryResult as h, metricsTracker as m, renderTemplate as r, sanitizeInput as s, templateRenderer as t }; diff --git a/packages/core/src/app.ts b/packages/core/src/app.ts index b3487d277..6d69e2380 100644 --- a/packages/core/src/app.ts +++ b/packages/core/src/app.ts @@ -30,6 +30,7 @@ import { getCoreVersion } from './utils/version' import { bootstrapMiddleware } from './middleware/bootstrap' import { metricsMiddleware } from './middleware/metrics' import { csrfProtection } from './middleware/csrf' +import { securityHeadersMiddleware } from './middleware/security-headers' import { createDatabaseToolsAdminRoutes } from './plugins/core-plugins/database-tools-plugin/admin-routes' import { createSeedDataAdminRoutes } from './plugins/core-plugins/seed-data-plugin/admin-routes' import { emailPlugin } from './plugins/core-plugins/email-plugin' @@ -166,10 +167,7 @@ export function createSonicJSApp(config: SonicJSConfig = {}): SonicJSApp { }) // Security middleware - app.use('*', async (_c, next) => { - // Security headers, CORS, etc. - await next() - }) + app.use('*', securityHeadersMiddleware()) // CSRF protection middleware app.use('*', csrfProtection()) diff --git a/packages/core/src/middleware/index.ts b/packages/core/src/middleware/index.ts index 0aea2f854..84377fb62 100644 --- a/packages/core/src/middleware/index.ts +++ b/packages/core/src/middleware/index.ts @@ -34,7 +34,7 @@ export const securityLoggingMiddleware: any = () => async (_c: any, next: any) = export const performanceLoggingMiddleware: any = () => async (_c: any, next: any) => await next() export const cacheHeaders: any = () => async (_c: any, next: any) => await next() export const compressionMiddleware: any = async (_c: any, next: any) => await next() -export const securityHeaders: any = () => async (_c: any, next: any) => await next() +export { securityHeadersMiddleware as securityHeaders } from './security-headers' // Other stubs export const PermissionManager: any = {} diff --git a/packages/core/src/middleware/security-headers.ts b/packages/core/src/middleware/security-headers.ts new file mode 100644 index 000000000..ef94b797e --- /dev/null +++ b/packages/core/src/middleware/security-headers.ts @@ -0,0 +1,23 @@ +import { Context, Next } from 'hono' + +/** + * Security headers middleware. + * Sets standard security headers on every response. + * Skips HSTS in development to avoid local dev issues. + */ +export const securityHeadersMiddleware = () => { + return async (c: Context, next: Next) => { + await next() + + c.header('X-Content-Type-Options', 'nosniff') + c.header('X-Frame-Options', 'SAMEORIGIN') + c.header('Referrer-Policy', 'strict-origin-when-cross-origin') + c.header('Permissions-Policy', 'camera=(), microphone=(), geolocation=()') + + // Only set HSTS in non-development environments + const environment = (c.env as any)?.ENVIRONMENT + if (environment !== 'development') { + c.header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains') + } + } +}