@alxwlw/stack 1.14.0 → 1.16.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.
- package/canon/catalogs.json +21 -21
- package/canon/files/prototools +4 -4
- package/package.json +1 -1
- package/schema.json +1 -1
- package/src/canon.ts +17 -5
- package/src/check.ts +27 -6
- package/src/cli.ts +30 -2
- package/src/exceptions.ts +4 -0
- package/src/findings.ts +4 -1
- package/src/peers-baseline.ts +88 -0
- package/src/peers-rule.ts +48 -0
- package/src/peers.ts +268 -0
- package/src/repo.ts +31 -6
- package/src/sync-pr.ts +10 -0
package/canon/catalogs.json
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"dev": {
|
|
3
3
|
"typescript": "7.1.0-beta",
|
|
4
|
-
"oxlint": "1.
|
|
5
|
-
"oxlint-tsgolint": "7.0.
|
|
6
|
-
"oxfmt": "0.
|
|
4
|
+
"oxlint": "1.94.0",
|
|
5
|
+
"oxlint-tsgolint": "7.0.2007",
|
|
6
|
+
"oxfmt": "0.79.0",
|
|
7
7
|
"@types/node": "26.6.6",
|
|
8
8
|
"@types/bun": "1.4.4",
|
|
9
|
-
"knip": "6.
|
|
10
|
-
"dependency-cruiser": "18.8.0
|
|
9
|
+
"knip": "6.45.1",
|
|
10
|
+
"dependency-cruiser": "18.8.0",
|
|
11
11
|
"vitest": "5.1.0",
|
|
12
|
-
"@playwright/test": "1.
|
|
13
|
-
"@alxwlw/stack": "1.
|
|
14
|
-
"@alxwlw/oxlint-config": "1.
|
|
15
|
-
"@alxwlw/tsconfig": "1.
|
|
12
|
+
"@playwright/test": "1.65.1",
|
|
13
|
+
"@alxwlw/stack": "1.16.0",
|
|
14
|
+
"@alxwlw/oxlint-config": "1.16.0",
|
|
15
|
+
"@alxwlw/tsconfig": "1.16.0"
|
|
16
16
|
},
|
|
17
17
|
"libs": {
|
|
18
|
-
"@nestjs/core": "12.
|
|
19
|
-
"@nestjs/common": "12.
|
|
20
|
-
"@nestjs/platform-express": "12.
|
|
21
|
-
"@nestjs/testing": "12.
|
|
18
|
+
"@nestjs/core": "12.5.1",
|
|
19
|
+
"@nestjs/common": "12.5.1",
|
|
20
|
+
"@nestjs/platform-express": "12.5.1",
|
|
21
|
+
"@nestjs/testing": "12.5.1",
|
|
22
22
|
"reflect-metadata": "0.2.2",
|
|
23
23
|
"rxjs": "7.8.2",
|
|
24
24
|
"@prisma/client": "7.10.1",
|
|
@@ -27,9 +27,9 @@
|
|
|
27
27
|
"pg": "8.23.1",
|
|
28
28
|
"@types/pg": "8.23.1",
|
|
29
29
|
"ioredis": "6.0.0",
|
|
30
|
-
"@nats-io/jetstream": "3.
|
|
31
|
-
"@nats-io/nats-core": "3.
|
|
32
|
-
"@nats-io/transport-node": "3.
|
|
30
|
+
"@nats-io/jetstream": "3.5.0",
|
|
31
|
+
"@nats-io/nats-core": "3.5.0",
|
|
32
|
+
"@nats-io/transport-node": "3.5.0",
|
|
33
33
|
"@opentelemetry/api": "1.10.0",
|
|
34
34
|
"@opentelemetry/core": "3.1.1",
|
|
35
35
|
"@opentelemetry/resources": "3.1.1",
|
|
@@ -46,13 +46,13 @@
|
|
|
46
46
|
"@types/react": "19.3.0",
|
|
47
47
|
"@types/react-dom": "19.3.0",
|
|
48
48
|
"react-router": "8.5.1",
|
|
49
|
-
"@tanstack/react-query": "5.
|
|
49
|
+
"@tanstack/react-query": "5.108.0",
|
|
50
50
|
"@tanstack/react-table": "9.3.1",
|
|
51
|
-
"zustand": "5.0
|
|
51
|
+
"zustand": "5.1.0",
|
|
52
52
|
"@dnd-kit/core": "6.3.1",
|
|
53
|
-
"tailwindcss": "4.3.
|
|
54
|
-
"@tailwindcss/vite": "4.3.
|
|
55
|
-
"lucide-react": "1.
|
|
53
|
+
"tailwindcss": "4.3.5",
|
|
54
|
+
"@tailwindcss/vite": "4.3.5",
|
|
55
|
+
"lucide-react": "1.75.0",
|
|
56
56
|
"@fontsource/ibm-plex-sans": "5.3.0",
|
|
57
57
|
"@fontsource/ibm-plex-mono": "5.3.0",
|
|
58
58
|
"@fontsource/ibm-plex-serif": "5.3.0"
|
package/canon/files/prototools
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# Canon pins. This file is sync-managed: edits happen in alxwlw/stack, not here.
|
|
2
|
-
proto = "0.
|
|
3
|
-
node = "26.13.
|
|
4
|
-
pnpm = "12.
|
|
2
|
+
proto = "0.64.0"
|
|
3
|
+
node = "26.13.1"
|
|
4
|
+
pnpm = "12.21.0"
|
|
5
5
|
bun = "1.4.4"
|
|
6
6
|
moon = "2.6.5"
|
|
7
|
-
uv = "0.13.
|
|
7
|
+
uv = "0.13.9"
|
|
8
8
|
|
|
9
9
|
# Guardrail binaries: versions pinned for reproducibility.
|
|
10
10
|
actionlint = "1.7.12"
|
package/package.json
CHANGED
package/schema.json
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"description": "Opt-in canon groups. \"renovate\" is deprecated and does nothing: Renovate is the canon's dependency bot for every profile.",
|
|
15
15
|
"items": {
|
|
16
16
|
"type": "string",
|
|
17
|
-
"enum": ["depcruise", "knip", "libs", "moon-tasks", "renovate"]
|
|
17
|
+
"enum": ["depcruise", "knip", "libs", "moon-tasks", "peers", "renovate"]
|
|
18
18
|
}
|
|
19
19
|
},
|
|
20
20
|
"exceptions": {
|
package/src/canon.ts
CHANGED
|
@@ -120,6 +120,8 @@ export interface Canon {
|
|
|
120
120
|
files: { dest: string; content: string; strategy?: SyncStrategy; satisfiedBy?: string[] }[];
|
|
121
121
|
catalogs: CanonCatalogs;
|
|
122
122
|
pins: Pins;
|
|
123
|
+
/** Включённые через with группы правил, в порядке RULE_GROUPS. */
|
|
124
|
+
rules: RuleGroup[];
|
|
123
125
|
}
|
|
124
126
|
|
|
125
127
|
// Пины инструментов из .prototools канона: node и pnpm обязательны, прочие строки верхнего уровня допустимы.
|
|
@@ -136,10 +138,15 @@ export function canonDir(): string {
|
|
|
136
138
|
// Устаревшие группы принимаются ради старых .stack.jsonc и ничего не включают.
|
|
137
139
|
const DEPRECATED_GROUPS: readonly string[] = ['renovate'];
|
|
138
140
|
|
|
141
|
+
// Группа правила включает правило `stack check`, файлов и каталогов не даёт.
|
|
142
|
+
export const RULE_GROUPS = ['peers'] as const;
|
|
143
|
+
export type RuleGroup = (typeof RULE_GROUPS)[number];
|
|
144
|
+
|
|
139
145
|
export interface CanonGroups {
|
|
140
146
|
files: string[];
|
|
141
147
|
catalogs: string[];
|
|
142
148
|
deprecated: readonly string[];
|
|
149
|
+
rules: readonly string[];
|
|
143
150
|
}
|
|
144
151
|
|
|
145
152
|
// canon/ как значение: все записи манифеста с содержимым, каталоги и имена групп. Читается один раз;
|
|
@@ -151,7 +158,8 @@ export interface CanonSource {
|
|
|
151
158
|
}
|
|
152
159
|
|
|
153
160
|
// Единственное место, где canon/ читается с диска: manifest.json и catalogs.json по разу, каждый src по разу.
|
|
154
|
-
// Имена групп: файловые — поле group манифеста, каталожные — ключи catalogs.json кроме dev
|
|
161
|
+
// Имена групп: файловые — поле group манифеста, каталожные — ключи catalogs.json кроме dev, устаревшие и
|
|
162
|
+
// группы правил — константы этого модуля.
|
|
155
163
|
export function readCanonSource(dir: string = canonDir()): CanonSource {
|
|
156
164
|
const manifest = checkManifest(JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')));
|
|
157
165
|
const catalogs = JSON.parse(readFileSync(join(dir, 'catalogs.json'), 'utf8')) as CanonCatalogs;
|
|
@@ -163,13 +171,15 @@ export function readCanonSource(dir: string = canonDir()): CanonSource {
|
|
|
163
171
|
files: [...new Set(entries.flatMap((f) => (f.group == null ? [] : [f.group])))],
|
|
164
172
|
catalogs: Object.keys(catalogs).filter((g) => g !== 'dev'),
|
|
165
173
|
deprecated: DEPRECATED_GROUPS,
|
|
174
|
+
rules: RULE_GROUPS,
|
|
166
175
|
};
|
|
167
176
|
return { entries, catalogs, groups };
|
|
168
177
|
}
|
|
169
178
|
|
|
170
|
-
// Все имена, допустимые в `with`: файловые,
|
|
179
|
+
// Все имена, допустимые в `with`: файловые, каталожные, устаревшие и группы правил — без повторов,
|
|
180
|
+
// по алфавиту.
|
|
171
181
|
export function knownGroups(g: CanonGroups): string[] {
|
|
172
|
-
return [...new Set([...g.files, ...g.catalogs, ...g.deprecated])].sort();
|
|
182
|
+
return [...new Set([...g.files, ...g.catalogs, ...g.deprecated, ...g.rules])].sort();
|
|
173
183
|
}
|
|
174
184
|
|
|
175
185
|
export function assertKnownGroups(groups: readonly string[], source: CanonSource): void {
|
|
@@ -191,7 +201,8 @@ export function selectEntries(source: CanonSource, cfg: StackConfig): CanonSourc
|
|
|
191
201
|
);
|
|
192
202
|
}
|
|
193
203
|
|
|
194
|
-
// Чистый шаг от источника к Canon: проверка групп, выбор записей, каталоги,
|
|
204
|
+
// Чистый шаг от источника к Canon: проверка групп, выбор записей, каталоги, пины, группы правил.
|
|
205
|
+
// Диск не трогает.
|
|
195
206
|
export function canonFor(source: CanonSource, cfg: StackConfig): Canon {
|
|
196
207
|
assertKnownGroups(cfg.with, source);
|
|
197
208
|
const files = selectEntries(source, cfg).map((f) => ({
|
|
@@ -215,7 +226,8 @@ export function canonFor(source: CanonSource, cfg: StackConfig): Canon {
|
|
|
215
226
|
if (!node) throw new Error('canon .prototools has no node pin');
|
|
216
227
|
// Пин pnpm нужен правилу package-manager: поле packageManager — второй источник версии pnpm.
|
|
217
228
|
if (!pnpm) throw new Error('canon .prototools has no pnpm pin');
|
|
218
|
-
|
|
229
|
+
const rules = RULE_GROUPS.filter((g) => cfg.with.includes(g));
|
|
230
|
+
return { files, catalogs, pins: { ...rest, node, pnpm }, rules };
|
|
219
231
|
}
|
|
220
232
|
|
|
221
233
|
export function loadCanon(cfg: StackConfig, dir: string = canonDir()): Canon {
|
package/src/check.ts
CHANGED
|
@@ -13,8 +13,10 @@ import type { Drift, Finding } from './findings.ts';
|
|
|
13
13
|
import { checkMoonToolchains } from './moon-toolchains.ts';
|
|
14
14
|
import { checkMoonDefaultBranch, planMoonDefaultBranch } from './moon-workspace.ts';
|
|
15
15
|
import { planPackageManager } from './package-manager.ts';
|
|
16
|
+
import { type PeersOutcome, peersOutcome, type PeersReader } from './peers.ts';
|
|
17
|
+
import { checkPeers } from './peers-rule.ts';
|
|
16
18
|
import { planReleaseAgeExcludes } from './release-age.ts';
|
|
17
|
-
import { loadRepo, type Repo } from './repo.ts';
|
|
19
|
+
import { loadRepo, LOCKFILE, type Repo } from './repo.ts';
|
|
18
20
|
|
|
19
21
|
// План дрейфа: всё, что sync умеет закрыть, в порядке применения — файлы, каталоги, release-age,
|
|
20
22
|
// packageManager, ветка по умолчанию moon. Правки одного файла друг от друга не зависят: sync применяет любое их подмножество.
|
|
@@ -28,9 +30,15 @@ export function plan(repo: Repo, canon: Canon): Drift[] {
|
|
|
28
30
|
];
|
|
29
31
|
}
|
|
30
32
|
|
|
31
|
-
// Находки в порядке: план, нечитаемые файлы загрузчика, правила «только отчёт» из deps.ts
|
|
32
|
-
// протухшие исключения. Все они проходят через
|
|
33
|
-
|
|
33
|
+
// Находки в порядке: план, нечитаемые файлы загрузчика, правила «только отчёт» из deps.ts и moon,
|
|
34
|
+
// правило группы peers, если она включена; затем протухшие исключения. Все они проходят через
|
|
35
|
+
// исключения. peers — исход `pnpm peers check`, его получает checkRepo.
|
|
36
|
+
export function check(
|
|
37
|
+
repo: Repo,
|
|
38
|
+
canon: Canon,
|
|
39
|
+
exceptions: Exception[],
|
|
40
|
+
peers?: PeersOutcome,
|
|
41
|
+
): Finding[] {
|
|
34
42
|
const r = resolve(
|
|
35
43
|
[
|
|
36
44
|
...plan(repo, canon),
|
|
@@ -41,6 +49,7 @@ export function check(repo: Repo, canon: Canon, exceptions: Exception[]): Findin
|
|
|
41
49
|
...checkDependabot(repo),
|
|
42
50
|
...checkMoonToolchains(repo, canon),
|
|
43
51
|
...checkMoonDefaultBranch(repo),
|
|
52
|
+
...(canon.rules.includes('peers') ? checkPeers(repo, peers) : []),
|
|
44
53
|
],
|
|
45
54
|
exceptions,
|
|
46
55
|
);
|
|
@@ -51,8 +60,20 @@ export function planRepo(repoRoot: string, canon: Canon): Drift[] {
|
|
|
51
60
|
return plan(loadRepo(repoRoot, canon), canon);
|
|
52
61
|
}
|
|
53
62
|
|
|
54
|
-
|
|
55
|
-
|
|
63
|
+
// pnpm запускается, только если группа peers включена и лок есть: без лока правило отвечает само.
|
|
64
|
+
export function checkRepo(
|
|
65
|
+
repoRoot: string,
|
|
66
|
+
canon: Canon,
|
|
67
|
+
exceptions: Exception[],
|
|
68
|
+
readPeers?: PeersReader,
|
|
69
|
+
): Finding[] {
|
|
70
|
+
const repo = loadRepo(repoRoot, canon);
|
|
71
|
+
let peers: PeersOutcome | undefined;
|
|
72
|
+
if (canon.rules.includes('peers') && repo.paths.has(LOCKFILE)) {
|
|
73
|
+
if (readPeers === undefined) throw new Error('checkRepo: peers group needs a PeersReader');
|
|
74
|
+
peers = peersOutcome(readPeers(repoRoot));
|
|
75
|
+
}
|
|
76
|
+
return check(repo, canon, exceptions, peers);
|
|
56
77
|
}
|
|
57
78
|
|
|
58
79
|
export interface SyncResult {
|
package/src/cli.ts
CHANGED
|
@@ -10,6 +10,8 @@ import { allowedLine, isHeld } from './exceptions.ts';
|
|
|
10
10
|
import { type Finding, isDrift } from './findings.ts';
|
|
11
11
|
import { ghGitHub } from './gh.ts';
|
|
12
12
|
import { initConfig } from './init.ts';
|
|
13
|
+
import type { PeersReader } from './peers.ts';
|
|
14
|
+
import { peersBaseline } from './peers-baseline.ts';
|
|
13
15
|
import { npmRegistryReader } from './registry.ts';
|
|
14
16
|
import { ownVersion, type RunProcess, SYNC_PR_WAIT, syncPr, withoutGhToken } from './sync-pr.ts';
|
|
15
17
|
|
|
@@ -29,6 +31,8 @@ function parseCliArgs() {
|
|
|
29
31
|
with: { type: 'string', multiple: true },
|
|
30
32
|
base: { type: 'string' },
|
|
31
33
|
'no-install': { type: 'boolean' },
|
|
34
|
+
init: { type: 'boolean' },
|
|
35
|
+
'allow-grow': { type: 'boolean' },
|
|
32
36
|
},
|
|
33
37
|
});
|
|
34
38
|
} catch (error) {
|
|
@@ -67,6 +71,19 @@ const runProcess: RunProcess = (cmd, args, { cwd, env }) => {
|
|
|
67
71
|
return r.status ?? 1;
|
|
68
72
|
};
|
|
69
73
|
|
|
74
|
+
// Боевой adapter порта pnpm для группы peers: вывод захватывается, разбор — peersOutcome. Проверка
|
|
75
|
+
// идёт по локу, без установки; GH_TOKEN не нужен pnpm, как и установке в sync-pr.
|
|
76
|
+
const pnpmPeers: PeersReader = (cwd) => {
|
|
77
|
+
const r = spawnSync('pnpm', ['peers', 'check', '--lockfile-only', '--json'], {
|
|
78
|
+
cwd,
|
|
79
|
+
encoding: 'utf8',
|
|
80
|
+
maxBuffer: 1 << 30,
|
|
81
|
+
env: withoutGhToken(process.env),
|
|
82
|
+
});
|
|
83
|
+
if (r.error) return { error: r.error.message };
|
|
84
|
+
return { status: r.status, signal: r.signal, stdout: r.stdout, stderr: r.stderr };
|
|
85
|
+
};
|
|
86
|
+
|
|
70
87
|
const { values, positionals } = parseCliArgs();
|
|
71
88
|
|
|
72
89
|
const repoRoot = values.repo ?? process.cwd();
|
|
@@ -90,7 +107,7 @@ try {
|
|
|
90
107
|
for (const line of stdout) console.log(line);
|
|
91
108
|
} else if (command === 'check') {
|
|
92
109
|
const cfg = readStackConfig(repoRoot);
|
|
93
|
-
const findings = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions);
|
|
110
|
+
const findings = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions, pnpmPeers);
|
|
94
111
|
const blocking = findings.filter((f) => !isHeld(f));
|
|
95
112
|
for (const f of findings.filter(isHeld)) console.warn(allowedLine(f));
|
|
96
113
|
for (const f of blocking) console.error(`${f.code}: ${f.target} — ${f.message}`);
|
|
@@ -119,11 +136,22 @@ try {
|
|
|
119
136
|
github: ghGitHub(repoRoot),
|
|
120
137
|
registry: npmRegistryReader(),
|
|
121
138
|
print: (stream, line) => (stream === 'out' ? console.log(line) : console.error(line)),
|
|
139
|
+
peers: pnpmPeers,
|
|
122
140
|
},
|
|
123
141
|
),
|
|
124
142
|
);
|
|
143
|
+
} else if (command === 'peers-baseline') {
|
|
144
|
+
if (values.init && values['allow-grow']) fail('--init and --allow-grow do not go together');
|
|
145
|
+
const cfg = readStackConfig(repoRoot);
|
|
146
|
+
const mode = values.init ? 'init' : values['allow-grow'] ? 'grow' : 'lower';
|
|
147
|
+
const r = peersBaseline(repoRoot, loadCanon(cfg), mode, pnpmPeers);
|
|
148
|
+
for (const line of r.out) console.log(line);
|
|
149
|
+
for (const line of r.err) console.error(line);
|
|
150
|
+
process.exit(r.code);
|
|
125
151
|
} else {
|
|
126
|
-
fail(
|
|
152
|
+
fail(
|
|
153
|
+
`unknown command "${command ?? ''}". Available: init, sync, check, sync-pr, peers-baseline`,
|
|
154
|
+
);
|
|
127
155
|
}
|
|
128
156
|
} catch (error) {
|
|
129
157
|
if (error instanceof StackConfigError) fail(error.message);
|
package/src/exceptions.ts
CHANGED
|
@@ -96,6 +96,10 @@ const ADDRESS: { [C in FindingCode]: ((f: FindingOf<C>) => Address) | 'unsuppres
|
|
|
96
96
|
'moon-default-branch': (f) => ({ file: f.file }),
|
|
97
97
|
'unreadable-file': 'unsuppressible',
|
|
98
98
|
'stale-exception': 'unsuppressible',
|
|
99
|
+
// Исключение для находок peers — сам baseline; отказ от гейта — убрать группу из with.
|
|
100
|
+
'peer-dependency': 'unsuppressible',
|
|
101
|
+
'stale-peer-baseline': 'unsuppressible',
|
|
102
|
+
'peers-unavailable': 'unsuppressible',
|
|
99
103
|
};
|
|
100
104
|
|
|
101
105
|
export function addressOf(f: Finding): Address | undefined {
|
package/src/findings.ts
CHANGED
|
@@ -22,7 +22,10 @@ export type Finding = FindingBase &
|
|
|
22
22
|
| 'dependabot-config'
|
|
23
23
|
| 'moon-toolchain-version'
|
|
24
24
|
| 'unreadable-file'
|
|
25
|
-
| 'stale-exception'
|
|
25
|
+
| 'stale-exception'
|
|
26
|
+
| 'peer-dependency'
|
|
27
|
+
| 'stale-peer-baseline'
|
|
28
|
+
| 'peers-unavailable';
|
|
26
29
|
}
|
|
27
30
|
);
|
|
28
31
|
export type FindingCode = Finding['code'];
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// `stack peers-baseline`: единственное место, где файл baseline группы peers пишется на диск.
|
|
2
|
+
// init — записать текущие проблемы в новый файл; lower — только убрать исправленные; grow — принять
|
|
3
|
+
// и новые; drop-fixed — убрать исправленные, если они есть, молча во всём остальном (sync-pr).
|
|
4
|
+
|
|
5
|
+
import { writeFileSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
import type { Canon } from './canon.ts';
|
|
9
|
+
import {
|
|
10
|
+
comparePeers,
|
|
11
|
+
lowerPeersBaseline,
|
|
12
|
+
PEERS_BASELINE,
|
|
13
|
+
peersOutcome,
|
|
14
|
+
type PeersReader,
|
|
15
|
+
serializePeersBaseline,
|
|
16
|
+
} from './peers.ts';
|
|
17
|
+
import { loadRepo, LOCKFILE } from './repo.ts';
|
|
18
|
+
|
|
19
|
+
export type PeersBaselineMode = 'init' | 'lower' | 'grow' | 'drop-fixed';
|
|
20
|
+
|
|
21
|
+
export interface PeersBaselineResult {
|
|
22
|
+
code: 0 | 1 | 2;
|
|
23
|
+
out: string[];
|
|
24
|
+
err: string[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const failed = (code: 1 | 2, line: string): PeersBaselineResult => ({ code, out: [], err: [line] });
|
|
28
|
+
const quiet = (): PeersBaselineResult => ({ code: 0, out: [], err: [] });
|
|
29
|
+
|
|
30
|
+
// Порядок проверок: группа, разбор файла, есть ли файл для режима, лок, pnpm, рост в lower. Первая
|
|
31
|
+
// сработавшая решает; файл пишется только в самом конце. drop-fixed там, где делать нечего, молчит.
|
|
32
|
+
export function peersBaseline(
|
|
33
|
+
repoRoot: string,
|
|
34
|
+
canon: Canon,
|
|
35
|
+
mode: PeersBaselineMode,
|
|
36
|
+
readPeers: PeersReader,
|
|
37
|
+
): PeersBaselineResult {
|
|
38
|
+
const dropFixed = mode === 'drop-fixed';
|
|
39
|
+
if (!canon.rules.includes('peers')) {
|
|
40
|
+
return dropFixed
|
|
41
|
+
? quiet()
|
|
42
|
+
: failed(2, 'peers-baseline needs "peers" in "with" of .stack.jsonc');
|
|
43
|
+
}
|
|
44
|
+
const repo = loadRepo(repoRoot, canon);
|
|
45
|
+
// Неразобранный файл не перезаписывается: в нём могли быть записи, которых больше нигде нет.
|
|
46
|
+
const broken = repo.unreadable.find((f) => f.target === PEERS_BASELINE);
|
|
47
|
+
if (broken !== undefined) return failed(2, broken.message);
|
|
48
|
+
const exists = repo.paths.has(PEERS_BASELINE);
|
|
49
|
+
if (mode === 'init' && exists) return failed(2, `${PEERS_BASELINE} already exists`);
|
|
50
|
+
if (mode !== 'init' && !exists) {
|
|
51
|
+
return dropFixed ? quiet() : failed(2, `no ${PEERS_BASELINE}: run stack peers-baseline --init`);
|
|
52
|
+
}
|
|
53
|
+
if (!repo.paths.has(LOCKFILE)) return failed(1, `no ${LOCKFILE}`);
|
|
54
|
+
const outcome = peersOutcome(readPeers(repoRoot));
|
|
55
|
+
if ('unavailable' in outcome) return failed(1, outcome.unavailable);
|
|
56
|
+
|
|
57
|
+
const current = outcome.issues;
|
|
58
|
+
const baseline = repo.peersBaseline ?? [];
|
|
59
|
+
const { added, stale } = comparePeers(current, baseline);
|
|
60
|
+
if (mode === 'lower' && added.length > 0) {
|
|
61
|
+
return {
|
|
62
|
+
code: 1,
|
|
63
|
+
out: [],
|
|
64
|
+
err: [
|
|
65
|
+
...added.map((i) => `new: ${i.entry.peer} in ${i.entry.importer} — ${i.detail}`),
|
|
66
|
+
`${added.length} new entr(ies) — fix them or pass --allow-grow`,
|
|
67
|
+
],
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
if (dropFixed && stale.length === 0) return quiet();
|
|
71
|
+
|
|
72
|
+
const next =
|
|
73
|
+
mode === 'init' || mode === 'grow'
|
|
74
|
+
? current.map((i) => i.entry)
|
|
75
|
+
: lowerPeersBaseline(baseline, current);
|
|
76
|
+
writeFileSync(
|
|
77
|
+
join(repoRoot, PEERS_BASELINE),
|
|
78
|
+
serializePeersBaseline(next, repo.files.get(PEERS_BASELINE)),
|
|
79
|
+
);
|
|
80
|
+
const wrote = `wrote ${PEERS_BASELINE}: ${next.length} entr(ies)`;
|
|
81
|
+
const line =
|
|
82
|
+
mode === 'init'
|
|
83
|
+
? wrote
|
|
84
|
+
: dropFixed
|
|
85
|
+
? `dropped ${stale.length} fixed entr(ies) from ${PEERS_BASELINE}`
|
|
86
|
+
: `${wrote} (-${stale.length} fixed, +${added.length} new)`;
|
|
87
|
+
return { code: 0, out: [line], err: [] };
|
|
88
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Правило группы peers над Repo: исход `pnpm peers check` против baseline. Отдельный модуль, потому
|
|
2
|
+
// что repo.ts берёт разбор baseline из peers.ts, и правило в peers.ts замкнуло бы цикл импортов.
|
|
3
|
+
|
|
4
|
+
import type { Finding } from './findings.ts';
|
|
5
|
+
import { comparePeers, type PeerEntry, PEERS_BASELINE, type PeersOutcome } from './peers.ts';
|
|
6
|
+
import { LOCKFILE, type Repo } from './repo.ts';
|
|
7
|
+
|
|
8
|
+
const TARGET = 'pnpm peers check';
|
|
9
|
+
|
|
10
|
+
const where = (e: PeerEntry): string => `${e.peer} in ${e.importer}`;
|
|
11
|
+
|
|
12
|
+
// Запись baseline словами: вид, объявивший пакет и линия найденной версии, если они есть у вида.
|
|
13
|
+
function recorded(e: PeerEntry): string {
|
|
14
|
+
switch (e.kind) {
|
|
15
|
+
case 'unmet':
|
|
16
|
+
return `unmet by ${e.by} (found ${e.found})`;
|
|
17
|
+
case 'missing':
|
|
18
|
+
return `missing by ${e.by}`;
|
|
19
|
+
case 'conflict':
|
|
20
|
+
return 'conflict';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Без лока pnpm ответил бы `{}` с кодом 0, то есть «чисто», поэтому исход тогда не читается вовсе.
|
|
25
|
+
// Неразобранный baseline даёт находку в загрузчике, и пустым baseline он не считается.
|
|
26
|
+
export function checkPeers(repo: Repo, outcome: PeersOutcome | undefined): Finding[] {
|
|
27
|
+
if (!repo.paths.has(LOCKFILE)) {
|
|
28
|
+
return [{ code: 'peers-unavailable', target: TARGET, message: `no ${LOCKFILE}` }];
|
|
29
|
+
}
|
|
30
|
+
if (outcome === undefined) throw new Error('checkPeers: no pnpm peers check outcome');
|
|
31
|
+
if ('unavailable' in outcome) {
|
|
32
|
+
return [{ code: 'peers-unavailable', target: TARGET, message: outcome.unavailable }];
|
|
33
|
+
}
|
|
34
|
+
if (repo.paths.has(PEERS_BASELINE) && repo.peersBaseline === undefined) return [];
|
|
35
|
+
const { added, stale } = comparePeers(outcome.issues, repo.peersBaseline ?? []);
|
|
36
|
+
return [
|
|
37
|
+
...added.map((i): Finding => ({
|
|
38
|
+
code: 'peer-dependency',
|
|
39
|
+
target: where(i.entry),
|
|
40
|
+
message: `${i.detail}; not in ${PEERS_BASELINE}`,
|
|
41
|
+
})),
|
|
42
|
+
...stale.map((e): Finding => ({
|
|
43
|
+
code: 'stale-peer-baseline',
|
|
44
|
+
target: where(e),
|
|
45
|
+
message: `recorded ${recorded(e)} is gone; drop it with: stack peers-baseline`,
|
|
46
|
+
})),
|
|
47
|
+
];
|
|
48
|
+
}
|
package/src/peers.ts
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// Ядро гейта `pnpm peers check`: разбор ответа pnpm, ключ проблемы, файл baseline и сравнение.
|
|
2
|
+
// Только чистые функции: процесс pnpm и диск — у вызывающих.
|
|
3
|
+
|
|
4
|
+
export const PEERS_BASELINE = '.stack-peers-baseline.json';
|
|
5
|
+
|
|
6
|
+
// Устойчивый ключ одной проблемы и запись baseline — одно и то же значение.
|
|
7
|
+
// Сырой JSON pnpm недетерминирован, поэтому в ключе нет версии объявившего пакета, wantedRange
|
|
8
|
+
// и parents[0].
|
|
9
|
+
export type PeerEntry =
|
|
10
|
+
| { importer: string; peer: string; kind: 'unmet'; by: string; found: string }
|
|
11
|
+
| { importer: string; peer: string; kind: 'missing'; by: string }
|
|
12
|
+
| { importer: string; peer: string; kind: 'conflict' };
|
|
13
|
+
|
|
14
|
+
// Текущая проблема: ключ плюс текст для находки (не входит в ключ).
|
|
15
|
+
export interface PeerIssue {
|
|
16
|
+
entry: PeerEntry;
|
|
17
|
+
detail: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Результат запуска pnpm как данные: порт процесса отдаёт его, разбор — чистый.
|
|
21
|
+
export type PeersRun =
|
|
22
|
+
| { status: number | null; signal: string | null; stdout: string; stderr: string }
|
|
23
|
+
| { error: string };
|
|
24
|
+
export type PeersOutcome = { issues: PeerIssue[] } | { unavailable: string };
|
|
25
|
+
// Порт процесса: запуск `pnpm peers check` в корне репозитория.
|
|
26
|
+
export type PeersReader = (repoRoot: string) => PeersRun;
|
|
27
|
+
|
|
28
|
+
// Линия версии: major, у 0.x — 0.minor, у 0.0.x — 0.0.patch. Пре-релиз и build отброшены,
|
|
29
|
+
// версия не по semver (link:, file:) остаётся как есть.
|
|
30
|
+
export function versionLine(version: string): string {
|
|
31
|
+
const [major, minor, patch, ...rest] = version.replace(/[-+][\s\S]*$/, '').split('.');
|
|
32
|
+
const digits = (p: string | undefined): p is string => p !== undefined && /^\d+$/.test(p);
|
|
33
|
+
if (!digits(major) || !digits(minor) || !digits(patch) || rest.length > 0) return version;
|
|
34
|
+
if (Number(major) > 0) return major;
|
|
35
|
+
if (Number(minor) > 0) return `0.${minor}`;
|
|
36
|
+
return `0.0.${patch}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function peerKey(e: PeerEntry): string {
|
|
40
|
+
const by = e.kind === 'conflict' ? '' : e.by;
|
|
41
|
+
const found = e.kind === 'unmet' ? e.found : '';
|
|
42
|
+
return JSON.stringify([e.importer, e.peer, e.kind, by, found]);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Порядок записей везде — по ключу, сравнением строк по кодовым единицам.
|
|
46
|
+
function byKey<T>(items: readonly T[], key: (t: T) => string): T[] {
|
|
47
|
+
return items
|
|
48
|
+
.map((item) => ({ item, k: key(item) }))
|
|
49
|
+
.sort((a, b) => (a.k < b.k ? -1 : a.k > b.k ? 1 : 0))
|
|
50
|
+
.map(({ item }) => item);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const sortEntries = (entries: readonly PeerEntry[]): PeerEntry[] => byKey(entries, peerKey);
|
|
54
|
+
const sortIssues = (issues: readonly PeerIssue[]): PeerIssue[] =>
|
|
55
|
+
byKey(issues, (i) => peerKey(i.entry));
|
|
56
|
+
|
|
57
|
+
function isObject(v: unknown): v is Record<string, unknown> {
|
|
58
|
+
return v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const nonEmpty = (v: unknown): v is string => typeof v === 'string' && v !== '';
|
|
62
|
+
|
|
63
|
+
// Общая часть записи pnpm из bad и missing после проверки формы. by — parents[-1], пакет,
|
|
64
|
+
// который объявил peer.
|
|
65
|
+
interface PnpmRecord {
|
|
66
|
+
by: string;
|
|
67
|
+
byVersion: string;
|
|
68
|
+
wantedRange: string;
|
|
69
|
+
suffix: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Сбой формы ответа pnpm; peersOutcome превращает его в unavailable.
|
|
73
|
+
class ShapeError extends Error {}
|
|
74
|
+
|
|
75
|
+
function pnpmRecord(raw: Record<string, unknown>, at: string): PnpmRecord {
|
|
76
|
+
const isParent = (p: unknown): p is { name: string; version: string } =>
|
|
77
|
+
isObject(p) && nonEmpty(p.name) && typeof p.version === 'string';
|
|
78
|
+
const parents: unknown[] = Array.isArray(raw.parents) ? raw.parents : [];
|
|
79
|
+
const last = parents.at(-1);
|
|
80
|
+
if (!parents.every(isParent) || !isParent(last)) {
|
|
81
|
+
throw new ShapeError(`${at}: "parents" is not a non-empty array of {name, version}`);
|
|
82
|
+
}
|
|
83
|
+
if (typeof raw.optional !== 'boolean') throw new ShapeError(`${at}: "optional" is not a boolean`);
|
|
84
|
+
if (typeof raw.wantedRange !== 'string') {
|
|
85
|
+
throw new ShapeError(`${at}: "wantedRange" is not a string`);
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
by: last.name,
|
|
89
|
+
byVersion: last.version,
|
|
90
|
+
wantedRange: raw.wantedRange,
|
|
91
|
+
suffix: raw.optional ? ' (optional)' : '',
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Записи поля bad или missing одного importer: peer, сама запись и её место для текста сбоя.
|
|
96
|
+
function pnpmGroup(
|
|
97
|
+
importer: Record<string, unknown>,
|
|
98
|
+
field: 'bad' | 'missing',
|
|
99
|
+
at: string,
|
|
100
|
+
): [string, Record<string, unknown>, string][] {
|
|
101
|
+
const group = importer[field];
|
|
102
|
+
if (!isObject(group)) throw new ShapeError(`${at}: "${field}" is not an object`);
|
|
103
|
+
const out: [string, Record<string, unknown>, string][] = [];
|
|
104
|
+
for (const [peer, records] of Object.entries(group)) {
|
|
105
|
+
const where = `${at}: ${field} ${JSON.stringify(peer)}`;
|
|
106
|
+
if (peer === '') throw new ShapeError(`${where} has an empty name`);
|
|
107
|
+
if (!Array.isArray(records)) throw new ShapeError(`${where} is not an array`);
|
|
108
|
+
records.forEach((r: unknown, i) => {
|
|
109
|
+
if (!isObject(r)) throw new ShapeError(`${where}[${i}] is not an object`);
|
|
110
|
+
out.push([peer, r, `${where}[${i}]`]);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Разбор разобранного JSON в проблемы. Несколько исходных записей одного ключа — одна проблема
|
|
117
|
+
// с наименьшим текстом: так текст не зависит от порядка записей в ответе pnpm.
|
|
118
|
+
function pnpmIssues(json: unknown): PeerIssue[] {
|
|
119
|
+
if (!isObject(json)) throw new ShapeError('top level is not an object');
|
|
120
|
+
const seen = new Map<string, PeerIssue>();
|
|
121
|
+
const add = (entry: PeerEntry, detail: string): void => {
|
|
122
|
+
const k = peerKey(entry);
|
|
123
|
+
const prev = seen.get(k);
|
|
124
|
+
if (prev === undefined || detail < prev.detail) seen.set(k, { entry, detail });
|
|
125
|
+
};
|
|
126
|
+
for (const [importer, raw] of Object.entries(json)) {
|
|
127
|
+
const at = `importer ${JSON.stringify(importer)}`;
|
|
128
|
+
if (importer === '') throw new ShapeError(`${at} has an empty name`);
|
|
129
|
+
if (!isObject(raw)) throw new ShapeError(`${at} is not an object`);
|
|
130
|
+
for (const [peer, rec, where] of pnpmGroup(raw, 'bad', at)) {
|
|
131
|
+
const r = pnpmRecord(rec, where);
|
|
132
|
+
const found = rec.foundVersion;
|
|
133
|
+
if (!nonEmpty(found)) {
|
|
134
|
+
throw new ShapeError(`${where}: "foundVersion" is not a non-empty string`);
|
|
135
|
+
}
|
|
136
|
+
add(
|
|
137
|
+
{ importer, peer, kind: 'unmet', by: r.by, found: versionLine(found) },
|
|
138
|
+
`${r.by}@${r.byVersion} wants ${r.wantedRange}, found ${found}${r.suffix}`,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
for (const [peer, rec, where] of pnpmGroup(raw, 'missing', at)) {
|
|
142
|
+
const r = pnpmRecord(rec, where);
|
|
143
|
+
add(
|
|
144
|
+
{ importer, peer, kind: 'missing', by: r.by },
|
|
145
|
+
`${r.by}@${r.byVersion} wants ${r.wantedRange}, none installed${r.suffix}`,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
const conflicts = raw.conflicts;
|
|
149
|
+
if (!Array.isArray(conflicts) || !conflicts.every(nonEmpty)) {
|
|
150
|
+
throw new ShapeError(`${at}: "conflicts" is not an array of package names`);
|
|
151
|
+
}
|
|
152
|
+
for (const peer of conflicts) {
|
|
153
|
+
add({ importer, peer, kind: 'conflict' }, 'no version satisfies every range');
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return sortIssues([...seen.values()]);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const firstLine = (text: string): string | undefined =>
|
|
160
|
+
text
|
|
161
|
+
.split('\n')
|
|
162
|
+
.map((l) => l.trim())
|
|
163
|
+
.find((l) => l !== '');
|
|
164
|
+
|
|
165
|
+
// Сбой запуска, сигнал, код кроме 0 и 1, не JSON или не та форма — unavailable, и чистым это
|
|
166
|
+
// не считается никогда.
|
|
167
|
+
export function peersOutcome(run: PeersRun): PeersOutcome {
|
|
168
|
+
if ('error' in run) return { unavailable: `pnpm peers check did not start: ${run.error}` };
|
|
169
|
+
if (run.signal !== null) return { unavailable: `pnpm peers check killed by ${run.signal}` };
|
|
170
|
+
if (run.status !== 0 && run.status !== 1) {
|
|
171
|
+
const line = firstLine(run.stderr);
|
|
172
|
+
const tail = line === undefined ? '' : `: ${line}`;
|
|
173
|
+
return { unavailable: `pnpm peers check exited with ${run.status}${tail}` };
|
|
174
|
+
}
|
|
175
|
+
let json: unknown;
|
|
176
|
+
try {
|
|
177
|
+
json = JSON.parse(run.stdout);
|
|
178
|
+
} catch {
|
|
179
|
+
return { unavailable: 'pnpm peers check output is not JSON' };
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
return { issues: pnpmIssues(json) };
|
|
183
|
+
} catch (e) {
|
|
184
|
+
if (!(e instanceof ShapeError)) throw e;
|
|
185
|
+
return { unavailable: `pnpm peers check output has an unexpected shape: ${e.message}` };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Запись baseline из JSON: ровно ключи своего kind, все значения — непустые строки. Число ключей
|
|
190
|
+
// вместе с обязательными полями исключает лишние. Ключи собираются заново в порядке peerKey.
|
|
191
|
+
function baselineEntry(raw: unknown): PeerEntry | undefined {
|
|
192
|
+
if (!isObject(raw)) return undefined;
|
|
193
|
+
const size = Object.keys(raw).length;
|
|
194
|
+
const { importer, peer, kind, by, found } = raw;
|
|
195
|
+
if (!nonEmpty(importer) || !nonEmpty(peer)) return undefined;
|
|
196
|
+
if (kind === 'conflict' && size === 3) return { importer, peer, kind };
|
|
197
|
+
if (!nonEmpty(by)) return undefined;
|
|
198
|
+
if (kind === 'missing' && size === 4) return { importer, peer, kind, by };
|
|
199
|
+
if (kind === 'unmet' && size === 5 && nonEmpty(found)) return { importer, peer, kind, by, found };
|
|
200
|
+
return undefined;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Формат файла: { "version": 1, "peers": [<PeerEntry>…] }, оба ключа обязательны, других нет.
|
|
204
|
+
// Порядок записей при чтении не проверяется, повтор записи — проблема.
|
|
205
|
+
export function parsePeersBaseline(text: string): { entries: PeerEntry[] } | { problem: string } {
|
|
206
|
+
let raw: unknown;
|
|
207
|
+
try {
|
|
208
|
+
raw = JSON.parse(text);
|
|
209
|
+
} catch (e) {
|
|
210
|
+
return { problem: `not JSON: ${e instanceof Error ? e.message : String(e)}` };
|
|
211
|
+
}
|
|
212
|
+
if (!isObject(raw) || raw.version !== 1) return { problem: 'version must be 1' };
|
|
213
|
+
const unknownKey = Object.keys(raw).find((k) => k !== 'version' && k !== 'peers');
|
|
214
|
+
if (unknownKey !== undefined) return { problem: `unknown field «${unknownKey}»` };
|
|
215
|
+
if (!Array.isArray(raw.peers)) return { problem: '"peers" must be an array' };
|
|
216
|
+
const entries: PeerEntry[] = [];
|
|
217
|
+
const keys = new Set<string>();
|
|
218
|
+
for (const [i, item] of raw.peers.entries()) {
|
|
219
|
+
const entry = baselineEntry(item);
|
|
220
|
+
if (entry === undefined) return { problem: `peers[${i}] is not a valid entry` };
|
|
221
|
+
const k = peerKey(entry);
|
|
222
|
+
if (keys.has(k)) return { problem: `peers[${i}] repeats an earlier entry` };
|
|
223
|
+
keys.add(k);
|
|
224
|
+
entries.push(entry);
|
|
225
|
+
}
|
|
226
|
+
return { entries };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Поля записи в порядке ключа, лишние свойства не пишутся.
|
|
230
|
+
function plainEntry(e: PeerEntry): PeerEntry {
|
|
231
|
+
switch (e.kind) {
|
|
232
|
+
case 'unmet':
|
|
233
|
+
return { importer: e.importer, peer: e.peer, kind: e.kind, by: e.by, found: e.found };
|
|
234
|
+
case 'missing':
|
|
235
|
+
return { importer: e.importer, peer: e.peer, kind: e.kind, by: e.by };
|
|
236
|
+
case 'conflict':
|
|
237
|
+
return { importer: e.importer, peer: e.peer, kind: e.kind };
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Записи по ключу, перевод строки в конце. Отступ — таб, а два пробела, если ими отступает
|
|
242
|
+
// прежний текст файла.
|
|
243
|
+
export function serializePeersBaseline(entries: readonly PeerEntry[], previous?: string): string {
|
|
244
|
+
const indent = previous !== undefined && /^ {2}/m.test(previous) ? ' ' : '\t';
|
|
245
|
+
const peers = sortEntries(entries).map(plainEntry);
|
|
246
|
+
return `${JSON.stringify({ version: 1, peers }, null, indent)}\n`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export function comparePeers(
|
|
250
|
+
current: readonly PeerIssue[],
|
|
251
|
+
baseline: readonly PeerEntry[],
|
|
252
|
+
): { added: PeerIssue[]; stale: PeerEntry[] } {
|
|
253
|
+
const recorded = new Set(baseline.map(peerKey));
|
|
254
|
+
const now = new Set(current.map((i) => peerKey(i.entry)));
|
|
255
|
+
return {
|
|
256
|
+
added: sortIssues(current.filter((i) => !recorded.has(peerKey(i.entry)))),
|
|
257
|
+
stale: sortEntries(baseline.filter((e) => !now.has(peerKey(e)))),
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Baseline ∩ текущие: исправленное уходит, новое не добавляется.
|
|
262
|
+
export function lowerPeersBaseline(
|
|
263
|
+
baseline: readonly PeerEntry[],
|
|
264
|
+
current: readonly PeerIssue[],
|
|
265
|
+
): PeerEntry[] {
|
|
266
|
+
const now = new Set(current.map((i) => peerKey(i.entry)));
|
|
267
|
+
return sortEntries(baseline.filter((e) => now.has(peerKey(e))));
|
|
268
|
+
}
|
package/src/repo.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { type Document, parseDocument } from 'yaml';
|
|
|
7
7
|
|
|
8
8
|
import type { Canon } from './canon.ts';
|
|
9
9
|
import type { Finding } from './findings.ts';
|
|
10
|
+
import { parsePeersBaseline, type PeerEntry, PEERS_BASELINE } from './peers.ts';
|
|
10
11
|
|
|
11
12
|
// package.json в этих каталогах не читаются: чужой или собранный файл — не предмет проверки.
|
|
12
13
|
export const SKIP = /node_modules|\.worktrees|\.moon\/cache|(^|\/)(dist|build)\//;
|
|
@@ -40,6 +41,9 @@ export const MOON_WORKSPACES = [MOON_WORKSPACE, '.moon/workspace.yaml'];
|
|
|
40
41
|
|
|
41
42
|
export const DEPENDABOT_CONFIGS = ['.github/dependabot.yml', '.github/dependabot.yaml'];
|
|
42
43
|
|
|
44
|
+
// Лок pnpm: правилу peers нужен только как существующий путь, его читает сам pnpm.
|
|
45
|
+
export const LOCKFILE = 'pnpm-lock.yaml';
|
|
46
|
+
|
|
43
47
|
// Репозиторий потребителя как значение: правила получают его и не читают диск сами.
|
|
44
48
|
export interface Repo {
|
|
45
49
|
/** Содержимое прочитанных файлов; нечитаемый (каталог, нет прав) в files не попадает — его существование в paths. */
|
|
@@ -58,7 +62,9 @@ export interface Repo {
|
|
|
58
62
|
moonWorkspace?: Record<string, unknown>;
|
|
59
63
|
/** Путь moon workspace, который прочитан первым из MOON_WORKSPACES; есть, когда файл есть (и разобрался, и нет). */
|
|
60
64
|
moonWorkspacePath?: string;
|
|
61
|
-
/**
|
|
65
|
+
/** Разобранный PEERS_BASELINE; нет поля — файла нет или он не разобрался. */
|
|
66
|
+
peersBaseline?: PeerEntry[];
|
|
67
|
+
/** Ровно одна находка unreadable-file на каждый неразобранный package.json, pnpm-workspace.yaml, первый конфиг Renovate, MOON_TOOLCHAINS, найденный из MOON_WORKSPACES и PEERS_BASELINE. */
|
|
62
68
|
unreadable: Finding[];
|
|
63
69
|
}
|
|
64
70
|
|
|
@@ -88,7 +94,8 @@ export type Snapshot = ReadonlyMap<string, Read>;
|
|
|
88
94
|
// Чистая часть: из снимка строит Repo. Здесь единственная классификация unreadable-file: сбой чтения и
|
|
89
95
|
// сбой разбора одной роли — одна находка. Разбираемые роли: package.json (корневой всегда; вложенные —
|
|
90
96
|
// только при pnpm-workspace.yaml среди путей), pnpm-workspace.yaml и первый из RENOVATE_CONFIGS среди
|
|
91
|
-
// путей (нечитаемый заслоняет остальные), MOON_TOOLCHAINS
|
|
97
|
+
// путей (нечитаемый заслоняет остальные), MOON_TOOLCHAINS, найденный из MOON_WORKSPACES и PEERS_BASELINE.
|
|
98
|
+
// Остальные пути (среди них LOCKFILE) — только в paths, находки не дают.
|
|
92
99
|
// Порядок unreadable: по rank, равные — в порядке снимка.
|
|
93
100
|
export function repoFromSnapshot(snapshot: Snapshot): Repo {
|
|
94
101
|
const files = new Map<string, string>();
|
|
@@ -196,6 +203,16 @@ export function repoFromSnapshot(snapshot: Snapshot): Repo {
|
|
|
196
203
|
}
|
|
197
204
|
}
|
|
198
205
|
}
|
|
206
|
+
// Неразобранный baseline не становится пустым: поля нет, и правило peers не сравнивает.
|
|
207
|
+
let peersBaseline: PeerEntry[] | undefined;
|
|
208
|
+
const peersRead = snapshot.get(PEERS_BASELINE);
|
|
209
|
+
if (peersRead !== undefined && 'failed' in peersRead) {
|
|
210
|
+
unparsable(PEERS_BASELINE, peersRead.failed.message);
|
|
211
|
+
} else if (peersRead !== undefined && 'text' in peersRead) {
|
|
212
|
+
const parsed = parsePeersBaseline(peersRead.text);
|
|
213
|
+
if ('problem' in parsed) unparsable(PEERS_BASELINE, parsed.problem);
|
|
214
|
+
else peersBaseline = parsed.entries;
|
|
215
|
+
}
|
|
199
216
|
unreadable.sort((a, b) => rank(a) - rank(b));
|
|
200
217
|
return {
|
|
201
218
|
files,
|
|
@@ -207,6 +224,7 @@ export function repoFromSnapshot(snapshot: Snapshot): Repo {
|
|
|
207
224
|
...(moonToolchains && { moonToolchains }),
|
|
208
225
|
...(moonWorkspace && { moonWorkspace }),
|
|
209
226
|
...(moonWorkspacePath !== undefined && { moonWorkspacePath }),
|
|
227
|
+
...(peersBaseline !== undefined && { peersBaseline }),
|
|
210
228
|
};
|
|
211
229
|
}
|
|
212
230
|
|
|
@@ -225,15 +243,22 @@ function readFile(root: string, path: string): Read {
|
|
|
225
243
|
}
|
|
226
244
|
|
|
227
245
|
// Адаптер диска, без классификации: dest и satisfiedBy канон-файлов, конфиги Renovate и dependabot,
|
|
228
|
-
// MOON_TOOLCHAINS, MOON_WORKSPACES, pnpm-workspace.yaml, корневой package.json;
|
|
229
|
-
// ещё вложенные package.json без SKIP.
|
|
246
|
+
// MOON_TOOLCHAINS, MOON_WORKSPACES, PEERS_BASELINE, LOCKFILE, pnpm-workspace.yaml, корневой package.json;
|
|
247
|
+
// если pnpm-workspace.yaml есть (текст или сбой чтения) — ещё вложенные package.json без SKIP.
|
|
230
248
|
export function readSnapshot(root: string, canon: Canon): Snapshot {
|
|
231
249
|
const candidates = new Set<string>(['package.json', WORKSPACE_FILE]);
|
|
232
250
|
for (const f of canon.files) {
|
|
233
251
|
candidates.add(f.dest);
|
|
234
252
|
for (const p of f.satisfiedBy ?? []) candidates.add(p);
|
|
235
253
|
}
|
|
236
|
-
for (const p of [
|
|
254
|
+
for (const p of [
|
|
255
|
+
...RENOVATE_CONFIGS,
|
|
256
|
+
...DEPENDABOT_CONFIGS,
|
|
257
|
+
MOON_TOOLCHAINS,
|
|
258
|
+
...MOON_WORKSPACES,
|
|
259
|
+
PEERS_BASELINE,
|
|
260
|
+
LOCKFILE,
|
|
261
|
+
])
|
|
237
262
|
candidates.add(p);
|
|
238
263
|
const snapshot = new Map<string, Read>();
|
|
239
264
|
for (const p of candidates) snapshot.set(p, readFile(root, p));
|
|
@@ -248,7 +273,7 @@ export function readSnapshot(root: string, canon: Canon): Snapshot {
|
|
|
248
273
|
|
|
249
274
|
// Verbatim канон-файл сравнивается по содержимому, поэтому нечитаемый (например, каталог) для правила
|
|
250
275
|
// отсутствует: file-missing, затем sync падает с EISDIR — громко, намеренно. Create-if-absent
|
|
251
|
-
// dest/satisfiedBy
|
|
276
|
+
// dest/satisfiedBy, конфиги dependabot и LOCKFILE нужны правилам только как существующие пути.
|
|
252
277
|
export function loadRepo(root: string, canon: Canon): Repo {
|
|
253
278
|
return repoFromSnapshot(readSnapshot(root, canon));
|
|
254
279
|
}
|
package/src/sync-pr.ts
CHANGED
|
@@ -5,6 +5,8 @@ import { join } from 'node:path';
|
|
|
5
5
|
import { loadCanon } from './canon.ts';
|
|
6
6
|
import { syncOutput, syncRepo } from './check.ts';
|
|
7
7
|
import { readStackConfig, StackConfigError } from './config.ts';
|
|
8
|
+
import type { PeersReader } from './peers.ts';
|
|
9
|
+
import { peersBaseline } from './peers-baseline.ts';
|
|
8
10
|
import { type Registry, type WaitOptions, waitVisible } from './registry.ts';
|
|
9
11
|
|
|
10
12
|
export interface NewPr {
|
|
@@ -274,6 +276,7 @@ export interface SyncPrPorts {
|
|
|
274
276
|
github: GitHub;
|
|
275
277
|
registry: Registry;
|
|
276
278
|
print: Print;
|
|
279
|
+
peers: PeersReader;
|
|
277
280
|
}
|
|
278
281
|
|
|
279
282
|
// Как ATTEMPTS/INTERVAL шага ожидания в sync.yml.
|
|
@@ -339,6 +342,13 @@ export async function syncPr(opts: SyncPrOptions, ports: SyncPrPorts): Promise<0
|
|
|
339
342
|
if (opts.install) step('pnpm', ['install', '--no-frozen-lockfile']);
|
|
340
343
|
if (hook) step('pnpm', ['run', 'stack:post-sync'], { VERSION: version });
|
|
341
344
|
|
|
345
|
+
// Новый лок мог исправить записи baseline группы peers: они уходят в тот же коммит, иначе CI
|
|
346
|
+
// sync-PR краснел бы на stale-peer-baseline. Новые записи не добавляются, а код не меняет итог:
|
|
347
|
+
// и новые записи, и сбой pnpm покажет stack check в CI sync-PR. Группу проверяет peersBaseline.
|
|
348
|
+
const peers = peersBaseline(repoRoot, canon, 'drop-fixed', ports.peers);
|
|
349
|
+
for (const line of peers.out) print('out', line);
|
|
350
|
+
for (const line of peers.err) print('err', `sync-pr: peers baseline: ${line}`);
|
|
351
|
+
|
|
342
352
|
return await publishChanges(opts, ports.github, print);
|
|
343
353
|
} catch (error) {
|
|
344
354
|
print('err', `sync-pr: ${message(error)}`);
|