import T from"node:path";import{unlink as h}from"node:fs/promises";import{writeFileSync as y}from"node:fs";import{readEnvVariable as S}from"../../server/utils/envs/read-env-variable.js";import{PORTAL_VERSION as A}from"../../server/version.js";import{logger as e}from"../../server/tools/notifiers/logger.js";import{reporter as b}from"../../server/tools/notifiers/reporter.js";import{exit as O}from"../../server/utils/process/exit.js";import{promiseMapLimit as E,ensureDir as v}from"../../server/utils/index.js";import{initPlugins as D,runPlugins as M,writeClientEntries as _}from"../../server/plugins/lifecycle.js";import{createClientCompiler as x,createNodeBundleCompiler as L}from"../../server/esbuild/esbuild.js";import{validateAllMarkdowns as F}from"../../server/plugins/markdown/compiler.js";import{copyEnvFiles as J}from"./copy-env-files.js";import{EsbuildError as m,esbuildLogger as p}from"../../server/esbuild/esbuild-logger.js";import{reportAllErrors as j}from"../../server/utils/report-all-errors.js";import{collectAnalytics as k}from"./analytics/collect-analytics.js";import{copyMigrationsFolder as U}from"../../server/providers/database/copy-migrations.js";import{validateReactPages as z}from"../../server/utils/reporter/validate-react-pages.js";import{telemetry as s}from"../telemetry/index.js";import{telemetryTraceStep as c}from"../telemetry/helpers/trace-step.js";async function oi(C,i){s.initialize(A),e.info("Starting project build.");const P=e.startTiming();await c("build.start",async R=>{_(i);const d=await x(i,i.outdir,"production"),u=await L(i,i.serverOutDir,"production");let n,f;try{await c("build.client_compilation",async()=>{const l=e.startTiming(),o=await d.rebuild().catch(a=>{throw new m(a)});Array.isArray(o.warnings)&&p(new m({warnings:o.warnings}));const r=e.infoTime(l,"Client JavaScript compiled");r&&s.sendTimingPerformedMessage(r)}),await c("build.server_compilation",async()=>{const l=e.startTiming(),o=await u.rebuild().catch(a=>{throw new m(a)});Array.isArray(o.warnings)&&p(new m({warnings:o.warnings}));const r=e.infoTime(l,"Server JavaScript compiled");r&&s.sendTimingPerformedMessage({message:r.message,timeMs:r.timeMs})}),await i.reloadMarkdocOptions();let t;({pluginInstances:t,lifecycleContext:n}=await D({outdir:i.outdir,serverOutDir:i.serverOutDir,contentDir:i.contentDir,devLogin:C.devLogin,setGlobalConfig:i.setGlobalConfig})),n.fs.dispose(),i.lifecycleContext=n,U(i),await M(t,i,n),f=k(i,n),await c("build.client_server_recompile",async()=>{const l=e.startTiming();e.info("Re-compiling JavaScript with user code"),(await Promise.all([d.rebuild(),u.rebuild()]).catch(a=>{throw new m(a)})).forEach(({warnings:a})=>{Array.isArray(a)&&p(new m({warnings:a}))});const r=e.infoTime(l,"JavaScript re-compiled");r&&s.sendTimingPerformedMessage(r)}),await c("build.pages_validation",async()=>{await z(i,n),await F(i,n)}),await j(n),i.markUserCodeReady()}catch(t){R?.error(t),t instanceof m&&p(t)}finally{f&&await f.catch(()=>{}),await s.forceFlush(),await d.dispose(),await u.dispose()}b.printErrors(),e.info("Rendering pages..."),await c("build.prepare_static_data",async t=>{const l=e.startTiming(),o=[...i.getAllRoutes(),...i.getAllApiRoutes()];t?.setAttribute("totalRoutes",o.length.toString()),await E(o,15,a=>i.writeRouteStaticData(a,n));const r=e.successTime(l,"Page static data prepared.");r&&s.sendTimingPerformedMessage(r)}),await c("build.store_serialization",async()=>{const t=e.startTiming();v(i.serverOutDir),y(T.join(i.serverOutDir,"store.json"),JSON.stringify(i.toJson())),e.successTime(t,"Store serialized and written."),J(i)});const g=S("REDOCLY_PROBLEMS_OUTPUT_FILE");if(g){const t=e.startTiming();y(v(g),JSON.stringify(b.getProblems()),"utf-8"),e.successTime(t,"Broken links written.")}await h(T.join(i.serverOutDir,"index.css"));const w=e.successTime(P,"All done");w&&s.sendTimingPerformedMessage(w)}),await s.forceFlush(),O(0)}export{oi as prepare};
