import { f as defineAdminEventHandler, h as requireAdminRole, L as getPluginRuntimeManager, bP as HookRegistry, bX as RouteRegistry, bY as ServiceRegistry, bZ as PolicyRegistry, b_ as MiddlewareRegistry, b$ as AdminExtensionRegistry, c0 as PluginDataLayerRegistry, b as getDatabaseManager, c1 as VERSION, c2 as resolveSchemasDir, a as getSchemaManager, c3 as getJobStats, b7 as getSchedules, c4 as getJobs, c5 as getJobQueue, c6 as getRegisteredHandlerNames, c7 as getAllWebhooks, c8 as getDeadLetterLogs, c9 as getWebhookStats, as as config } from '../../../nitro/nitro.mjs';
import 'node:crypto';
import 'jsonwebtoken';
import 'node:fs';
import 'node:module';
import 'node:path';
import 'node:url';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'pino';
import 'drizzle-orm/better-sqlite3';
import 'drizzle-orm/node-postgres';
import 'drizzle-orm/mysql2';
import 'better-sqlite3';
import 'pg';
import 'mysql2/promise';
import 'drizzle-orm';
import 'fs';
import 'path';
import 'prom-client';
import 'bcryptjs';
import '@node-rs/argon2';
import 'node:async_hooks';
import 'crypto';
import 'node:dns';
import 'node:util';
import 'node:net';
import 'fs/promises';
import 'url';
import 'semver';

