{"version":3,"file":"db-repair.cjs","names":["diagnosePlugin"],"sources":["../../src/cli/db-repair.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { type DoctorReport, diagnosePlugin } from \"./db-doctor\";\nimport type { PluginDbInfo } from \"./db-studio\";\n\nexport interface RepairResult {\n  status: \"repaired\" | \"refused\" | \"error\";\n  diagnosis: DoctorReport;\n  message: string;\n}\n\nexport async function repairPlugin(\n  info: PluginDbInfo,\n  mode: \"history-reset\" | \"recreate\",\n): Promise<RepairResult> {\n  const diagnosis = await diagnosePlugin(info);\n\n  if (diagnosis.diagnosis === \"error\") {\n    return {\n      status: \"refused\",\n      diagnosis,\n      message: `Cannot repair — diagnosis failed: ${diagnosis.error}`,\n    };\n  }\n\n  if (mode === \"recreate\") {\n    return {\n      status: \"refused\",\n      diagnosis,\n      message:\n        \"Recreate mode is not supported without per-plugin database schemas. Use --mode history-reset instead.\",\n    };\n  }\n\n  if (diagnosis.diagnosis !== \"drift-safe-repair\") {\n    if (diagnosis.diagnosis === \"healthy\") {\n      return { status: \"refused\", diagnosis, message: \"Database is healthy — no repair needed.\" };\n    }\n    if (diagnosis.diagnosis === \"no-local-migrations\") {\n      return {\n        status: \"refused\",\n        diagnosis,\n        message: \"No local migrations found for this plugin.\",\n      };\n    }\n    if (diagnosis.diagnosis === \"drift-manual\") {\n      return {\n        status: \"refused\",\n        diagnosis,\n        message:\n          `Partial drift detected (${diagnosis.missingTables.length}/${diagnosis.expectedTables.length} tables missing). ` +\n          \"Manual intervention required — some tables exist but schema is incomplete.\",\n      };\n    }\n    if (diagnosis.diagnosis === \"unapplied\") {\n      return {\n        status: \"refused\",\n        diagnosis,\n        message: \"Migrations have not been applied yet. Start the dev server to apply them.\",\n      };\n    }\n    if (diagnosis.diagnosis === \"untracked-existing-schema\") {\n      return {\n        status: \"refused\",\n        diagnosis,\n        message:\n          \"Tables exist but no matching migration history was found. \" +\n          \"Run `drizzle-kit pull --init` in the plugin workspace to adopt the existing schema, \" +\n          \"then run migrations from that baseline.\",\n      };\n    }\n    return {\n      status: \"refused\",\n      diagnosis,\n      message: `Cannot repair — diagnosis: ${diagnosis.diagnosis}`,\n    };\n  }\n\n  // drift-safe-repair: drop the journal and replay\n  const { Pool } = await import(\"pg\");\n  const journalRef = `\"${diagnosis.journalSchema}\".\"${diagnosis.journalTable}\"`;\n  const pool = new Pool({\n    connectionString: info.databaseUrl,\n    ssl:\n      info.databaseUrl.includes(\"localhost\") || info.databaseUrl.includes(\"127.0.0.1\")\n        ? false\n        : { rejectUnauthorized: false },\n    max: 1,\n    connectionTimeoutMillis: 10_000,\n  });\n\n  try {\n    await pool.query(`DROP TABLE IF EXISTS ${journalRef}`);\n\n    if (info.workspaceDir) {\n      const configPath = join(info.workspaceDir, \"drizzle.config.ts\");\n      if (existsSync(configPath)) {\n        try {\n          await spawnDrizzleMigrate(info.workspaceDir, configPath);\n          return {\n            status: \"repaired\",\n            diagnosis,\n            message:\n              `Migration history reset for ${diagnosis.plugin}. ` +\n              `Migrations reapplied via drizzle-kit. Restart the dev server to confirm.`,\n          };\n        } catch (error) {\n          return {\n            status: \"repaired\",\n            diagnosis,\n            message:\n              `Migration history reset for ${diagnosis.plugin}. ` +\n              `Automatic reapply failed: ${error instanceof Error ? error.message : String(error)}. ` +\n              `Run \\`bun run --cwd ${info.workspaceDir} db:migrate\\` manually.`,\n          };\n        }\n      }\n    }\n  } catch (error) {\n    return {\n      status: \"error\",\n      diagnosis,\n      message: `Repair failed: ${error instanceof Error ? error.message : String(error)}`,\n    };\n  } finally {\n    await pool.end().catch(() => {});\n  }\n\n  return {\n    status: \"repaired\",\n    diagnosis,\n    message:\n      `Migration history reset for ${diagnosis.plugin}. ` +\n      \"No local drizzle.config.ts found — start the dev server to reapply migrations.\",\n  };\n}\n\nfunction spawnDrizzleMigrate(cwd: string, configPath: string): Promise<void> {\n  return new Promise((resolvePromise, reject) => {\n    const child = spawn(\"npx\", [\"drizzle-kit\", \"migrate\", \"--config\", configPath], {\n      cwd,\n      stdio: \"pipe\",\n      shell: true,\n    });\n\n    let stderr = \"\";\n    child.stderr?.on(\"data\", (data: Buffer) => {\n      stderr += data.toString();\n    });\n\n    child.on(\"error\", (err) => reject(err));\n\n    child.on(\"exit\", (code) => {\n      if (code === 0) {\n        resolvePromise();\n      } else {\n        reject(new Error(`drizzle-kit migrate exited with code ${code}: ${stderr}`));\n      }\n    });\n  });\n}\n"],"mappings":";;;;;;AAYA,eAAsB,aACpB,MACA,MACuB;CACvB,MAAM,YAAY,MAAMA,iCAAe,IAAI;CAE3C,IAAI,UAAU,cAAc,SAC1B,OAAO;EACL,QAAQ;EACR;EACA,SAAS,qCAAqC,UAAU;CAC1D;CAGF,IAAI,SAAS,YACX,OAAO;EACL,QAAQ;EACR;EACA,SACE;CACJ;CAGF,IAAI,UAAU,cAAc,qBAAqB;EAC/C,IAAI,UAAU,cAAc,WAC1B,OAAO;GAAE,QAAQ;GAAW;GAAW,SAAS;EAA0C;EAE5F,IAAI,UAAU,cAAc,uBAC1B,OAAO;GACL,QAAQ;GACR;GACA,SAAS;EACX;EAEF,IAAI,UAAU,cAAc,gBAC1B,OAAO;GACL,QAAQ;GACR;GACA,SACE,2BAA2B,UAAU,cAAc,OAAO,GAAG,UAAU,eAAe,OAAO;EAEjG;EAEF,IAAI,UAAU,cAAc,aAC1B,OAAO;GACL,QAAQ;GACR;GACA,SAAS;EACX;EAEF,IAAI,UAAU,cAAc,6BAC1B,OAAO;GACL,QAAQ;GACR;GACA,SACE;EAGJ;EAEF,OAAO;GACL,QAAQ;GACR;GACA,SAAS,8BAA8B,UAAU;EACnD;CACF;CAGA,MAAM,EAAE,SAAS,MAAM,OAAO;CAC9B,MAAM,aAAa,IAAI,UAAU,cAAc,KAAK,UAAU,aAAa;CAC3E,MAAM,OAAO,IAAI,KAAK;EACpB,kBAAkB,KAAK;EACvB,KACE,KAAK,YAAY,SAAS,WAAW,KAAK,KAAK,YAAY,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