eslint-config-kelo-nextjs 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/base/custom-rules/boundaries-unknown.mjs +58 -0
  2. package/base/custom-rules/index.mjs +7 -0
  3. package/base/custom-rules/no-inline-style-tokens.mjs +2 -2
  4. package/base/custom-rules/no-nested-feature-dir.mjs +1 -1
  5. package/base/eslint-rules/boundaries/boundary-elements.mjs +40 -6
  6. package/base/eslint-rules/boundaries/boundary-ignores.mjs +4 -2
  7. package/base/eslint-rules/boundaries/boundary-rules.mjs +63 -10
  8. package/base/eslint-rules/builders/build-architecture-boundaries.mjs +7 -3
  9. package/base/eslint-rules/builders/to-boundaries-policies.mjs +170 -20
  10. package/base/eslint-rules/docs/layer-semantics.mjs +31 -19
  11. package/base/eslint-rules/docs/structure-annotations.mjs +1 -0
  12. package/base/eslint-rules/quality/base-config.mjs +4 -9
  13. package/base/eslint-rules/quality/custom-rules.mjs +1 -1
  14. package/base/eslint-rules/quality/file-size.mjs +20 -0
  15. package/base/eslint-rules/quality/import-cycle.mjs +18 -0
  16. package/base/eslint-rules/quality/sonarjs.mjs +79 -0
  17. package/base/eslint-rules/settings/domain-banned-packages.mjs +3 -1
  18. package/base/eslint-rules/settings/import-resolver-settings.mjs +1 -1
  19. package/base/eslint-rules/settings/restricted-syntax.mjs +2 -2
  20. package/base/eslint.rules.mjs +3 -1
  21. package/base/stylelint.rules.mjs +3 -3
  22. package/bin/kelo-lint.mjs +0 -5
  23. package/index.mjs +15 -111
  24. package/lib/factory-helpers.mjs +3 -24
  25. package/lib/run-lint-cli.mjs +7 -6
  26. package/package.json +15 -19
  27. package/base/eslint.formatter.mjs +0 -50
  28. package/design-system/antd/eslint.rules.mjs +0 -20
  29. package/design-system/mantine/eslint.rules.mjs +0 -19
  30. package/design-system/shadcn/eslint.rules.mjs +0 -71
  31. package/next-proxy/eslint.rules.mjs +0 -8
  32. package/nextauth/eslint.rules.mjs +0 -58
  33. package/tanstack-query/eslint.rules.mjs +0 -9
@@ -0,0 +1,58 @@
1
+ // =============================================================================
2
+ // boundaries/no-unknown-files · no-unknown-dependencies 래퍼
3
+ // -----------------------------------------------------------------------------
4
+ // 플러그인 규칙은 메시지 옵션이 없어(`context.report({ message })` 고정 문구)
5
+ // 에디터에 원문만 보인다. 플러그인 규칙의 `create`를 그대로 호출하되 `report`만
6
+ // 가로챈 context를 넘겨 메시지를 ARCHITECTURE.md 안내로 바꾼다. 나머지 context
7
+ // (settings·filename·options·sourceCode)는 원본을 프로토타입으로 물려받는다.
8
+ //
9
+ // rules/nestjs/base/custom-rules/boundaries-unknown.mjs 와
10
+ // rules/nextjs/base/custom-rules/boundaries-unknown.mjs 는 동일 내용을 유지한다.
11
+ // =============================================================================
12
+
13
+ import path from "node:path";
14
+
15
+ import boundaries from "eslint-plugin-boundaries";
16
+
17
+ const HOW_TO_REGISTER =
18
+ "프로젝트 고유 레이어나 소스가 아닌 보조 파일이면, 사용자 확인 후 kelo.lint.json의 boundaryElements / boundaryIgnores에 추가";
19
+
20
+ /** 메시지의 상대 경로 기준 — boundaries root-path(소비 프로젝트 루트), 없으면 ESLint cwd. */
21
+ function relativePath(context) {
22
+ const root = context.settings?.["boundaries/root-path"] ?? context.cwd;
23
+ return path.relative(root, context.filename).split(path.sep).join("/");
24
+ }
25
+
26
+ function wrap(ruleName, describe) {
27
+ const original = boundaries.rules[ruleName];
28
+ return {
29
+ meta: {
30
+ ...original.meta,
31
+ docs: {
32
+ ...original.meta?.docs,
33
+ description: `${original.meta?.docs?.description ?? ruleName} (kelo 안내 메시지)`,
34
+ },
35
+ },
36
+ create(context) {
37
+ const report = (descriptor) =>
38
+ context.report({ node: descriptor.node, message: describe(context) });
39
+ // ESLint rule context는 freeze돼 있어 Proxy로 report를 바꿀 수 없다 —
40
+ // 원본을 프로토타입으로 둔 새 객체에 report만 덮어쓴다.
41
+ return original.create(
42
+ Object.create(context, { report: { value: report } }),
43
+ );
44
+ },
45
+ };
46
+ }
47
+
48
+ export const noUnknownFiles = wrap(
49
+ "no-unknown-files",
50
+ (context) =>
51
+ `[구조 위반] ${relativePath(context)}는 어떤 레이어 폴더에도 속하지 않습니다. docs/ARCHITECTURE.md 트리의 위치로 옮기세요. (${HOW_TO_REGISTER})`,
52
+ );
53
+
54
+ export const noUnknownDependencies = wrap(
55
+ "no-unknown-dependencies",
56
+ () =>
57
+ `[구조 위반] import 대상 파일이 어떤 레이어 폴더에도 속하지 않습니다. 대상 파일을 docs/ARCHITECTURE.md 트리의 위치로 옮기세요. (${HOW_TO_REGISTER})`,
58
+ );
@@ -2,6 +2,10 @@
2
2
  // Kelo NextJS — Custom ESLint Plugin