function getErrorMessage(error) {
  return error instanceof Error ? error.message : String(error);
}
function isEnabled(value) {
  return value === true || value === 1;
}
function getSchemaRegistryDiagnostics() {
  try {
    const schemasDir = resolveSchemasDir();
    const schemaManager = getSchemaManager();
    const schemas = schemaManager.getAllSchemas();
    const schemaEntries = schemas.map((schema) => {
      var _a, _b, _c, _d;
      const singularName = schema.info.singularName;
      return {
        singularName,
        displayName: schema.info.displayName,
        kind: schema.kind,
        attributes: Object.keys((_a = schema.attributes) != null ? _a : {}).length,
        draftAndPublish: Boolean((_b = schema.options) == null ? void 0 : _b.draftAndPublish),
        localized: Boolean((_d = (_c = schema.options) == null ? void 0 : _c.i18n) == null ? void 0 : _d.enabled),
        hidden: schemaManager.isHiddenSchema(singularName),
        system: schemaManager.isSystemSchema(singularName),
        filePath: schemaManager.schemaFileExists(singularName) ? schemaManager.getSchemaFilePath(singularName) : null
      };
    });
    return {
      schemasDir,
      total: schemaEntries.length,
      visible: schemaEntries.filter((schema) => !schema.hidden).length,
      hidden: schemaEntries.filter((schema) => schema.hidden).length,
      system: schemaEntries.filter((schema) => schema.system).length,
      schemas: schemaEntries,
      error: null
    };
  } catch (error) {
    return {
      schemasDir: resolveSchemasDir(),
      total: 0,
      visible: 0,
      hidden: 0,
      system: 0,
      schemas: [],
      error: getErrorMessage(error)
    };
  }
}
async function getJobsDiagnostics() {
  try {
    const [stats, scheduledJobs, recentFailedJobs] = await Promise.all([
      getJobStats(),
      getSchedules(),
      getJobs({ status: ["failed", "cancelled"] }, 10, 0)
    ]);
    let queueInitialized = false;
    try {
      getJobQueue();
      queueInitialized = true;
    } catch {
      queueInitialized = false;
    }
    return {
      queueInitialized,
      handlers: getRegisteredHandlerNames(),
      stats,
      scheduledJobs: scheduledJobs.map((job) => ({
        id: job.id,
        name: job.name,
        queue: job.queue,
        cronExpression: job.cronExpression,
        enabled: job.enabled,
        lastRunAt: job.lastRunAt,
        nextRunAt: job.nextRunAt
      })),
      recentFailures: recentFailedJobs.data.map((job) => ({
        id: job.id,
        name: job.name,
        queue: job.queue,
        status: job.status,
        attempts: job.attempts,
        maxAttempts: job.maxAttempts,
        error: job.error,
        updatedAt: job.updatedAt
      })),
      error: null
    };
  } catch (error) {
    return {
      queueInitialized: false,
      handlers: [],
      stats: {
        total: 0,
        byStatus: {},
        byQueue: {}
      },
      scheduledJobs: [],
      recentFailures: [],
      error: getErrorMessage(error)
    };
  }
}
async function getWebhookDiagnostics() {
  try {
    const webhooks = await getAllWebhooks();
    const [statsByWebhook, deadLetters] = await Promise.all([
      Promise.all(
        webhooks.map(async (webhook) => ({
          id: webhook.id,
          stats: await getWebhookStats(webhook.id)
        }))
      ),
      getDeadLetterLogs(10)
    ]);
    const statsMap = new Map(statsByWebhook.map((entry) => [entry.id, entry.stats]));
    const items = webhooks.map((webhook) => {
      var _a, _b, _c, _d, _e;
      const stats = statsMap.get(webhook.id);
      return {
        id: webhook.id,
        name: webhook.name,
        url: webhook.url,
        enabled: isEnabled(webhook.enabled),
        consecutiveFailures: (_a = webhook.consecutive_failures) != null ? _a : 0,
        autoDisabledAt: webhook.auto_disabled_at,
        lastTriggeredAt: webhook.last_triggered_at,
        lastSuccessAt: webhook.last_success_at,
        totalDeliveries: (_b = stats == null ? void 0 : stats.totalDeliveries) != null ? _b : 0,
        failedCount: (_c = stats == null ? void 0 : stats.failedCount) != null ? _c : 0,
        deadLetterCount: (_d = stats == null ? void 0 : stats.deadLetterCount) != null ? _d : 0,
        successRate: (_e = stats == null ? void 0 : stats.successRate) != null ? _e : 0
      };
    });
    const deliveryTotals = items.reduce(
      (acc, webhook) => {
        acc.total += webhook.totalDeliveries;
        acc.failed += webhook.failedCount;
        acc.deadLetter += webhook.deadLetterCount;
        acc.success += Math.max(
          webhook.totalDeliveries - webhook.failedCount - webhook.deadLetterCount,
          0
        );
        return acc;
      },
      { total: 0, success: 0, failed: 0, deadLetter: 0 }
    );
    return {
      total: items.length,
      enabled: items.filter((webhook) => webhook.enabled).length,
      autoDisabled: items.filter((webhook) => webhook.autoDisabledAt).length,
      deliveryTotals,
      items,
      deadLetters: deadLetters.map((log) => ({
        id: log.id,
        webhookId: log.webhook_id,
        webhookName: log.webhook_name,
        event: log.event,
        status: log.status,
        attempt: log.attempt,
        createdAt: log.created_at,
        error: log.error
      })),
      error: null
    };
  } catch (error) {
    return {
      total: 0,
      enabled: 0,
      autoDisabled: 0,
      deliveryTotals: { total: 0, success: 0, failed: 0, deadLetter: 0 },
      items: [],
      deadLetters: [],
      error: getErrorMessage(error)
    };
  }
}
function getConfigDiagnostics() {
  try {
    const initialized = config.isInitialized();
    if (!initialized) {
      return {
        initialized,
        cacheSize: config.cacheSize(),
        totals: {
          settings: 0,
          envOverrides: 0,
          locked: 0,
          restartRequired: 0
        },
        categories: [],
        settings: [],
        error: null
      };
    }
    const groupedSettings = config.getAllGrouped();
    const settings = Object.entries(groupedSettings).flatMap(
      ([category, entries]) => entries.map((entry) => ({
        key: entry.key,
        category,
        source: entry.source,
        locked: entry.locked,
        restartRequired: entry.restartRequired
      }))
    );
    const categories = Object.entries(groupedSettings).map(([key, entries]) => ({
      key,
      total: entries.length,
      envOverrides: entries.filter((entry) => entry.source === "env").length,
      locked: entries.filter((entry) => entry.locked).length,
      restartRequired: entries.filter((entry) => entry.restartRequired).length
    }));
    return {
      initialized,
      cacheSize: config.cacheSize(),
      totals: {
        settings: settings.length,
        envOverrides: settings.filter((entry) => entry.source === "env").length,
        locked: settings.filter((entry) => entry.locked).length,
        restartRequired: settings.filter((entry) => entry.restartRequired).length
      },
      categories,
      settings,
      error: null
    };
  } catch (error) {
    return {
      initialized: config.isInitialized(),
      cacheSize: config.cacheSize(),
      totals: {
        settings: 0,
        envOverrides: 0,
        locked: 0,
        restartRequired: 0
      },
      categories: [],
      settings: [],
      error: getErrorMessage(error)
    };
  }
}
const devtools_get = defineAdminEventHandler("admin:devtools:get", async (event) => {
  var _a, _b, _c;
  await requireAdminRole(event, ["super-admin"]);
  const system = {
    version: VERSION,
    nodeVersion: process.version,
    platform: process.platform,
    arch: process.arch,
    uptime: process.uptime(),
    memoryUsage: process.memoryUsage(),
    environment: "production",
    pid: process.pid
  };
  const manager = getPluginRuntimeManager();
  const registry = manager == null ? void 0 : manager.getRegistry();
  const plugins = registry ? registry.getAll().map((entry) => {
    var _a2;
    return {
      name: entry.definition.manifest.name,
      displayName: entry.definition.manifest.displayName,
      version: entry.definition.manifest.version,
      description: entry.definition.manifest.description,
      phase: entry.state.phase,
      enabled: entry.state.enabled,
      error: entry.state.error ? {
        phase: entry.state.error.phase,
        message: entry.state.error.message
      } : null,
      timing: entry.timing,
      extensionSource: (_a2 = entry.extensionSource) != null ? _a2 : "unknown",
      updatedAt: entry.state.updatedAt
    };
  }) : [];
  const hookNames = HookRegistry.hookNames();
  const hooks = hookNames.map((name) => ({
    name,
    listenerCount: HookRegistry.listenerCount(name)
  }));
  const routes = RouteRegistry.getAll().map((r) => {
    var _a2;
    return {
      method: r.method,
      path: r.path,
      pluginName: r.pluginName,
      policies: (_a2 = r.options) == null ? void 0 : _a2.policies
    };
  });
  const services = ServiceRegistry.list().map((s) => ({
    name: s.name,
    pluginName: s.pluginName,
    registeredAt: s.registeredAt
  }));
  const policies = PolicyRegistry.list().map((p) => ({
    name: p.name,
    pluginName: p.pluginName,
    description: p.description
  }));
  const allMiddleware = MiddlewareRegistry.getAll();
  const middleware = {
    admin: ((_a = allMiddleware.admin) != null ? _a : []).map((m) => ({
      name: m.name,
      order: m.order,
      enabled: m.enabled,
      routes: m.routes
    })),
    content: ((_b = allMiddleware.content) != null ? _b : []).map((m) => ({
      name: m.name,
      order: m.order,
      enabled: m.enabled,
      contentTypes: m.contentTypes,
      operations: m.operations
    })),
    system: ((_c = allMiddleware.system) != null ? _c : []).map((m) => ({
      name: m.name,
      order: m.order,
      enabled: m.enabled,
      events: m.events
    }))
  };
  const adminExtensions = AdminExtensionRegistry.getAll().map((ext) => ({
    pluginName: ext.pluginName,
    displayName: ext.displayName,
    version: ext.version,
    navigationItems: ext.navigationItems.length,
    pages: ext.pages.length,
    settingsSections: ext.settingsSections.length,
    dashboardWidgets: ext.dashboardWidgets.length,
    injectionZones: ext.injectionZones.length,
    fieldExtensions: ext.fieldExtensions.length
  }));
  const dataLayer = {
    contentTypes: PluginDataLayerRegistry.getContentTypes().map((c) => ({
      pluginName: c.pluginName,
      singularName: c.schema.info.singularName,
      source: c.source
    })),
    components: PluginDataLayerRegistry.getComponents().map((c) => ({
      pluginName: c.pluginName,
      uid: c.component.uid,
      source: c.source
    })),
    migrations: PluginDataLayerRegistry.getMigrations().map((m) => ({
      pluginName: m.pluginName,
      name: m.name,
      source: m.source
    })),
    seeds: PluginDataLayerRegistry.getSeeds().map((s) => ({
      pluginName: s.pluginName,
      name: s.name,
      source: s.source
    }))
  };
  let database = {
    connected: false,
    dialect: "unknown"
  };
  try {
    const dbManager = getDatabaseManager();
    const status = await dbManager.getStatus();
    const tables = await dbManager.getTables();
    database = {
      connected: status.connected,
      dialect: status.dialect,
      tables: tables.length
    };
  } catch {
  }
  const [schemaRegistry, jobs, webhooks, configState] = await Promise.all([
    getSchemaRegistryDiagnostics(),
    getJobsDiagnostics(),
    getWebhookDiagnostics(),
    getConfigDiagnostics()
  ]);
  return {
    success: true,
    data: {
      system,
      plugins,
      hooks,
      routes,
      services,
      policies,
      middleware,
      adminExtensions,
      dataLayer,
      database,
      schemaRegistry,
      jobs,
      webhooks,
      config: configState
    }
  };
});

export { devtools_get as default };
//# sourceMappingURL=devtools.get.mjs.map
