Repository navigation
Description
Analysis of packages/core (parser, style resolution, SVG renderer, translate — pure TS) for refactoring opportunities. All refactorings must be zero-behavior-change (output SVGs byte-identical); existing tests must keep passing. Constraints: barrel imports of **/index.js are forbidden inside packages/core/src; pnpm check:cycles forbids circular deps including type-only imports.
Context worth noting: pnpm knip currently reports zero unused exports in core, so there is no dead-code cleanup to be had — the wins are in duplication and decomposition. Package exports only expose "." and "./icons/*", so all internal file moves below are invisible to consumers.
Refactoring opportunities in packages/core
1. Deduplicate the three compile*Diff pipelines in index.ts
- Files:
src/index.ts(compileSystemDiffL1266–1375,compileDeployDiffL1408–1487,compileOrgDiffL1520–1573,buildAllViewsSvgDiffProjectL1608+) - Problem: All three diff compilers repeat the same boilerplate verbatim: create
ImportResolver,Promise.all-resolve before/after entries, concat diagnostics, assemble[builtin, ...before.styleSheets, ...after.styleSheets], append icon-theme sheet (displayMode === "icon" ? [...sheets, getIconThemeStyleSheet()] : sheetsappears 4x in this file plus once inrenderer/all-layers-svg.ts:101), convertdiffed.nodes/diffed.edgesintoMap<string,string>state maps, andinjectDiffStylethe SVG. Any change to sheet ordering or diagnostics merging must be applied in 3–4 places. - Suggested approach: Extract three tiny helpers:
resolveBeforeAfter(fs, beforePath, afterPath),assembleDiffSheets(before, after, theme, badgeLabels, displayMode), andtoDiffStateMaps(diffed). Pure mechanical inlining in reverse; output SVGs byte-identical. - Risk: low
- Effort: S
2. Move the compile facade out of the index.ts barrel
- Files:
src/index.ts(1716 lines; implementation spans ~L258–1716:_compileFromPreparedInputL506–710,_compileCoreL712+,compile/compileProjectoverloads L776–851,buildNodeMetadataL885,buildDeployNodeMetadataL952, allcompile*Diff,buildAllViewsSvgDiffProject,diagnosticToWarning) - Problem: The barrel mixes ~1,100 lines of real compile-pipeline logic with re-exports, making it both the highest-traffic API file and a large implementation file. Because barrel imports are forbidden inside
packages/core/src, no other core module can reuse anything defined here (e.g.diagnosticToWarning). - Suggested approach: Move the implementation (interfaces + functions, unmodified) into e.g.
src/compile/compile.tsandsrc/compile/compile-diff.tsusing deep imports, and replace withexport { ... } from "./compile/compile.js"lines inindex.ts. This is not a wholesale barrel restructure — the export surface stays identical, only ~1,100 implementation lines relocate. Verified safe: nothing in core importsindex.jsinternally,package.jsonexportsonly exposes"."and"./icons/*", and knip currently reports zero unused exports. Gate withpnpm typecheck, core tests,pnpm check:cycles,pnpm knip. - Risk: medium (large mechanical move; mitigated by full-repo typecheck + tests)
- Effort: M
3. Consolidate CJK text-width estimation and font-ratio constants
- Files:
src/renderer/layout.ts:2455,src/renderer/deploy-layout.ts:23,src/render/matrix-svg.ts:41,src/renderer/svg-builder.ts:57–100,src/renderer/rendering-constants.ts - Problem: The "CJK char = 1.5x width, threshold
charCodeAt(0) > 0x2e80" heuristic exists as three separateestimateTextWidthfunctions (layout.ts and deploy-layout.ts are line-for-line identical apart from thecharWidthparameter) plus three inline copies insidetruncateToWidth/wrapToWidthin svg-builder.ts. matrix-svg.ts has a deliberately different, wider-coverage heuristic (isWideCharwith full CJK ranges) — the divergence is invisible today. There is also a live drift bug-in-waiting:layout.ts:41definesDESCRIPTION_FONT_RATIO = 0.85for width estimation, butsvg-renderer.ts:1077usesCHAR_WIDTH * 0.8; // DESCRIPTION_FONT_RATIO— the comment claims a constant it doesn't use, so layout width and rendered font size are computed with different ratios. - Suggested approach: Add
charDisplayWidth(ch, charWidth)(orestimateTextWidth(text, charWidth)) torendering-constants.tsorsvg-builder.tsand use it from layout.ts, deploy-layout.ts, and the three svg-builder loops — values unchanged, zero behavior change. Keep matrix-svg's heuristic separate but add a comment cross-referencing the intentional difference. Name the0.8in svg-renderer.ts as its own constant (do not unify it to 0.85 — that would change output) and fix the misleading comment. - Risk: low
- Effort: S
4. layoutMultipleSystems: 10 positional optional parameters, mirrored machinery with layout()
- Files:
src/renderer/layout.ts(layoutL946–1520, 574 lines;layoutMultipleSystemsL1587–1986, 399 lines; call site L982) - Problem:
layoutMultipleSystems(viewSlice, ownerIndex?, boundaryIndex?, displayMode?, layoutHints?, edgeDirections?, collapsedCategories?, groupBy?, collapsedGroups?, edgeDiffState?)takes 10 mostly-optional positional params that just re-splat theLayoutOptionsobjectlayout()already received — adding an option means threading an 11th positional arg. Beyond that, both functions duplicate the group-collapse/grouped-layer sequence; comments in the multi-system path literally say "mirrors layout()" but it's copy-adapted, not shared. - Suggested approach: Step 1 (trivially safe): change the signature to
layoutMultipleSystems(viewSlice, options: LayoutOptions). Step 2 (optional, separate commit): extract the shared per-node-set group-collapse block into a helper.layout.test.ts(1786 lines) +group-*-render.test.tsfence this well. - Risk: low (step 1) / medium (step 2)
- Effort: M
5. Decompose renderNode (534 lines) in svg-renderer
- Files:
src/renderer/svg-renderer.ts(renderNodeL904–1438; alsorenderFromLayoutL218–492) - Problem:
renderNodeis a single 534-line function interleaving independent concerns: icon-mode card frame, shape, labelSlot-positioned text vs. default text stack, multi-line description wrapping, badges, link/team meta row, and the info button. Each new node feature has grown it further; reviewing a change means paging through all concerns. - Suggested approach: Extract per-concern private helpers (
renderIconFrame,renderSlottedText,renderDefaultText,renderMetaRow,renderInfoButton) that append to thechildrenarray, keeping attribute order and string output byte-identical. The SVG string equality tests (svg-renderer.test.ts1019 lines,svg-builder-family-parity.test.ts) make this mechanically verifiable. - Risk: medium
- Effort: M
6. Decompose extractView (344 lines)
- Files:
src/view/view-extract.ts(extractViewL685–1029) - Problem: The central view-slicing function handles root vs. drill-down paths, ghost-edge synthesis, unassigned-node merging, and expansion frames in one body. It is the function most feature PRs touch (expand Comprehension: single-container in-frame expansion — mixed-LOD Phase 1 (案3) #1921, boundary Declare semantic clusters within a system; render with boundary frames #1822 both grew it), so merge conflicts and review cost concentrate here.
- Suggested approach: Split into phase helpers (path resolution, child collection, ghost-edge synthesis, expanded-frame construction) with explicit input/output types.
view-extract.test.ts(1755 lines) +view-extract.expand.test.ts+derivation-contracts.test.tsgive strong fencing. - Risk: medium
- Effort: M
7. Type-safety: illegal LayoutNode["kind"] cast in drawio org-layout (untested file)
- Files:
src/exporter/drawio/org-layout.ts:92(kind: "member" as unknown as LayoutNode["kind"]),src/renderer/layout-types.ts:20(kind: LogicalNodeKind | DeployNodeKind) - Problem: This is one of only two
as unknown as/as anycasts in all of core's production code. It smuggles the string"member"into a union that doesn't contain it, so downstreamswitches onkindsilently miss org nodes and the compiler can't warn.org-layout.tsalso has no co-located test file. - Suggested approach: Widen
LayoutNode["kind"]to include the org kinds ("member"/"team") or introduce anOrgLayoutNodeKindunion member inlayout-types.ts, then delete the cast. Type-only change; runtime output identical. Optionally add a small snapshot test fororg-layout.tsin the same PR. - Risk: low
- Effort: S
8. Micro-duplication and placement inconsistencies
- Files:
src/render/matrix-svg.ts(sole file inrender/; every other renderer lives inrenderer/),src/translate/db.ts:5vssrc/translate/openapi.ts:39(byte-identicaltoPascalCase),src/renderer/svg-builder.ts:18vssrc/exporter/drawio/mxgraph-builder.ts:17(twoescapeXmlvariants — the drawio one additionally escapes') - Problem:
render/vsrenderer/forces contributors to remember one exception and makes greps miss files. The duplicatedtoPascalCasemeans an ID-derivation fix in one translator can silently miss the other. The twoescapeXmls are near-duplicates whose semantic difference (apostrophe escaping) is undocumented. - Suggested approach: Move
matrix-svg.tsintorenderer/(only importer isindex.ts:85plus its own test). HoisttoPascalCaseinto a sharedtranslate/identifier.ts(deep import, no barrel). ForescapeXml, don't merge (the'difference is load-bearing for mxgraph attributes) — just add a one-line comment in each explaining why two exist. - Risk: low
- Effort: S
Suggested first batch
A single low-risk PR combining the mechanical items, verified by pnpm --filter @karasu-tools/core test, pnpm typecheck, pnpm check:cycles, pnpm knip:
- Point 1 — dedupe the
compile*Diffpipelines (pure helper extraction insideindex.ts) - Point 3 — consolidate the CJK width heuristic + name the
0.8ratio constant (values untouched) - Point 7 — fix the
LayoutNode["kind"]cast (type-only) - Point 8 —
render/→renderer/move + sharedtoPascalCase
Point 2 (compile facade extraction) is the natural follow-up PR: it builds directly on point 1's helpers but is a big enough diff to deserve its own review. Points 4–6 are independent decomposition PRs, each fenced by an existing large test suite.
Analysis performed by Claude Code agents on 2026-07-16.
Activity
refactor(core): dedupe diff pipelines, CJK width heuristic, and micro…
chore: add changeset for description truncation fix
refactor(core): move compile facade out of index.ts barrel (#2038)
refactor(core): layoutMultipleSystems options object + shared group-c…
refactor(core): apply code-review findings — parametrize icon buttons…
refactor(core): decompose renderNode into per-concern private helpers (…
refactor(core): decompose extractView into phase helpers (#2064)
kompiro commentedon Jul 18, 2026
All refactoring points implemented and merged across batches: compile*Diff dedup, compile facade extraction (#2038), CJK width heuristic, layoutMultipleSystems options (#2057), renderNode decomposition (#2061), extractView decomposition (#2064), LayoutNode kind cast fix, render/→renderer/ + toPascalCase consolidation. All PRs verified byte-identical via the render harness. Closing as done.
feat(core): wrap descriptions, vector meta glyphs, and AA secondary t…