- Home
- Skills
- Code Quality & Review
- Circular Import & TDZ Surgeon
Works with the AI Agents you already use
Circular Import & TDZ Surgeon
by Badung
Trace and cut circular imports, barrel-file cycles and TDZ crashes in TypeScript, JavaScript, Python and Go — 5 deterministic DAG patterns, patch-ready diffs, no lint ignores, plus a CI regression gate.
$3.99
Circular Import & TDZ Surgeon
Example session with this skill installed
Our Node/TS app crashes at startup. Fix it without disabling lint rules and without breaking our public barrel exports.
ReferenceError: Cannot access 'UserService' before initialization
at src/audit/audit.service.ts:4:25
src/users/index.ts
export * from './user.service';
export * from './user.types';
src/users/user.service.ts
import { AuditService } from '../audit/audit.service';
export class UserService { constructor(private audit: AuditService) {} }
src/users/user.types.ts
export enum UserRole { MEMBER = 'member', ADMIN = 'admin' }
src/audit/audit.service.ts
import { UserService, UserRole } from '../users';
export class AuditService {
static defaultRole = UserRole.MEMBER;
constructor(private users: UserService) {}
}
- Read your context and instructions
- Compiled the circular import
Summary
This is a barrel cycle, not a type error. audit.service.ts imports the runtime enum UserRole and the class UserService from the users barrel, while that same barrel is still evaluating user.service.ts — so UserService sits in its temporal dead zone when the static field defaultRole initializes.
1. Cycle inventory
| ID | Exact cycle chain | Severity | Root cause | Pattern |
|---|---|---|---|---|
| CYC-01 | users/index.ts -> users/user.service.ts -> audit/audit.service.ts -> users/index.ts | CRITICAL (TDZ crash) | A top-level value (UserRole.MEMBER in a static field) is read through a barrel that is mid-initialization | C4 barrel bypass + C1 type-only |
2. Edge classification
users/index.ts -> user.service.ts— re-export, executes on loaduser.service.ts -> audit/audit.service.ts— top-level value,AuditServicereferenced in a constructor signatureaudit/audit.service.ts -> users/index.ts— top-level runtime value (UserRole.MEMBER) plus a type-only reference (UserService)
Only the third edge has to change: its runtime import moves to the leaf, its type reference becomes type-only.
3. Surgical patch
--- a/src/audit/audit.service.ts
+++ b/src/audit/audit.service.ts
@@ -1,5 +1,6 @@
-import { UserService, UserRole } from '../users';
+import { UserRole } from '../users/user.types';
+import type { UserService } from '../users/user.service';
export class AuditService {
static defaultRole = UserRole.MEMBER;
Resulting graph, now acyclic:
user.types.ts <- audit.service.ts <- user.service.ts <- users/index.ts
users/index.ts still re-exports both modules, so anything importing UserRole or UserService from ../users or from src/index.ts keeps working unchanged.
Why not the alternatives: eslint-disable leaves the cycle and the next static initializer crashes again, while a lazy await import() would turn a synchronous enum reference into async code for no gain.
4. Verification
# NOT RUN in this session: no repository or node_modules here
npx dpdm --circular --exit-code circular:1 src/index.ts
npx madge --circular --extensions ts,tsx src/
Expected after the patch: ✔ No circular dependency found!
5. Regression gate
// eslint.config.js
'import/no-cycle': ['error', { maxDepth: 4 }],
Next steps
- Apply the two-line diff in
src/audit/audit.service.tsand restart the app — the TDZ error should be gone. - Run both scanners above and send the output back if either still reports a cycle.
- Sweep other internal files for
from '../users'andfrom './index'imports and point them at leaf modules; that is the same cycle waiting to happen.
Connects securely to your tools. The creator never sees your data.
About this skill
Your app dies at startup with ReferenceError: Cannot access 'UserService' before initialization. Or FastAPI refuses to boot with ImportError: cannot import name 'Order' from partially initialized module. The cause is rarely the file you were editing — it is a cycle running through a barrel file, a class inheritance chain, or a type hint that was imported eagerly.
The usual fixes (disable import/no-cycle, add # noqa, cast to any, shuffle code until the error moves) hide the cycle and leave the next one to find you in production.
What this skill does
It treats your imports as a dependency graph and operates on the graph, not on guesses.
- Maps the exact loop from the real
import/require/from ... importlines you paste. You get the literal chain, for exampleusers/index.ts -> users/user.service.ts -> audit/audit.service.ts -> users/index.ts. - Classifies every edge as type-only, top-level value (executed at module load:
extends, decorators, singletons) or deferred (used only inside a function), then rates the cycle CRITICAL / HIGH / MEDIUM by real runtime risk. - Cuts it with one of five deterministic patterns, always picking the smallest DAG cut:
- C1 Type-only decoupling —
import type,TYPE_CHECKING,from __future__ import annotations - C2 Shared leaf extraction — move types, constants and pure helpers into a zero-dependency module both sides import
- C3 Dependency inversion — a narrow interface in the lower layer, implemented at the composition root
- C4 Internal barrel bypass — internal files import the leaf directly;
index.tsstays for external consumers only - C5 Controlled lazy boundary — only a genuinely mutual runtime import moves inside the calling function, with the reason documented in the code
- C1 Type-only decoupling —
- Delivers patch-ready diffs, not advice: per-file
Before -> Afterhunks with the new one-way graph spelled out, and public exports (src/index.ts, packageexports,__init__.py) kept intact. - Hands you the regression gate:
dpdm --circular,madge --circular, ESLintimport/no-cycle, Pythonimport-linter,go build ./..., so the cycle cannot quietly come back.
Guardrails it refuses to break
- No silencing: no
eslint-disable,# noqa,tsconfigpath hacks or blindanycasts just to make the warning disappear. - No public API breakage: the barrel that outside consumers depend on stays; cycles are cut inside the package by stopping internal files from importing through their own barrel.
- No unverified claims: if your build, test runner or cycle scanner cannot run in the session, the verification commands are marked
NOT RUNand handed back to you verbatim. - No over-engineering: a type-only cycle gets
import type, not a dependency-injection rewrite.
Stacks covered
- TypeScript / ESM —
ReferenceError: Cannot access 'X' before initialization(TDZ), class inheritance and top-level singleton cycles - Node CommonJS — imported symbol arrives as
undefinedor{}from a partially builtmodule.exports - Next.js / Vite / Webpack — internal modules importing through
index.tsbarrels, broken tree-shaking, slow HMR,'use client'bundle bleed - Python —
ImportError: cannot import name ... from partially initialized modulein FastAPI, Django and SQLAlchemy model/schema layers - Go —
import cycle not allowed, fixed by extracting a shared contract package
Who it is for
Developers inheriting a legacy codebase that crashes at boot, teams whose bundle quietly grew after a refactor, backend engineers fighting FastAPI or SQLAlchemy cycles, and reviewers who want a real DAG change instead of one more suppression comment.
One skill file, no install and no network: paste the error and the files involved, get the loop, the cut, the diff and the gate.
Verification commands are marked as NOT RUN if the environment lacks the specific toolchain. Requires manual execution of generated CI gate commands for final validation.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before buying a skill.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill goes through the trust checks below.
Security scanned
Checked by our 8-point scan before listing
Fresh listing
Recently published to Agensi
Money-back guarantee
Doesn't do what its page promises? You get your money back.
Trust & safety
Security scan
Security scan passed 12 days ago
- Software
- dpdm
Node.jsmadge
Paste the error and the files in the cycle — no CLI or account needed. The dpdm / madge / import-linter commands in the output are optional checks for your own CI; when they cannot be run, the output marks them NOT RUN.
Permissions
What's inside
Frequently Asked Questions
New in Code Quality & Review
Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for Code Quality & Review.