/* PLAN 349-0k sub7 헬퍼 — 열기 → 노선 꼭짓점 끌기 → 되돌리기(초안 버림)면 상세 = 열 때 저장 정본 그대로. * 진짜 TS(`design_pipeline_page` · 단계 파일 · 상세 가게 `B06_Section_Section_Store`)를 트랜스파일해 Node 로 · * 서버 창구만 가짜. 종단 보기 고리 흉내 = `design_view_profile_sections.followSwap`(가게 stations → 갈아끼움 · * 새 상세 → render) · `design_view_profile` 의 `holdDraft`(초안 전 상태 · 되돌림) 그대로. 초안 동안 갈아끼운 횡단은 * 브라우저 다시 셈 흉내로 면적을 바꿔 둠(옛 길이면 되돌린 뒤 그 값이 남음). * 입력 argv[2] JSON · argv[3] 격자 이진. 결과 = 표준출력 JSON. 짝 = `test_349_0k_undo_saved.py`. */ const fs = require("fs"); const path = require("path"); const ts = require(path.join(__dirname, "..", "..", "config", "node_modules", "typescript")); const CATALOG = require("./helper_322_catalog_module.cjs"); const ROOT = path.join(__dirname, "..", ".."); const job = JSON.parse(fs.readFileSync(process.argv[2], "utf8")); function memoryStorage() { const map = new Map(); return { getItem: (key) => (map.has(key) ? map.get(key) : null), setItem: (key, value) => map.set(key, String(value)), removeItem: (key) => map.delete(key), key: (index) => [...map.keys()][index] ?? null, get length() { return map.size; }, }; } globalThis.window = { sessionStorage: memoryStorage(), localStorage: memoryStorage(), setTimeout, clearTimeout, }; // 흙 배분 서버 — 늦게 답함 · 끊기면 버림 globalThis.fetch = (url, init) => new Promise((resolve, reject) => { const timer = setTimeout( () => resolve({ ok: true, json: async () => ({ haul_plan: { blocks: [], url } }) }), 20, ); init.signal.addEventListener("abort", () => { clearTimeout(timer); reject(new Error("aborted")); }); }); const STUBS = {}; const cache = new Map(); function loadTs(full) { if (cache.has(full)) return cache.get(full); const js = ts.transpileModule(fs.readFileSync(full, "utf8"), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, }).outputText; const box = { exports: {} }; cache.set(full, box.exports); const localRequire = (request) => { if (CATALOG.isCatalogRequest(request)) return CATALOG; const key = Object.keys(STUBS).find((name) => request.endsWith(name)); if (key) return STUBS[key]; if (request.startsWith("@config/")) return { API_BASE_URL: "http://fake" }; if (request.startsWith("@ui/")) return { showToast: () => undefined }; if (request.endsWith(".css")) return {}; if (request.endsWith(".json")) return require(path.join(path.dirname(full), request)); if (request.startsWith("@util/")) return loadTs(path.join(ROOT, "common_util", `${request.slice(6)}.ts`)); if (request.startsWith(".")) return loadTs(path.join(path.dirname(full), `${request}.ts`)); return require(request); }; new Function("exports", "module", "require", js)(box.exports, box, localRequire); return box.exports; } const load = (...parts) => loadTs(path.join(ROOT, ...parts)); const sampler = load("common_util", "common_util_surface_sampler.ts"); const bytes = fs.readFileSync(process.argv[3]); const grid = sampler.parseDtmGrid( bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length), ); const local = { grid, design: "las" }; STUBS["B05_Profile_Api_Replan"] = { analysisTerrain: () => "las", fetchRoutePlan: async () => ({ planned: job.line, curves: job.curves, min_radius_m: job.minRadius, station_snap: job.stationSnap, }), }; STUBS["B05_Profile_Api_Structures"] = { fetchStructures: async () => ({ structures: [] }), fetchStructureTypes: async () => job.types, readPendingStructures: () => null, }; STUBS["B05_Profile_Api_TerrainGrid"] = { loadDesignTerrainGrid: async () => local, groundStageDeps: () => ({ grid: () => local, remote: async () => [] }), }; STUBS["B04_PreProcess_Api_Fetch"] = { fetchDetailPipePoints: async () => ({ pipe_points: job.pipes.map((pipe) => ({ ...pipe, lonlat: [0, 0] })), }), }; STUBS["B06_Section_UI_Standard_Panel"] = { effectiveStandardCross: () => job.standard, readRockBoundaryDefault: () => -0.5, }; // 구조물 초안 얹기(측점 계획 · 형상) — 이 시험 밖 · 아무 일 없음 STUBS["B06_Section_Section_Drafts"] = { withDraftStations: async () => undefined, withDraftShapes: async () => undefined, forgetDraftStations: () => undefined, }; STUBS["B06_Section_Api_Fetch"] = { fetchSectionDetail: async () => JSON.parse(JSON.stringify(job.detail)), saveSections: async () => undefined, }; const pageMod = load("A00_Common", "design", "design_pipeline_page.ts"); const storeMod = load("A00_Common", "design", "design_store.ts"); const sectionStore = load("B06_Section", "B06_Section_Section_Store.ts"); const alignment = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Alignment.ts"); const massHaul = load("common_util", "common_util_mass_haul.ts"); const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms)); const runs = () => globalThis.__aisloPipeline?.runs ?? []; /** 묶음 · 상세 가게가 조용해질 때까지 — 마지막 기록이 끝나고 새 기록이 더 안 생김. */ async function quiet() { let seen = -1; for (let i = 0; i < 400; i += 1) { await tick(15); const last = runs()[runs().length - 1]; const count = runs().length; if (count === seen && (!last || last.outcome !== "running")) return; seen = count; } throw new Error("묶음이 조용해지지 않음"); } const n = job.nodes.length; const draftOf = (nodes) => ({ nodes, curveOn: Array(n).fill(true), curveRadius: Array(n).fill(null), curveLock: Array(n).fill(null), curveArc: Array(n).fill(null), stationSnap: job.stationSnap, }); const shift = (index, dx, dy) => job.nodes.map((node, i) => (i === index ? [node[0] + dx, node[1] + dy] : node)); const sliceRuns = (mark) => runs() .slice(mark) .map((r) => ({ sources: r.sources, outcome: r.outcome })); const finalOf = (detail) => { const [series] = massHaul.computeMassHaulSeries( detail.longitudinal, detail.cross_sections, job.conversion, undefined, ["cross"], ); const points = series?.result.points ?? []; return points.length ? points[points.length - 1].cumulative_volume_m3 : null; }; const crossOf = (detail) => JSON.stringify(detail.cross_sections.map((s) => [s.chainage_m, s.design, s.samples])); /** 브라우저 다시 셈 흉내 — 면적 칸(`*_m2`)을 두 배로(카드 · 종단도가 갈아끼운 상세 횡단을 다시 셈). */ const recompute = (detail) => detail.cross_sections.forEach((section) => { if (!section.design) return; const design = { ...section.design }; for (const [key, value] of Object.entries(design)) if (key.endsWith("_m2") && typeof value === "number") design[key] = value * 2; section.design = design; }); async function run() { const P = "proj-349k"; const R = 7; window.localStorage.setItem("frd_current_project_id", P); const savedAlignment = job.detail.longitudinal.profile_alignment; const savedBase = alignment.toAlignmentBase(savedAlignment); let detail = await sectionStore.loadSectionDetail(P, R); const opened = detail; const link = { pipelineSource: () => ({ base: savedBase, edits: savedAlignment.edits, detail, routeId: R }), adoptPipeline: (base, edits, draft) => pageMod.pipelineGrade(P, draft ? edits : savedAlignment.edits), redraw: () => undefined, side: null, }; const swaps = []; const restores = []; pageMod.routeDraftBridge(P, link, { stationIntervalM: job.interval, // `design_view_profile` 의 holdDraft 그대로(349-0o) holdDraft: (routeId, saved) => { const hold = saved && sectionStore.holdSectionDetail(P, routeId, saved); return async (stations) => { if (!hold) { restores.push({ saved: false, back: null }); await sectionStore.swapSectionStations(P, routeId, stations); return "no-saved"; } const back = await sectionStore.restoreSectionDetail(P, routeId, hold, stations); restores.push({ saved: true, back: back ? { same: back.same } : null }); return !back ? "no-cache" : back.same ? "saved" : "saved-diff"; }; }, }); // followSwap — 새 상세 → 종단도 render(처음부터 다시 · 비정규 측점) · 가게 stations → 갈아끼움 const stopListen = sectionStore.subscribeSectionDetail(P, R, (next) => { swaps.push(next.cross_sections.length); detail = next; pageMod.restartPagePipeline(P); pageMod.restartPagePipeline(P); }); const stopStore = storeMod.useDesignStore(P, null).subscribe("stations", (stations) => { if (stations?.length) void sectionStore.swapSectionStations(P, R, stations); }); pageMod.pipelineEarthwork(P, { conversion: job.conversion }); pageMod.restartPagePipeline(P); await quiet(); const open = { runs: sliceRuns(0), stations: detail.cross_sections.map((s) => s.chainage_m), final: finalOf(detail), cross: crossOf(detail), same: detail === opened, }; // 노선 꼭짓점 한 번 끌기 — 상세가 새 노선 측점으로 갈아끼워짐 · 그 횡단을 다시 셈 let mark = runs().length; const bridge = pageMod.routeDraftBridge(P, link); bridge.edited(draftOf(shift(1, 6, -4))); await quiet(); const cached = await sectionStore.loadSectionDetail(P, R); recompute(cached); const drag = { runs: sliceRuns(mark), swapped: cached !== opened && detail === cached, stations: cached.cross_sections.map((s) => s.chainage_m), final: finalOf(cached), }; // 되돌리기 한 번(초안 버림) mark = runs().length; const swapMark = swaps.length; bridge.edited(null); await quiet(); const back = await sectionStore.loadSectionDetail(P, R); const undo = { runs: sliceRuns(mark), restores, swaps: swaps.length - swapMark, sameObject: back === opened && detail === opened, stations: back.cross_sections.map((s) => s.chainage_m), final: finalOf(back), cross: crossOf(back), }; // 되돌린 뒤 조용함 — 더 안 돎 mark = runs().length; await quiet(); const after = { runs: runs().length - mark, blocked: pageMod.pagePipeline(P).blockedWrites }; stopListen(); stopStore(); pageMod.disposePagePipeline(P); return { open, drag, undo, after }; } run() .then((out) => { process.stdout.write(JSON.stringify(out)); process.exit(0); }) .catch((error) => { process.stderr.write(String(error && error.stack ? error.stack : error)); process.exit(1); });