[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -1,102 +1,180 @@
---
id: wiki-2026-0508-nodejs-global-namespace-augmenta
title: Nodejs Global Namespace Augmentation
title: Node.js Global Namespace Augmentation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-NodejsG-001]
aliases: [Node.js Global Augmentation, globalThis Augmentation, Node Global Types]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, nodejs, typescript, software-engineering]
confidence_score: 0.9
verification_status: applied
tags: [nodejs, typescript, declaration-merging, global, types]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript
framework: Node.js
---
# [[Nodejs-Global-Namespace-Augmentation|Nodejs-Global-Namespace-Augmentation]]
# Node.js Global Namespace Augmentation
## 📌 한 줄 통찰 (The Karpathy Summary)
> "전역 공간의 안전한 확장: TypeScript 환경에서 Node.js의 `Global` 인터페이스를 확장하여, 타입 안정성을 유지하면서도 커스텀 전역 변수를 사용하는 기술적 '타협점'."
## 한 줄
> **"매 globalThis 의 typed extension"**. Node.js 환경에서 매 global / globalThis 에 property 추가 시 (e.g. dev-mode singleton, env-typed config, monkey-patch), TS declaration merging 으로 매 type-safe access. 매 `declare global { ... }` + module file (top-level import/export) 매 정답.
## 📖 구조화된 지식 (Synthesized Content)
Node.js 전역 네임스페이스 확장(Global Namespace Augmentation)은 주로 테스트 환경이나 특정 프레임워크 설정 시 전역적으로 접근 가능한 속성을 정의하기 위해 사용됩니다.
## 매 핵심
1. **구현 기법 (Declaration Merging)**:
```typescript
declare global {
namespace NodeJS {
interface Global {
myCustomUtility: MyUtilityType;
}
}
}
```
* `declare global` 블록을 사용하여 외부 모듈 내에서도 전역 스코프에 타입을 병합함.
2. **사용 사례**:
* **테스트 환경**: `jest`나 `mocha`에서 전역적으로 사용되는 매칭 도구(Match Styles) 확장.
* **환경 변수 타입**: `process.env` 속성에 대한 자동 완성 및 타입 체크 지원( `ProcessEnv` 인터페이스 확장).
3. **주의사항**:
* 남용 시 이름 충돌(Name Collision) 및 의존성 추적의 어려움 발생. 최대한 모듈형(Module-based) 접근을 우선해야 함.
### 매 왜 필요
- Dev hot-reload 의 Prisma/Mongoose client singleton 매 module-level 으로는 reload 마다 reconnect.
- `process.env` 의 strict typing.
- Vitest/Jest setup 의 global helper.
- Polyfill / shim 매 global 추가.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 `global.d.ts` 파일을 만드는 것만으로 충분했으나, 최신 TypeScript 버전과 ES Modules 시스템 하에서는 `export {}` 등을 추가하여 파일이 모듈로 인식되게 해야 전역 확장이 정확히 작동하는 경우가 많음.
- **정책 변화(RL Update)**: 클린 코드 프린시플([[_뇌와 팔다리의 분리_ - 관심사의 분리 (Separation of Concerns)|Separation of Concerns]])에 따라 전역 변수 사용은 점진적으로 지양되는 추세이나, 엔터프라이즈 급 대규모 모노레포에서는 공통 유틸리티의 타입 접근성을 위해 엄격한 거버넌스 하에 선택적으로 허용하는 정책을 취함.
### 매 globalThis vs global vs window
- **globalThis**: 매 모든 환경 (Node, browser, worker) — 매 prefer.
- **global**: Node.js 만 — 매 deprecated trend.
- **window**: 매 browser only.
## 🔗 지식 연결 (Graph)
- **Related**: [[TypeScript_Type_Safety|TypeScript_Type_Safety]], [[Monorepo|Monorepo]]-[[Management|Management]], [[Separation_of_Concerns|Separation_of_Concerns]], Modular Monolith
- **Modern Tech/Tools**: TypeScript Declaration Merging, tsconfig paths.
---
### 매 응용
1. Prisma / DB client dev-singleton.
2. Typed `process.env` (NODE_ENV, DATABASE_URL).
3. Test setup global mocks.
4. Monkey-patched `fetch` / `Buffer`.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### globalThis singleton (매 Prisma dev)
```ts
// db.ts
import { PrismaClient } from "@prisma/client";
**언제 쓰면 안 되는가:**
- *(TODO)*
declare global {
// eslint-disable-next-line no-var
var __prisma: PrismaClient | undefined;
}
## 🧪 검증 상태 (Validation)
export const prisma = globalThis.__prisma ?? new PrismaClient();
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
if (process.env.NODE_ENV !== "production") {
globalThis.__prisma = prisma;
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Typed process.env
```ts
// env.d.ts
declare namespace NodeJS {
interface ProcessEnv {
readonly NODE_ENV: "development" | "production" | "test";
readonly DATABASE_URL: string;
readonly OPENAI_API_KEY: string;
readonly LOG_LEVEL?: "debug" | "info" | "warn" | "error";
}
}
export {};
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Augment global with custom helper
```ts
// global.d.ts
declare global {
function inject<T>(token: string): T;
var __APP_VERSION__: string;
}
export {};
**선택 B를 써야 할 때:**
- *(TODO)*
// runtime.ts
globalThis.inject = function <T>(token: string): T { /* ... */ return null as any; };
globalThis.__APP_VERSION__ = "1.4.2";
```
**기본값:**
> *(TODO)*
### Test setup augmentation (Vitest)
```ts
// vitest.setup.ts
import { vi } from "vitest";
## ❌ 안티패턴 (Anti-Patterns)
declare global {
var fetchMock: ReturnType<typeof vi.fn>;
}
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
globalThis.fetchMock = vi.fn();
globalThis.fetch = globalThis.fetchMock as any;
```
### Monkey-patch with type
```ts
// fetch-with-retry.ts
declare global {
interface GlobalThis {
originalFetch?: typeof fetch;
}
}
if (!globalThis.originalFetch) {
globalThis.originalFetch = globalThis.fetch;
globalThis.fetch = async (input, init) => {
for (let i = 0; i < 3; i++) {
try {
return await globalThis.originalFetch!(input, init);
} catch (e) {
if (i === 2) throw e;
await new Promise(r => setTimeout(r, 100 * 2 ** i));
}
}
throw new Error("unreachable");
};
}
```
### Validated env (Zod)
```ts
import { z } from "zod";
const envSchema = z.object({
NODE_ENV: z.enum(["development", "production", "test"]),
DATABASE_URL: z.string().url(),
PORT: z.coerce.number().default(3000),
});
export const env = envSchema.parse(process.env);
// env.PORT: number, env.DATABASE_URL: string
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Dev singleton | globalThis cache + declare global |
| Env typing | namespace NodeJS.ProcessEnv (or Zod) |
| Test mocks | declare global in setup |
| Runtime validation | Zod / Valibot — 매 declare 만 매 trust X |
| Module-scoped state | normal module export, not global |
**기본값**: 매 globalThis + `declare global { var ... }` (top-level export 로 module 화).
## 🔗 Graph
- 부모: [[TypeScript-Declaration-Merging]] · [[Node.js-Globals]]
- 변형: [[ProcessEnv-Typing]] · [[Module-Augmentation]]
- 응용: [[Prisma-Singleton]] · [[Test-Setup]] · [[Env-Validation]]
- Adjacent: [[ESM-vs-CJS]] · [[tsconfig-types]]
## 🤖 LLM 활용
**언제**: dev singleton, typed env, test global mock, runtime polyfill.
**언제 X**: app state 의 global stash — 매 anti-pattern. Module export 로 한정.
## ❌ 안티패턴
- **No `export {}`**: 매 d.ts 가 module 인식 X — 매 global pollute or merge 실패.
- **`global.x = ...` without declare**: 매 TS error or any.
- **Production singleton on global**: 매 cluster mode worker 별 다른 instance.
- **Trust env type only**: 매 runtime validation 없이 매 typo 매 silent undefined.
- **Mutate built-ins**: 매 `Array.prototype` 매 augment — library 호환성 폭망.
## 🧪 검증 / 중복
- Verified (TypeScript Handbook — Declaration Merging, Node.js docs globalThis, Prisma docs Best Practices).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Prisma singleton, ProcessEnv, Zod env, monkey-patch 패턴 |