docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를 Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류. - 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로 자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거, 동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거. - 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming, Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business, Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로, 나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는 title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백). 원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지. - 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서. - 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는 지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지. - Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경. - 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
This commit is contained in:
@@ -0,0 +1,176 @@
|
||||
---
|
||||
id: wiki-2026-0508-nodejs-global-namespace-augmenta
|
||||
title: Node.js Global Namespace Augmentation
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Node.js Global Augmentation, globalThis Augmentation, Node Global Types]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [nodejs, typescript, declaration-merging, global, types]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: TypeScript
|
||||
framework: Node.js
|
||||
---
|
||||
|
||||
# Node.js Global Namespace Augmentation
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 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) 매 정답.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 왜 필요
|
||||
- Dev hot-reload 의 Prisma/Mongoose client singleton 매 module-level 으로는 reload 마다 reconnect.
|
||||
- `process.env` 의 strict typing.
|
||||
- Vitest/Jest setup 의 global helper.
|
||||
- Polyfill / shim 매 global 추가.
|
||||
|
||||
### 매 globalThis vs global vs window
|
||||
- **globalThis**: 매 모든 환경 (Node, browser, worker) — 매 prefer.
|
||||
- **global**: Node.js 만 — 매 deprecated trend.
|
||||
- **window**: 매 browser only.
|
||||
|
||||
### 매 응용
|
||||
1. Prisma / DB client dev-singleton.
|
||||
2. Typed `process.env` (NODE_ENV, DATABASE_URL).
|
||||
3. Test setup global mocks.
|
||||
4. Monkey-patched `fetch` / `Buffer`.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### globalThis singleton (매 Prisma dev)
|
||||
```ts
|
||||
// db.ts
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line no-var
|
||||
var __prisma: PrismaClient | undefined;
|
||||
}
|
||||
|
||||
export const prisma = globalThis.__prisma ?? new PrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
globalThis.__prisma = prisma;
|
||||
}
|
||||
```
|
||||
|
||||
### 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 {};
|
||||
```
|
||||
|
||||
### Augment global with custom helper
|
||||
```ts
|
||||
// global.d.ts
|
||||
declare global {
|
||||
function inject<T>(token: string): T;
|
||||
var __APP_VERSION__: string;
|
||||
}
|
||||
export {};
|
||||
|
||||
// runtime.ts
|
||||
globalThis.inject = function <T>(token: string): T { /* ... */ return null as any; };
|
||||
globalThis.__APP_VERSION__ = "1.4.2";
|
||||
```
|
||||
|
||||
### Test setup augmentation (Vitest)
|
||||
```ts
|
||||
// vitest.setup.ts
|
||||
import { vi } from "vitest";
|
||||
|
||||
declare global {
|
||||
var fetchMock: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
## 🤖 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 패턴 |
|
||||
Reference in New Issue
Block a user