---
id: wiki-2026-0508-issue-001-combat-reference-error
title: Issue 001 Combat Reference Error Troubleshooting
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Reference Error Debugging, Runtime Reference Error]
duplicate_of: none
source_trust_level: B
confidence_score: 0.85
verification_status: applied
tags: [debugging, reference-error, runtime, troubleshooting, combat-system]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: typescript
  framework: nodejs
---

# Issue 001 Combat Reference Error Troubleshooting

## 매 한 줄
> **"매 ReferenceError 의 root cause 매 hoisting, TDZ, circular import, async timing 의 4 가지로 collapse"**. 매 case study (combat system 의 reference error) 를 통해 매 systematic debug pipeline 정리.

## 매 핵심

### 매 ReferenceError 4 카테고리
- **Undeclared**: variable 매 declare 안됨 (typo, missing import).
- **TDZ**: `let`/`const` 매 init 전 access (temporal dead zone).
- **Circular import**: A imports B, B imports A → 매 partially-loaded module.
- **Async timing**: top-level await, dynamic import 의 race.

### 매 Combat case (post-mortem 요약)
- **Symptom**: `ReferenceError: CombatEngine is not defined` 매 production only.
- **Root cause**: Vite tree-shaking 의 side-effect import 의 elimination.
- **Fix**: `package.json` 의 `"sideEffects": ["./src/combat/registry.ts"]`.

### 매 Debug 절차
1. Reproduce: minimal repo.
2. Stack trace: 매 first frame 의 file:line.
3. Bisect: git bisect or feature flag.
4. Verify: regression test 추가.

## 💻 패턴

### TDZ 의 detection
```ts
// BAD — TDZ
console.log(x); // ReferenceError
let x = 1;

// GOOD — declare 먼저
let x: number;
x = 1;
console.log(x);
```

### Circular import resolve
```ts
// a.ts
import { B } from './b';
export class A { b = new B(); }

// b.ts — circular
// import { A } from './a';  // 매 X
// 매 type-only import 로 break:
import type { A } from './a';
export class B { parent?: A; }
```

### Vite sideEffects 의 protect
```json
// package.json
{
  "sideEffects": [
    "./src/combat/registry.ts",
    "./src/polyfills/*.ts",
    "*.css"
  ]
}
```

### Webpack module federation 의 안전한 dynamic
```ts
const Combat = await import(/* webpackChunkName: "combat" */ './combat')
  .catch(err => {
    console.error('Combat module failed', err);
    return { CombatEngine: class FallbackEngine {} };
  });
```

### Stack trace parser
```ts
function parseRefError(err: Error): { name: string; file?: string; line?: number } {
  const m = err.message.match(/(\w+) is not defined/);
  const frame = err.stack?.split('\n')[1]?.match(/at .* \((.+):(\d+):\d+\)/);
  return {
    name: m?.[1] ?? 'unknown',
    file: frame?.[1],
    line: frame ? Number(frame[2]) : undefined
  };
}
```

### Regression test
```ts
import { describe, it, expect } from 'vitest';
import { CombatEngine } from '@/combat';

describe('combat module loading', () => {
  it('exports CombatEngine after tree-shake', () => {
    expect(CombatEngine).toBeDefined();
    expect(typeof CombatEngine).toBe('function');
  });

  it('registry has registered abilities', async () => {
    const { abilityRegistry } = await import('@/combat/registry');
    expect(abilityRegistry.size).toBeGreaterThan(0);
  });
});
```

### Sentry breadcrumb 의 capture
```ts
import * as Sentry from '@sentry/node';
Sentry.init({
  beforeSend(event, hint) {
    if (hint.originalException instanceof ReferenceError) {
      event.tags = { ...event.tags, error_class: 'reference' };
    }
    return event;
  }
});
```

## 매 결정 기준
| 상황 | Approach |
|---|---|
| TDZ 의 의심 | 매 declaration 위치 의 audit |
| Circular import | type-only import or DI |
| Tree-shake elimination | sideEffects 명시 |
| Async race | top-level await guard |

**기본값**: 매 minimal repro → bisect → regression test 의 add.

## 🔗 Graph
- 부모: [[Debugger_Techniques]] · [[Runtime Errors]]
- 변형: [[TypeError]] · [[SyntaxError]]
- 응용: [[Tree Shaking]] · [[Circular Dependency]]
- Adjacent: [[Source Maps]] · [[Sentry]]

## 🤖 LLM 활용
**언제**: stack trace + module graph paste → root cause hypothesis.
**언제 X**: 매 production memory dump 매 직접 read X — local repro 가 우선.

## ❌ 안티패턴
- **Catch and ignore**: `try { ... } catch {}` — error 매 silently 사라짐.
- **No regression test**: fix 후 test 매 추가 X → 매 regression repeat.
- **Random side-effect import**: `import './magic'` — tree-shake 가 죽임.
- **Production-only debug**: local 매 repro 안하고 prod 에서 console.log.

## 🧪 검증 / 중복
- Verified (MDN ReferenceError, Vite tree-shake docs).
- 신뢰도 B (case-specific 의 detail).

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — ReferenceError 의 4 카테고리 + combat case |