3
3
  // -----------------------------------------------------------------------------
4
4
 
5
+ import {
6
+ noUnknownDependencies,
7
+ noUnknownFiles,
8
+ } from "./boundaries-unknown.mjs";
5
9
  import noInlineStyleTokens from "./no-inline-style-tokens.mjs";
6
10
  import noNestedFeatureDir from "./no-nested-feature-dir.mjs";
7
11
  import noUnknownSrcDir from "./no-unknown-src-dir.mjs";
@@ -13,6 +17,9 @@ import noUnknownSrcDir from "./no-unknown-src-dir.mjs";
13
17
  /** @type {import('eslint').ESLint.Plugin} */
14
18
  export default {
15
19
  rules: {
20
+ // boundaries/no-unknown-* 래퍼 (안내 메시지) — build-architecture-boundaries가 켠다
21
+ "no-unknown-files": noUnknownFiles,
22
+ "no-unknown-dependencies": noUnknownDependencies,
16
23
  "no-inline-style-tokens": noInlineStyleTokens,
17
24
  "no-nested-feature-dir": noNestedFeatureDir,
18
25
  "no-unknown-src-dir": noUnknownSrcDir,
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // 허용:
14
14
  // - MemberExpression: `theme.radius.sm`, `theme.colors.primary[6]`, `token.colorPrimary`
15
- // - `var(...)` 문자열: `'var(--mantine-shadow-sm)'` — negative lookahead로 통과
15
+ // - `var(...)` 문자열: `'var(--shadow-sm)'` — negative lookahead로 통과
16
16
  // - TemplateLiteral: `\`${x}px\`` — 동적 값 escape
17
17
  // - Identifier: `radiusVar` — 변수 참조
18
18
  //
@@ -41,7 +41,7 @@ export default {
41
41
  },
42
42
  messages: {
43
43
  identifierKey:
44
- "Do not hardcode inline style tokens in JSX style prop. Use theme references (e.g., theme.radius.*, theme.colors.*, theme.shadows.*, var(--mantine-*)) instead of raw literals.",
44
+ "Do not hardcode inline style tokens in JSX style prop. Use theme references (e.g., theme.radius.*, theme.colors.*, theme.shadows.*, var(--*)) instead of raw literals.",
45
45
  stringLiteralKey:
46
46
  "Do not hardcode inline style tokens in JSX style prop (string-literal key). Use theme references.",
47
47
  },
@@ -26,7 +26,7 @@
26
26
  // src/http/_generated/ — generator 산출물 (client.ts·index.ts·types·endpoints·services 전부; 구조 고정, layer root 허용 항목)
27
27
  //
28
28
  // 보완 룰:
29
- // - boundaries/no-unknown-files: 어떤 element pattern에도 매치되지 않는 파일 차단
29
+ // - local/no-unknown-files: 어떤 element pattern에도 매치되지 않는 파일 차단
30
30
  // =============================================================================
31
31
 
32
32
  import fs from "node:fs";
@@ -5,13 +5,30 @@
5
5
  */
6
6
  export const baseBoundaryElements = [
7
7
  // Domain layer — 프레임워크 비의존 순수 TS. feature-first (`src/domain/<feature>/...`)
8
- { type: "domain-model", mode: "full", pattern: ["src/domain/*/model.ts"] }, // Entity·VO
9
- { type: "domain-error", mode: "full", pattern: ["src/domain/*/errors.ts"] }, // 도메인 에러
10
- { type: "domain-port", mode: "full", pattern: ["src/domain/*/port.ts"] }, // Repository 인터페이스
8
+ // `capture: ["module"]` — `<feature>` 이름이 모듈 키. domain과 http의 같은 feature 이름은 같은 모듈이다.
9
+ {
10
+ type: "domain-model",
11
+ mode: "full",
12
+ pattern: ["src/domain/*/model.ts"],
13
+ capture: ["module"],
14
+ }, // Entity·VO
15
+ {
16
+ type: "domain-error",
17
+ mode: "full",
18
+ pattern: ["src/domain/*/errors.ts"],
19
+ capture: ["module"],
20
+ }, // 도메인 에러
21
+ {
22
+ type: "domain-port",
23
+ mode: "full",
24
+ pattern: ["src/domain/*/port.ts"],
25
+ capture: ["module"],
26
+ }, // Repository 인터페이스
11
27
  {
12
28
  type: "domain-service",
13
29
  mode: "full",
14
30
  pattern: ["src/domain/*/service.ts"],
31
+ capture: ["module"],
15
32
  }, // UseCase/서비스
16
33
  // HTTP adapter layer — feature-first, transport 명시. `src/http/<feature>/...`
17
34
  {
@@ -30,13 +47,30 @@ export const baseBoundaryElements = [
30
47
  mode: "full",
31
48
  pattern: ["src/http/_generated/services/*.ts"],
32
49
  }, // (generated) tag별 API 서비스 클래스
33
- { type: "http-mapper", mode: "full", pattern: ["src/http/*/mapper.ts"] }, // DTO ↔ Domain 변환
50
+ {
51
+ type: "http-mapper",
52
+ mode: "full",
53
+ pattern: ["src/http/*/mapper.ts"],
54
+ capture: ["module"],
55
+ }, // DTO ↔ Domain 변환
34
56
  {
35
57
  type: "http-repository",
36
58
  mode: "full",
37
59
  pattern: ["src/http/*/repository.ts"],
60
+ capture: ["module"],
38
61
  }, // Port 구현체
39
- { type: "http-hook", mode: "full", pattern: ["src/http/*/hook.ts"] }, // TanStack Query 훅
62
+ {
63
+ type: "http-factory",
64
+ mode: "full",
65
+ pattern: ["src/http/*/factory.ts"],
66
+ capture: ["module"],
67
+ }, // Port 구현체를 끼워 service를 만드는 조립 지점
68
+ {
69
+ type: "http-hook",
70
+ mode: "full",
71
+ pattern: ["src/http/*/hook.ts"],
72
+ capture: ["module"],
73
+ }, // TanStack Query 훅
40
74
  // Shared lib — layered code(domain/http)는 더 이상 lib 아래 두지 않고, lib는 공용 리소스 전담.
41
75
  // barrel은 lib-shared보다 먼저 정의 — 더 구체적인 pattern이 우선 매칭되어야 한다.
42
76
  {
@@ -66,7 +100,7 @@ export const baseBoundaryElements = [
66
100
  { type: "shared-hook", pattern: ["src/hooks"] }, // 전역 재사용 React hook
67
101
  // Style layer — 전역 CSS·디자인 토큰 (CSS custom property + TS 토큰)
68
102
  { type: "style", pattern: ["src/styles"] }, // 전역 스타일·토큰 리소스
69
- // Theme layer — 디자인 시스템 테마 설정 (Mantine `createTheme()`, Ant Design `ConfigProvider.theme`, shadcn 토큰 등)
103
+ // Theme layer — UI 라이브러리·ThemeProvider에 주입할 테마 설정
70
104
  // 수기 작성한 `theme.ts` + generator 산출물 `theme.generated.ts` 두 파일을 함께 인정.
71
105
  {
72
106
  type: "theme",
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Boundary 검사 제외 (boundaries/no-unknown-files 오탐 방지).
3
- * 테스트/스펙/설정, 루트 메타 파일, scripts/e2e 빌드 유틸, 전역 타입,
2
+ * Boundary 검사 제외 (local/no-unknown-files 오탐 방지).
3
+ * 테스트/스펙/설정, 루트 메타 파일, 프레임워크 진입점(`src/proxy.ts`), scripts/e2e 빌드 유틸, 전역 타입,
4
4
  * 모노레포 sibling workspace로 resolve된 import 등.
5
5
  */
6
6
  export const baseBoundaryIgnores = [
@@ -11,6 +11,8 @@ export const baseBoundaryIgnores = [
11
11
  "*.config.*",
12
12
  "*.ts",
13
13
  "*.d.ts",
14
+ // Next.js `src/proxy.ts`(구 middleware) — 프레임워크 진입점이라 레이어에 속하지 않음
15
+ "src/proxy.ts",
14
16
  "types/**",
15
17
  "src/lib/types/**",
16
18
  ".kelo/**",
@@ -1,12 +1,24 @@
1
1
  /**
2
2
  * 레이어 간 import 관계 (allow-list). 기본 disallow 정책 위에 아래 조합만 허용.
3
- * 각 레이어의 역할·책임은 "레이어 글로서리" 섹션 참조.
3
+ * `scope: "module"`의 domain·http 대상은 같은 feature만, 다른 feature로는 `scope: "cross-module"`의 공개 계약(domain-model·domain-port)만 허용한다 — feature 간 결합 차단.
4
4
  */
5
5
  export const baseBoundaryRules = [
6
6
  // Domain: 자기 자신 및 하위 순수 레이어만 참조
7
- { from: { type: "domain-model" }, allow: [{ to: { type: "domain-model" } }] }, // 모델 간 참조만
8
- { from: { type: "domain-error" }, allow: [{ to: { type: "domain-error" } }] }, // 에러 간 참조만
9
- { from: { type: "domain-port" }, allow: [{ to: { type: "domain-model" } }] }, // Port 시그니처는 모델을 사용
7
+ {
8
+ from: { type: "domain-model" },
9
+ allow: [{ to: { type: "domain-model" } }],
10
+ scope: "module",
11
+ }, // 모델 간 참조만
12
+ {
13
+ from: { type: "domain-error" },
14
+ allow: [{ to: { type: "domain-error" } }],
15
+ scope: "module",
16
+ }, // 에러 간 참조만
17
+ {
18
+ from: { type: "domain-port" },
19
+ allow: [{ to: { type: "domain-model" } }],
20
+ scope: "module",
21
+ }, // Port 시그니처는 모델을 사용
10
22
  {
11
23
  from: { type: "domain-service" },
12
24
  allow: [
@@ -15,6 +27,7 @@ export const baseBoundaryRules = [
15
27
  { to: { type: "domain-error" } },
16
28
  { to: { type: "domain-service" } },
17
29
  ],
30
+ scope: "module",
18
31
  },
19
32
  // HTTP 원시 계층: 외부에서만 주입받아 쓰므로 import 0개 (순수 데이터/통신 경계)
20
33
  { from: { type: "http-client" }, allow: [] },
@@ -29,6 +42,7 @@ export const baseBoundaryRules = [
29
42
  // Mapper: DTO → Domain 변환 전용. 두 타입 모두 참조 필요
30
43
  from: { type: "http-mapper" },
31
44
  allow: [{ to: { type: "domain-model" } }, { to: { type: "http-dto" } }],
45
+ scope: "module",
32
46
  },
33
47
  {
34
48
  // Repository: Port 구현체. 모든 원시 통신 요소 + domain 사용.
@@ -46,15 +60,50 @@ export const baseBoundaryRules = [
46
60
  { to: { type: "domain-model" } },
47
61
  { to: { type: "db" } },
48
62
  ],
63
+ scope: "module",
49
64
  },
50
- // Hook: UI에 제공되는 데이터 페칭 훅 + Service 팩토리. 데이터 호출은 domain-service만, http-repository는 Service 팩토리에서 Port 구현체 주입 용도로만, domain-model은 useMutation/useQuery 타입 시그니처용으로 허용.
65
+ // Factory: Port 구현체(repository)를 끼워 service를 만드는 유일한 조립 지점 — hook·route-handler·page가 공유.
51
66
  {
52
- from: { type: "http-hook" },
67
+ from: { type: "http-factory" },
53
68
  allow: [
54
69
  { to: { type: "domain-service" } },
55
- { to: { type: "http-repository" } }, // Service 팩토리에서 Port 구현체 주입용 (데이터 호출 금지)
70
+ { to: { type: "domain-port" } },
71
+ { to: { type: "http-repository" } },
72
+ { to: { type: "http-client" } },
73
+ { to: { type: "db" } },
74
+ ],
75
+ scope: "module",
76
+ },
77
+ // Hook: UI에 제공되는 데이터 페칭 훅. service는 factory로 받고, repository 직접 import는 금지 (조립은 factory 담당).
78
+ {
79
+ from: { type: "http-hook" },
80
+ allow: [
81
+ { to: { type: "http-factory" } },
82
+ { to: { type: "domain-service" } }, // service 타입 참조용
56
83
  { to: { type: "domain-model" } }, // useMutation/useQuery 타입 시그니처용
57
84
  ],
85
+ scope: "module",
86
+ },
87
+ // 다른 feature로는 공개 계약만 — domain-model은 어디서나, domain-port는 service에서
88
+ {
89
+ from: {
90
+ type: [
91
+ "domain-model",
92
+ "domain-port",
93
+ "domain-service",
94
+ "http-mapper",
95
+ "http-repository",
96
+ "http-factory",
97
+ "http-hook",
98
+ ],
99
+ },
100
+ allow: [{ to: { type: "domain-model" } }],
101
+ scope: "cross-module",
102
+ },
103
+ {
104
+ from: { type: "domain-service" },
105
+ allow: [{ to: { type: "domain-port" } }],
106
+ scope: "cross-module",
58
107
  },
59
108
  // lib-shared: src/lib 루트 공용 유틸. 내부 의존 0개 (순수 유틸만)
60
109
  { from: { type: "lib-shared" }, allow: [] },
@@ -130,7 +179,7 @@ export const baseBoundaryRules = [
130
179
  { from: { type: "style" }, allow: [{ to: { type: "style" } }] },
131
180
  // theme: 디자인 시스템 테마 설정. TS 디자인 토큰(style) + 동일 레이어(theme) 참조만 — 도메인/HTTP/UI 레이어 import 금지.
132
181
  // self-allow: `theme.ts`가 generator 산출물 `theme.generated.ts`를 import하는 경우(둘 다 `type: "theme"`)를 위해 필요.
133
- // 외부 디자인 시스템 패키지(mantine/antd/shadcn 등)는 element 규칙 대상 아님.
182
+ // 외부 UI 라이브러리 패키지는 element 규칙 대상 아님.
134
183
  {
135
184
  from: { type: "theme" },
136
185
  allow: [{ to: { type: "style" } }, { to: { type: "theme" } }],
@@ -157,11 +206,12 @@ export const baseBoundaryRules = [
157
206
  allow: [{ to: { type: "dictionary" } }, { to: { type: "shared-type" } }],
158
207
  },
159
208
  {
160
- // Route Handler (HTTP 진입점): 얇은 어댑터 — 도메인 서비스 호출에 집중.
209
+ // Route Handler (HTTP 진입점): 얇은 어댑터 — factory로 service를 조립해 호출.
161
210
  // UI 레이어(shared-ui/page-component) import 금지 (서버 코드 경계 위반).
162
211
  // 프록시·핸들러에서 로케일 검증/협상을 위해 i18n-config 허용.
163
212
  from: { type: "route-handler" },
164
213
  allow: [
214
+ { to: { type: "http-factory" } },
165
215
  { to: { type: "domain-model" } },
166
216
  { to: { type: "domain-error" } },
167
217
  { to: { type: "domain-service" } },
@@ -171,12 +221,15 @@ export const baseBoundaryRules = [
171
221
  },
172
222
  {
173
223
  // Page (최상위 컨슈머): 페이지 조립에 필요한 거의 모든 레이어 사용 가능
174
- // (단, domain-service/repository/http-hook 직접 호출 금지 — 컴포넌트를 거쳐야 함)
224
+ // Server Component 데이터 로드는 http-factory로 (domain-service/repository 직접 import 금지,
225
+ // http-hook은 Client Component 전용이라 금지)
175
226
  // layout/page에서 next-intl routing·navigation 사용을 위해 i18n-config 허용.
176
227
  // layout.tsx의 `import '@/styles/globals.css'` 같은 side-effect import 위해 style 허용.
177
228
  // layout.tsx에서 디자인 시스템 ThemeProvider에 주입하기 위해 theme 허용.
178
229
  from: { type: "page" },
179
230
  allow: [
231
+ { to: { type: "http-factory" } },
232
+ { to: { type: "domain-model" } },
180
233
  { to: { type: "page-component" } },
181
234
  { to: { type: "page-provider" } },
182
235
  { to: { type: "shared-ui" } },
@@ -1,9 +1,11 @@
1
1
  import { defineConfig } from "eslint/config";
2
2
  import boundaries from "eslint-plugin-boundaries";
3
3
 
4
+ import keloLocalPlugin from "../../custom-rules/index.mjs";
4
5
  import { baseBoundaryIgnores } from "../boundaries/boundary-ignores.mjs";
5
6
  import { baseImportResolverSettings } from "../settings/import-resolver-settings.mjs";
6
7
  import {
8
+ guidancePolicies,
7
9
  internalDependencyOptions,
8
10
  splitBoundaryElements,
9
11
  toBoundariesPolicies,
@@ -30,7 +32,7 @@ export function buildArchitectureBoundaries(
30
32
  const internal = internalDependencyOptions(folderElements, classification);
31
33
  return defineConfig([
32
34
  {
33
- plugins: { boundaries },
35
+ plugins: { boundaries, local: keloLocalPlugin },
34
36
  settings: {
35
37
  ...baseImportResolverSettings,
36
38
  "boundaries/elements": folderElements,
@@ -44,14 +46,16 @@ export function buildArchitectureBoundaries(
44
46
  : {}),
45
47
  },
46
48
  rules: {
47
- "boundaries/no-unknown-dependencies": "error",
48
- "boundaries/no-unknown-files": "error",
49
+ // boundaries/no-unknown-* 대신 같은 동작에 안내 메시지를 붙인 래퍼를 쓴다 (에디터에도 표시)
50
+ "local/no-unknown-dependencies": "error",
51
+ "local/no-unknown-files": "error",
49
52
  "boundaries/dependencies": [
50
53
  "error",
51
54
  {
52
55
  default: "disallow",
53
56
  checkInternals: internal.checkInternals,
54
57
  policies: [
58
+ ...guidancePolicies(rules, elements, classification),
55
59
  ...toBoundariesPolicies(rules, classification),
56
60
  ...internal.policies,
57
61
  ],
@@ -14,9 +14,19 @@
14
14
  * 파일에는 기본 카테고리를 붙이고, 폴더 레이어 선택자는 목록상 앞선 파일
15
15
  * 레이어 카테고리를 `noneOf`로 제외한다
16
16
  * (예: `src/app/**\/route.ts`는 `page` 폴더 안이지만 `route-handler`로만 취급).
17
+ * - 모듈 격리: `capture: ["module"]`을 가진 element가 모듈 레이어다. 규칙의
18
+ * `scope: "module"`은 모듈 레이어로 가는 `to`에 `captured.module`을 from의
19
+ * 모듈로 묶고(같은 모듈만), `scope: "cross-module"`은 묶지 않는다(어느 모듈이든).
20
+ * `scope`가 없으면 기존과 같다 (kelo.lint.json 프로젝트 규칙 포함).
17
21
  */
18
22
 
19
23
  const FOLDER_FILE_CATEGORY = "kelo:folder-file";
24
+ const MODULE_CAPTURE = "module";
25
+ const EMPTY_CLASSIFICATION = {
26
+ fileTypes: new Set(),
27
+ excludedCategories: new Map(),
28
+ moduleTypes: new Set(),
29
+ };
20
30
 
21
31
  export function splitBoundaryElements(elements) {
22
32
  const folderElements = [];
@@ -63,23 +73,52 @@ export function splitBoundaryElements(elements) {
63
73
  .filter((c) => c !== FOLDER_FILE_CATEGORY),
64
74
  ),
65
75
  excludedCategories,
76
+ moduleTypes: new Set(
77
+ elements
78
+ .filter((e) => e.capture?.includes(MODULE_CAPTURE))
79
+ .map((e) => e.type),
80
+ ),
66
81
  },
67
82
  };
68
83
  }
69
84
 
70
- function convertSelector(selector, classification) {
85
+ const typesOf = (side) =>
86
+ (Array.isArray(side) ? side : [side])
87
+ .map((s) => (typeof s === "string" ? s : s?.type))
88
+ .flat()
89
+ .filter((t) => typeof t === "string");
90
+
91
+ /** from 파일의 모듈을 가리키는 템플릿 (파일 레이어는 file, 폴더 레이어는 element의 captured). */
92
+ function moduleTemplate(fromType, classification) {
93
+ if (!classification.moduleTypes?.has(fromType)) return null;
94
+ const source = classification.fileTypes.has(fromType) ? "file" : "element";
95
+ return `{{from.${source}.captured.${MODULE_CAPTURE}}}`;
96
+ }
97
+
98
+ /**
99
+ * `sameModule`(from 모듈 템플릿)이 있으면 모듈 레이어 대상에 `captured.module`
100
+ * 조건을 붙인다. 공유 레이어 대상은 그대로.
101
+ */
102
+ function convertSelector(selector, classification, sameModule = null) {
71
103
  const { fileTypes, excludedCategories } = classification;
104
+ const moduleTypes = classification.moduleTypes ?? new Set();
72
105
  const s = typeof selector === "string" ? { type: selector } : selector;
73
106
  if (!s || typeof s !== "object" || "element" in s || "file" in s) {
74
107
  return [s];
75
108
  }
76
109
  const { type, ...rest } = s;
77
110
  const types = Array.isArray(type) ? type : [type];
111
+ const bind = (t) => sameModule !== null && moduleTypes.has(t);
112
+ const captured = { [MODULE_CAPTURE]: sameModule };
78
113
  const folderTypes = types.filter((t) => !fileTypes.has(t));
79
114
  const categories = types.filter((t) => fileTypes.has(t));
80
115
  const out = [];
81
116
  for (const folderType of folderTypes) {
82
- const element = { ...rest, type: folderType };
117
+ const element = {
118
+ ...rest,
119
+ type: folderType,
120
+ ...(bind(folderType) ? { captured } : {}),
121
+ };
83
122
  const excluded = excludedCategories.get(folderType) ?? [];
84
123
  out.push(
85
124
  excluded.length === 0
@@ -87,44 +126,155 @@ function convertSelector(selector, classification) {
87
126
  : { element, file: { categories: { noneOf: excluded } } },
88
127
  );
89
128
  }
90
- if (categories.length > 0) {
91
- out.push({ file: { categories } });
129
+ const boundCategories = categories.filter(bind);
130
+ const freeCategories = categories.filter((t) => !bind(t));
131
+ if (freeCategories.length > 0) {
132
+ out.push({ file: { categories: freeCategories } });
133
+ }
134
+ if (boundCategories.length > 0) {
135
+ out.push({ file: { categories: boundCategories, captured } });
92
136
  }
93
137
  return out;
94
138
  }
95
139
 
96
- function convertSide(value, classification) {
140
+ function convertSide(value, classification, sameModule = null) {
97
141
  const list = (Array.isArray(value) ? value : [value]).flatMap((s) =>
98
- convertSelector(s, classification),
142
+ convertSelector(s, classification, sameModule),
99
143
  );
100
144
  return list.length === 1 ? list[0] : list;
101
145
  }
102
146
 
103
- function convertClause(clause, classification) {
147
+ function convertClause(clause, classification, sameModule = null) {
104
148
  if (!clause || typeof clause !== "object") return clause;
105
149
  if (Array.isArray(clause))
106
- return clause.map((c) => convertClause(c, classification));
150
+ return clause.map((c) => convertClause(c, classification, sameModule));
107
151
  const next = { ...clause };
108
- if ("to" in next) next.to = convertSide(next.to, classification);
152
+ if ("to" in next) next.to = convertSide(next.to, classification, sameModule);
109
153
  if ("from" in next) next.from = convertSide(next.from, classification);
110
154
  return next;
111
155
  }
112
156
 
157
+ function convertRule(rule, classification, sameModule = null) {
158
+ const { scope: _scope, ...policy } = rule;
159
+ if ("from" in policy) policy.from = convertSide(policy.from, classification);
160
+ if ("to" in policy) policy.to = convertSide(policy.to, classification);
161
+ if ("allow" in policy)
162
+ policy.allow = convertClause(policy.allow, classification, sameModule);
163
+ if ("disallow" in policy) {
164
+ policy.disallow = convertClause(
165
+ policy.disallow,
166
+ classification,
167
+ sameModule,
168
+ );
169
+ }
170
+ return policy;
171
+ }
172
+
173
+ /**
174
+ * `scope: "module"` 규칙은 from type마다 정책을 나눠 from의 모듈 템플릿을 붙인다
175
+ * (파일·폴더 레이어는 템플릿 경로가 다르다).
176
+ */
177
+ function expandModuleRule(rule, classification) {
178
+ const fromTypes = typesOf(rule.from);
179
+ if (fromTypes.length === 0) return [convertRule(rule, classification)];
180
+ const others =
181
+ rule.from && typeof rule.from === "object" && !Array.isArray(rule.from)
182
+ ? rule.from
183
+ : {};
184
+ return fromTypes.map((type) =>
185
+ convertRule(
186
+ { ...rule, from: { ...others, type } },
187
+ classification,
188
+ moduleTemplate(type, classification),
189
+ ),
190
+ );
191
+ }
192
+
193
+ /**
194
+ * v6 규칙 → v7 정책. 순서: 레이어 규칙(같은 모듈 한정 포함) → 모듈 간 공개 계약
195
+ * (`scope: "cross-module"`). 모두 허용 정책이라 순서는 가독성용이다.
196
+ */
113
197
  export function toBoundariesPolicies(
114
198
  rules,
115
- classification = { fileTypes: new Set(), excludedCategories: new Map() },
199
+ classification = EMPTY_CLASSIFICATION,
116
200
  ) {
117
- return rules.map((rule) => {
118
- const policy = { ...rule };
119
- if ("from" in policy)
120
- policy.from = convertSide(policy.from, classification);
121
- if ("to" in policy) policy.to = convertSide(policy.to, classification);
122
- if ("allow" in policy)
123
- policy.allow = convertClause(policy.allow, classification);
124
- if ("disallow" in policy) {
125
- policy.disallow = convertClause(policy.disallow, classification);
201
+ const cross = rules.filter((r) => r.scope === "cross-module");
202
+ const layer = rules.filter((r) => r.scope !== "cross-module");
203
+ return [
204
+ ...layer.flatMap((rule) =>
205
+ rule.scope === "module"
206
+ ? expandModuleRule(rule, classification)
207
+ : [convertRule(rule, classification)],
208
+ ),
209
+ ...cross.map((rule) => convertRule(rule, classification)),
210
+ ];
211
+ }
212
+
213
+ const sortedList = (set) => [...set].sort().join(", ");
214
+
215
+ /**
216
+ * 안내 메시지의 허용 목록. 모듈 레이어는 같은 모듈 / 다른 모듈 / 공유로 나눈다
217
+ * (`scope: "module"` 대상은 같은 모듈만, 그 외 모듈 레이어 대상은 어느 모듈이든).
218
+ */
219
+ function allowText(type, entry, classification) {
220
+ const all = new Set([...entry.same, ...entry.any, ...entry.shared]);
221
+ if (all.size === 0) return `${type}는 다른 레이어를 import할 수 없습니다.`;
222
+ if (!classification.moduleTypes?.has(type)) {
223
+ return `${type}가 import할 수 있는 레이어: ${sortedList(all)}.`;
224
+ }
225
+ const same = new Set([...entry.same, ...entry.any]);
226
+ const parts = [
227
+ `같은 모듈: ${same.size ? sortedList(same) : "없음"}`,
228
+ `다른 모듈: ${entry.any.size ? sortedList(entry.any) : "없음"}`,
229
+ ];
230
+ if (entry.shared.size) parts.push(`공유: ${sortedList(entry.shared)}`);
231
+ return `${type}가 import할 수 있는 레이어 — ${parts.join(" / ")}.`;
232
+ }
233
+
234
+ /**
235
+ * 레이어마다 "전부 금지 + 안내 메시지" 정책을 만든다. 정책은 뒤에서 매칭된 것이
236
+ * 이기므로 이 정책들을 허용 정책보다 앞에 두면, 허용되지 않은 import만 이 정책에
237
+ * 걸려 레이어별 메시지(허용 레이어 목록 포함)가 나온다.
238
+ */
239
+ export function guidancePolicies(
240
+ rules,
241
+ elements,
242
+ classification = EMPTY_CLASSIFICATION,
243
+ ) {
244
+ const moduleTypes = classification.moduleTypes ?? new Set();
245
+ const allowed = new Map();
246
+ for (const rule of rules) {
247
+ const targets = (Array.isArray(rule.allow) ? rule.allow : [rule.allow])
248
+ .filter(Boolean)
249
+ .flatMap((a) => typesOf(a.to));
250
+ for (const from of typesOf(rule.from)) {
251
+ if (!allowed.has(from)) {
252
+ allowed.set(from, {
253
+ same: new Set(),
254
+ any: new Set(),
255
+ shared: new Set(),
256
+ });
257
+ }
258
+ const entry = allowed.get(from);
259
+ const sameOnly = rule.scope === "module" && moduleTypes.has(from);
260
+ for (const to of targets) {
261
+ if (!moduleTypes.has(to)) entry.shared.add(to);
262
+ else (sameOnly ? entry.same : entry.any).add(to);
263
+ }
126
264
  }
127
- return policy;
265
+ }
266
+ const empty = { same: new Set(), any: new Set(), shared: new Set() };
267
+ const types = [...new Set(elements.map((e) => e.type))];
268
+ return types.map((type) => {
269
+ const text = allowText(type, allowed.get(type) ?? empty, classification);
270
+ return {
271
+ from: convertSide({ type }, classification),
272
+ disallow: [
273
+ { to: { element: { type: "*" } } },
274
+ { to: { file: { categories: "*" } } },
275
+ ],
276
+ message: `[경계 위반] ${type} 레이어에서 '{{dependency.source}}'를 import할 수 없습니다. ${text} 레이어별 폴더 위치는 docs/ARCHITECTURE.md 참고.`,
277
+ };
128
278
  });
129
279
  }
130
280