@alxwlw/stack 1.8.0 → 1.9.1
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 +23 -23
- package/canon/files/moon-tasks/stack-infra.yml +22 -0
- package/canon/files/moon-tasks/stack.yml +11 -4
- package/canon/files/prototools +6 -6
- package/canon/manifest.json +8 -1
- package/package.json +2 -1
- package/src/apply.ts +67 -0
- package/src/canon.ts +66 -42
- package/src/catalogs.ts +12 -24
- package/src/check.ts +49 -31
- package/src/cli.ts +6 -7
- package/src/config.ts +5 -23
- package/src/deps.ts +30 -80
- package/src/exceptions.ts +109 -0
- package/src/files.ts +12 -21
- package/src/findings.ts +34 -54
- package/src/moon-toolchains.ts +20 -0
- package/src/package-manager.ts +6 -24
- package/src/repo.ts +213 -0
package/canon/catalogs.json
CHANGED
|
@@ -1,48 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"dev": {
|
|
3
3
|
"typescript": "7.0.2",
|
|
4
|
-
"oxlint": "1.
|
|
5
|
-
"oxlint-tsgolint": "7.0.
|
|
6
|
-
"oxfmt": "0.
|
|
7
|
-
"@types/node": "26.6.
|
|
8
|
-
"@types/bun": "1.4.
|
|
9
|
-
"knip": "6.
|
|
10
|
-
"dependency-cruiser": "18.
|
|
11
|
-
"vitest": "
|
|
4
|
+
"oxlint": "1.90.0",
|
|
5
|
+
"oxlint-tsgolint": "7.0.2005",
|
|
6
|
+
"oxfmt": "0.75.0",
|
|
7
|
+
"@types/node": "26.6.6",
|
|
8
|
+
"@types/bun": "1.4.4",
|
|
9
|
+
"knip": "6.44.1",
|
|
10
|
+
"dependency-cruiser": "18.7.1",
|
|
11
|
+
"vitest": "5.1.0",
|
|
12
12
|
"@playwright/test": "1.64.1",
|
|
13
|
-
"@alxwlw/stack": "1.
|
|
14
|
-
"@alxwlw/oxlint-config": "1.
|
|
15
|
-
"@alxwlw/tsconfig": "1.
|
|
13
|
+
"@alxwlw/stack": "1.9.1",
|
|
14
|
+
"@alxwlw/oxlint-config": "1.9.1",
|
|
15
|
+
"@alxwlw/tsconfig": "1.9.1"
|
|
16
16
|
},
|
|
17
17
|
"libs": {
|
|
18
|
-
"@nestjs/core": "12.2
|
|
19
|
-
"@nestjs/common": "12.2
|
|
20
|
-
"@nestjs/platform-express": "12.2
|
|
21
|
-
"@nestjs/testing": "12.2
|
|
18
|
+
"@nestjs/core": "12.3.2",
|
|
19
|
+
"@nestjs/common": "12.3.2",
|
|
20
|
+
"@nestjs/platform-express": "12.3.2",
|
|
21
|
+
"@nestjs/testing": "12.3.2",
|
|
22
22
|
"reflect-metadata": "0.2.2",
|
|
23
23
|
"rxjs": "7.8.2",
|
|
24
24
|
"@prisma/client": "7.10.1",
|
|
25
25
|
"prisma": "7.10.1",
|
|
26
26
|
"pg": "8.23.1",
|
|
27
27
|
"@types/pg": "8.23.1",
|
|
28
|
-
"ioredis": "
|
|
28
|
+
"ioredis": "6.0.0",
|
|
29
29
|
"@nats-io/jetstream": "3.4.0",
|
|
30
30
|
"@nats-io/nats-core": "3.4.0",
|
|
31
|
-
"@opentelemetry/api": "1.
|
|
32
|
-
"@opentelemetry/sdk-metrics": "
|
|
31
|
+
"@opentelemetry/api": "1.10.0",
|
|
32
|
+
"@opentelemetry/sdk-metrics": "3.0.0",
|
|
33
33
|
"zod": "4.6.7",
|
|
34
34
|
"react": "19.3.1",
|
|
35
35
|
"react-dom": "19.3.1",
|
|
36
36
|
"@types/react": "19.3.0",
|
|
37
37
|
"@types/react-dom": "19.3.0",
|
|
38
|
-
"react-router": "8.
|
|
39
|
-
"@tanstack/react-query": "5.
|
|
40
|
-
"@tanstack/react-table": "
|
|
41
|
-
"zustand": "5.0.
|
|
38
|
+
"react-router": "8.5.1",
|
|
39
|
+
"@tanstack/react-query": "5.105.2",
|
|
40
|
+
"@tanstack/react-table": "9.3.1",
|
|
41
|
+
"zustand": "5.0.16",
|
|
42
42
|
"@dnd-kit/core": "6.3.1",
|
|
43
43
|
"tailwindcss": "4.3.3",
|
|
44
44
|
"@tailwindcss/vite": "4.3.3",
|
|
45
|
-
"lucide-react": "1.
|
|
45
|
+
"lucide-react": "1.66.0",
|
|
46
46
|
"@fontsource/ibm-plex-sans": "5.3.0",
|
|
47
47
|
"@fontsource/ibm-plex-mono": "5.3.0",
|
|
48
48
|
"@fontsource/ibm-plex-serif": "5.3.0"
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
$schema: 'https://moonrepo.dev/schemas/tasks.json'
|
|
2
|
+
|
|
3
|
+
# Canon template (seeded once via --with=moon-tasks; repo-owned afterwards).
|
|
4
|
+
# `stack check` reads .stack.jsonc; no git hook is imposed — wire this task
|
|
5
|
+
# into your own pre-commit/CI as you see fit.
|
|
6
|
+
#
|
|
7
|
+
# Every project inherits this task, and .stack.jsonc lives at the workspace root:
|
|
8
|
+
# the task runs from the root, with workspace-relative inputs. An infra repo has
|
|
9
|
+
# no package.json, so `bunx` fetches @alxwlw/stack (bun is pinned in .prototools)
|
|
10
|
+
# and asks the registry for a newer version once a day.
|
|
11
|
+
# `moon run <project>:stack-check` checks the repo once; `moon run :stack-check`
|
|
12
|
+
# repeats the same check for every project.
|
|
13
|
+
|
|
14
|
+
tasks:
|
|
15
|
+
stack-check:
|
|
16
|
+
command: 'bunx @alxwlw/stack check'
|
|
17
|
+
inputs:
|
|
18
|
+
- '/.stack.jsonc'
|
|
19
|
+
- '/.prototools'
|
|
20
|
+
options:
|
|
21
|
+
cache: false
|
|
22
|
+
runFromWorkspaceRoot: true
|
|
@@ -3,13 +3,20 @@ $schema: 'https://moonrepo.dev/schemas/tasks.json'
|
|
|
3
3
|
# Canon template (seeded once via --with=moon-tasks; repo-owned afterwards).
|
|
4
4
|
# `stack check` reads .stack.jsonc; no git hook is imposed — wire this task
|
|
5
5
|
# into your own pre-commit/CI as you see fit.
|
|
6
|
+
#
|
|
7
|
+
# Every project inherits this task, and .stack.jsonc lives at the workspace root:
|
|
8
|
+
# the task runs from the root, through `pnpm exec` (a project without package.json
|
|
9
|
+
# has no node_modules/.bin on its PATH), with workspace-relative inputs.
|
|
10
|
+
# `moon run <project>:stack-check` checks the repo once; `moon run :stack-check`
|
|
11
|
+
# repeats the same check for every project.
|
|
6
12
|
|
|
7
13
|
tasks:
|
|
8
14
|
stack-check:
|
|
9
|
-
command: 'stack check'
|
|
15
|
+
command: 'pnpm exec stack check'
|
|
10
16
|
inputs:
|
|
11
|
-
- '
|
|
12
|
-
- '
|
|
13
|
-
- 'pnpm-workspace.yaml'
|
|
17
|
+
- '/.stack.jsonc'
|
|
18
|
+
- '/.prototools'
|
|
19
|
+
- '/pnpm-workspace.yaml'
|
|
14
20
|
options:
|
|
15
21
|
cache: false
|
|
22
|
+
runFromWorkspaceRoot: true
|
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.63.
|
|
3
|
-
node = "26.
|
|
4
|
-
pnpm = "12.
|
|
5
|
-
bun = "1.4.
|
|
6
|
-
moon = "2.6.
|
|
7
|
-
uv = "0.13.
|
|
2
|
+
proto = "0.63.2"
|
|
3
|
+
node = "26.13.0"
|
|
4
|
+
pnpm = "12.16.1"
|
|
5
|
+
bun = "1.4.4"
|
|
6
|
+
moon = "2.6.5"
|
|
7
|
+
uv = "0.13.6"
|
|
8
8
|
|
|
9
9
|
# Guardrail binaries: versions pinned for reproducibility.
|
|
10
10
|
actionlint = "1.7.12"
|
package/canon/manifest.json
CHANGED
|
@@ -113,7 +113,14 @@
|
|
|
113
113
|
{
|
|
114
114
|
"src": "files/moon-tasks/stack.yml",
|
|
115
115
|
"dest": ".moon/tasks/stack.yml",
|
|
116
|
-
"appliesTo": ["node", "contracts"
|
|
116
|
+
"appliesTo": ["node", "contracts"],
|
|
117
|
+
"strategy": "create-if-absent",
|
|
118
|
+
"group": "moon-tasks"
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
"src": "files/moon-tasks/stack-infra.yml",
|
|
122
|
+
"dest": ".moon/tasks/stack.yml",
|
|
123
|
+
"appliesTo": ["infra"],
|
|
117
124
|
"strategy": "create-if-absent",
|
|
118
125
|
"group": "moon-tasks"
|
|
119
126
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alxwlw/stack",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
"files": [
|
|
13
13
|
"src",
|
|
14
14
|
"!src/**/*.test.ts",
|
|
15
|
+
"!src/testkit.ts",
|
|
15
16
|
"canon",
|
|
16
17
|
"schema.json"
|
|
17
18
|
],
|
package/src/apply.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { applyEdits, modify } from 'jsonc-parser';
|
|
5
|
+
import { parseDocument } from 'yaml';
|
|
6
|
+
|
|
7
|
+
import type { Change } from './findings.ts';
|
|
8
|
+
|
|
9
|
+
function renderFile(file: string, current: string | undefined, changes: Change[]): string {
|
|
10
|
+
// Список по файлу не бывает пустым: правки группирует renderChanges.
|
|
11
|
+
const first = changes[0] as Change;
|
|
12
|
+
if (changes.some((c) => c.kind !== first.kind)) {
|
|
13
|
+
throw new Error(`conflicting changes for ${file}`);
|
|
14
|
+
}
|
|
15
|
+
if (first.kind === 'write') {
|
|
16
|
+
// Несколько write в один файл: побеждает последний (дубликат dest ловит canon.test.ts).
|
|
17
|
+
let content = '';
|
|
18
|
+
for (const c of changes) if (c.kind === 'write') content = c.content;
|
|
19
|
+
return content;
|
|
20
|
+
}
|
|
21
|
+
if (first.kind === 'yaml-set') {
|
|
22
|
+
const doc = parseDocument(current ?? '');
|
|
23
|
+
for (const c of changes) {
|
|
24
|
+
// setIn создаёт недостающие узлы и не трогает соседей и их комментарии.
|
|
25
|
+
if (c.kind === 'yaml-set') doc.setIn(c.path, c.value);
|
|
26
|
+
}
|
|
27
|
+
// singleQuote: oxfmt (canon .oxfmtrc.jsonc) formats YAML with singleQuote:true, and
|
|
28
|
+
// pnpm-workspace.yaml's own pre-existing catalogs already use single quotes for scoped names.
|
|
29
|
+
// New scoped-package keys (@foo/bar isn't a plain-scalar-safe start char) default to
|
|
30
|
+
// double quotes otherwise, so a freshly-synced workspace fails `oxfmt --check`.
|
|
31
|
+
// lineWidth: 0 — без переноса: по умолчанию yaml режет скаляры длиннее 80 колонок во
|
|
32
|
+
// всём документе, и sync переписал бы строки, к каталогам не относящиеся.
|
|
33
|
+
return doc.toString({ singleQuote: true, lineWidth: 0 });
|
|
34
|
+
}
|
|
35
|
+
let text = current ?? '';
|
|
36
|
+
for (const c of changes) {
|
|
37
|
+
// modify+applyEdits меняет только значение поля: отступы и порядок ключей остаются.
|
|
38
|
+
if (c.kind === 'json-set') text = applyEdits(text, modify(text, c.path, c.value, {}));
|
|
39
|
+
}
|
|
40
|
+
return text;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Чистая часть: текущее содержимое (undefined — файла нет) + правки → итог по одному на файл.
|
|
44
|
+
export function renderChanges(
|
|
45
|
+
current: ReadonlyMap<string, string | undefined>,
|
|
46
|
+
changes: readonly Change[],
|
|
47
|
+
): Map<string, string> {
|
|
48
|
+
const byFile = new Map<string, Change[]>();
|
|
49
|
+
for (const c of changes) byFile.set(c.file, [...(byFile.get(c.file) ?? []), c]);
|
|
50
|
+
const out = new Map<string, string>();
|
|
51
|
+
for (const [file, list] of byFile) out.set(file, renderFile(file, current.get(file), list));
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Текущее содержимое берётся из снимка репозитория (нет ключа — нет файла), диск не читается;
|
|
56
|
+
// не больше одной записи на файл.
|
|
57
|
+
export function applyChanges(
|
|
58
|
+
root: string,
|
|
59
|
+
changes: readonly Change[],
|
|
60
|
+
current: ReadonlyMap<string, string>,
|
|
61
|
+
): void {
|
|
62
|
+
for (const [file, content] of renderChanges(current, changes)) {
|
|
63
|
+
const target = join(root, file);
|
|
64
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
65
|
+
writeFileSync(target, content);
|
|
66
|
+
}
|
|
67
|
+
}
|
package/src/canon.ts
CHANGED
|
@@ -24,33 +24,22 @@ export type CanonCatalogs = Record<string, Record<string, string>>;
|
|
|
24
24
|
export interface Canon {
|
|
25
25
|
files: { dest: string; content: string; strategy?: SyncStrategy; satisfiedBy?: string[] }[];
|
|
26
26
|
catalogs: CanonCatalogs;
|
|
27
|
-
|
|
28
|
-
pnpmPin: string;
|
|
27
|
+
pins: Pins;
|
|
29
28
|
}
|
|
30
29
|
|
|
30
|
+
// Пины инструментов из .prototools канона: node и pnpm обязательны, прочие строки верхнего уровня допустимы.
|
|
31
|
+
export type Pins = {
|
|
32
|
+
readonly node: string;
|
|
33
|
+
readonly pnpm: string;
|
|
34
|
+
readonly [tool: string]: string;
|
|
35
|
+
};
|
|
36
|
+
|
|
31
37
|
export function canonDir(): string {
|
|
32
38
|
return join(dirname(fileURLToPath(import.meta.url)), '..', 'canon');
|
|
33
39
|
}
|
|
34
40
|
|
|
35
|
-
export function loadManifest(dir: string = canonDir()): CanonFile[] {
|
|
36
|
-
const raw = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')) as {
|
|
37
|
-
files: CanonFile[];
|
|
38
|
-
};
|
|
39
|
-
return raw.files;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export function filesFor(cfg: StackConfig, dir: string = canonDir()): CanonFile[] {
|
|
43
|
-
return loadManifest(dir).filter(
|
|
44
|
-
(f) => f.appliesTo.includes(cfg.profile) && (f.group == null || cfg.with.includes(f.group)),
|
|
45
|
-
);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export function loadCatalogs(dir: string = canonDir()): CanonCatalogs {
|
|
49
|
-
return JSON.parse(readFileSync(join(dir, 'catalogs.json'), 'utf8')) as CanonCatalogs;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
41
|
// Устаревшие группы принимаются ради старых .stack.jsonc и ничего не включают.
|
|
53
|
-
|
|
42
|
+
const DEPRECATED_GROUPS: readonly string[] = ['renovate'];
|
|
54
43
|
|
|
55
44
|
export interface CanonGroups {
|
|
56
45
|
files: string[];
|
|
@@ -58,15 +47,35 @@ export interface CanonGroups {
|
|
|
58
47
|
deprecated: readonly string[];
|
|
59
48
|
}
|
|
60
49
|
|
|
61
|
-
//
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
50
|
+
// canon/ как значение: все записи манифеста с содержимым, каталоги и имена групп. Читается один раз;
|
|
51
|
+
// выбор под профиль и with — чистый шаг canonFor.
|
|
52
|
+
export interface CanonSource {
|
|
53
|
+
entries: readonly (CanonFile & { content: string })[];
|
|
54
|
+
catalogs: CanonCatalogs;
|
|
55
|
+
groups: CanonGroups;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Единственное место, где canon/ читается с диска: manifest.json и catalogs.json по разу, каждый src по разу.
|
|
59
|
+
// Имена групп: файловые — поле group манифеста, каталожные — ключи catalogs.json кроме dev.
|
|
60
|
+
export function readCanonSource(dir: string = canonDir()): CanonSource {
|
|
61
|
+
const manifest = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')) as {
|
|
62
|
+
files: CanonFile[];
|
|
63
|
+
};
|
|
64
|
+
const catalogs = JSON.parse(readFileSync(join(dir, 'catalogs.json'), 'utf8')) as CanonCatalogs;
|
|
65
|
+
const entries = manifest.files.map((f) => ({
|
|
66
|
+
...f,
|
|
67
|
+
content: readFileSync(join(dir, f.src), 'utf8'),
|
|
68
|
+
}));
|
|
69
|
+
const groups: CanonGroups = {
|
|
70
|
+
files: [...new Set(entries.flatMap((f) => (f.group == null ? [] : [f.group])))],
|
|
71
|
+
catalogs: Object.keys(catalogs).filter((g) => g !== 'dev'),
|
|
72
|
+
deprecated: DEPRECATED_GROUPS,
|
|
73
|
+
};
|
|
74
|
+
return { entries, catalogs, groups };
|
|
66
75
|
}
|
|
67
76
|
|
|
68
|
-
export function assertKnownGroups(groups: readonly string[],
|
|
69
|
-
const g =
|
|
77
|
+
export function assertKnownGroups(groups: readonly string[], source: CanonSource): void {
|
|
78
|
+
const g = source.groups;
|
|
70
79
|
const known = [...g.files, ...g.catalogs, ...g.deprecated].sort();
|
|
71
80
|
for (const name of groups) {
|
|
72
81
|
if (!known.includes(name)) {
|
|
@@ -77,15 +86,24 @@ export function assertKnownGroups(groups: readonly string[], dir: string = canon
|
|
|
77
86
|
}
|
|
78
87
|
}
|
|
79
88
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
89
|
+
// Единственный предикат выбора: запись приходит в канон профиля, если профиль в appliesTo, а группа
|
|
90
|
+
// (если есть) включена через with. Им же пользуются гварды тестов, у которых нет права на свою копию.
|
|
91
|
+
export function selectEntries(source: CanonSource, cfg: StackConfig): CanonSource['entries'] {
|
|
92
|
+
return source.entries.filter(
|
|
93
|
+
(f) => f.appliesTo.includes(cfg.profile) && (f.group == null || cfg.with.includes(f.group)),
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Чистый шаг от источника к Canon: проверка групп, выбор записей, каталоги, пины. Диск не трогает.
|
|
98
|
+
export function canonFor(source: CanonSource, cfg: StackConfig): Canon {
|
|
99
|
+
assertKnownGroups(cfg.with, source);
|
|
100
|
+
const files = selectEntries(source, cfg).map((f) => ({
|
|
83
101
|
dest: f.dest,
|
|
84
|
-
content:
|
|
102
|
+
content: f.content,
|
|
85
103
|
strategy: f.strategy,
|
|
86
104
|
satisfiedBy: f.satisfiedBy,
|
|
87
105
|
}));
|
|
88
|
-
const all =
|
|
106
|
+
const all = source.catalogs;
|
|
89
107
|
const groups = ['dev', ...cfg.with];
|
|
90
108
|
const catalogs = Object.fromEntries(
|
|
91
109
|
groups.filter((g) => g in all).map((g) => [g, all[g] as Record<string, string>]),
|
|
@@ -96,15 +114,21 @@ export function loadCanon(cfg: StackConfig, dir: string = canonDir()): Canon {
|
|
|
96
114
|
if (!prototools) {
|
|
97
115
|
throw new Error('canon manifest has no .prototools entry for profile ' + cfg.profile);
|
|
98
116
|
}
|
|
99
|
-
const
|
|
100
|
-
if (!
|
|
117
|
+
const { node, pnpm, ...rest } = parsePins(prototools.content);
|
|
118
|
+
if (!node) throw new Error('canon .prototools has no node pin');
|
|
101
119
|
// Пин pnpm нужен правилу package-manager: поле packageManager — второй источник версии pnpm.
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
120
|
+
if (!pnpm) throw new Error('canon .prototools has no pnpm pin');
|
|
121
|
+
return { files, catalogs, pins: { ...rest, node, pnpm } };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function loadCanon(cfg: StackConfig, dir: string = canonDir()): Canon {
|
|
125
|
+
return canonFor(readCanonSource(dir), cfg);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Строковые значения верхнего уровня .prototools; таблица [plugins] и нестроковые значения — не пины.
|
|
129
|
+
function parsePins(prototools: string): Record<string, string> {
|
|
130
|
+
const parsed = Bun.TOML.parse(prototools) as Record<string, unknown>;
|
|
131
|
+
return Object.fromEntries(
|
|
132
|
+
Object.entries(parsed).filter((e): e is [string, string] => typeof e[1] === 'string'),
|
|
133
|
+
);
|
|
110
134
|
}
|
package/src/catalogs.ts
CHANGED
|
@@ -1,12 +1,6 @@
|
|
|
1
|
-
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
|
|
4
|
-
import { parseDocument } from 'yaml';
|
|
5
|
-
|
|
6
1
|
import type { Canon } from './canon.ts';
|
|
7
2
|
import type { Drift } from './findings.ts';
|
|
8
|
-
|
|
9
|
-
const WORKSPACE_FILE = 'pnpm-workspace.yaml';
|
|
3
|
+
import { type Repo, WORKSPACE_FILE } from './repo.ts';
|
|
10
4
|
|
|
11
5
|
// doc.getIn() возвращает unknown: скаляр (обычный случай) или узел yaml-коллекции,
|
|
12
6
|
// если запись каталога сломана (не скаляр). String() на объекте даёт "[object Object]" —
|
|
@@ -19,10 +13,10 @@ function displayValue(v: unknown): string {
|
|
|
19
13
|
}
|
|
20
14
|
|
|
21
15
|
// Один проход и один предикат для check и sync — см. planFiles.
|
|
22
|
-
export function planCatalogs(
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
16
|
+
export function planCatalogs(repo: Repo, canon: Canon): Drift[] {
|
|
17
|
+
// Документа нет: файла нет или он не разобрался (находка — в repo.unreadable).
|
|
18
|
+
const doc = repo.workspace;
|
|
19
|
+
if (doc === undefined) return [];
|
|
26
20
|
const plan: Drift[] = [];
|
|
27
21
|
for (const [group, entries] of Object.entries(canon.catalogs)) {
|
|
28
22
|
for (const [name, version] of Object.entries(entries)) {
|
|
@@ -37,20 +31,14 @@ export function planCatalogs(repoRoot: string, canon: Canon): Drift[] {
|
|
|
37
31
|
from == null
|
|
38
32
|
? `catalog entry missing: expected ${version}`
|
|
39
33
|
: `${from} instead of ${version}`,
|
|
40
|
-
|
|
34
|
+
catalog: group,
|
|
35
|
+
name,
|
|
41
36
|
fix: `catalog ${group}.${name}: ${from ?? '—'} → ${version}`,
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
// New scoped-package keys (@foo/bar isn't a plain-scalar-safe start char) default to
|
|
48
|
-
// double quotes otherwise, so a freshly-synced workspace fails `oxfmt --check`.
|
|
49
|
-
// ponytail: doc общий на весь план, файл пишется на каждую запись; один flush в
|
|
50
|
-
// конце, если ~40 записей первого sync станут заметны.
|
|
51
|
-
// lineWidth: 0 — без переноса: по умолчанию yaml режет скаляры длиннее 80 колонок во
|
|
52
|
-
// всём документе, и sync переписал бы строки, к каталогам не относящиеся.
|
|
53
|
-
writeFileSync(path, doc.toString({ singleQuote: true, lineWidth: 0 }));
|
|
37
|
+
change: {
|
|
38
|
+
kind: 'yaml-set',
|
|
39
|
+
file: WORKSPACE_FILE,
|
|
40
|
+
path: ['catalogs', group, name],
|
|
41
|
+
value: version,
|
|
54
42
|
},
|
|
55
43
|
});
|
|
56
44
|
}
|
package/src/check.ts
CHANGED
|
@@ -1,56 +1,74 @@
|
|
|
1
|
+
import { applyChanges } from './apply.ts';
|
|
1
2
|
import type { Canon } from './canon.ts';
|
|
2
3
|
import { planCatalogs } from './catalogs.ts';
|
|
3
|
-
import type { Exception } from './config.ts';
|
|
4
4
|
import {
|
|
5
5
|
checkDependabot,
|
|
6
6
|
checkEnginesNode,
|
|
7
7
|
checkInlineVersions,
|
|
8
8
|
checkRenovatePreset,
|
|
9
9
|
} from './deps.ts';
|
|
10
|
+
import { type Exception, type Held, isHeld, resolve } from './exceptions.ts';
|
|
10
11
|
import { planFiles } from './files.ts';
|
|
11
|
-
import {
|
|
12
|
+
import type { Drift, Finding } from './findings.ts';
|
|
13
|
+
import { checkMoonToolchains } from './moon-toolchains.ts';
|
|
12
14
|
import { planPackageManager } from './package-manager.ts';
|
|
15
|
+
import { loadRepo, type Repo } from './repo.ts';
|
|
13
16
|
|
|
14
17
|
// План дрейфа: всё, что sync умеет закрыть, в порядке применения — файлы, каталоги, packageManager.
|
|
15
|
-
export function
|
|
18
|
+
export function plan(repo: Repo, canon: Canon): Drift[] {
|
|
16
19
|
return [
|
|
17
|
-
...planFiles(
|
|
18
|
-
...planCatalogs(
|
|
19
|
-
...planPackageManager(
|
|
20
|
+
...planFiles(repo, canon),
|
|
21
|
+
...planCatalogs(repo, canon),
|
|
22
|
+
...planPackageManager(repo, canon),
|
|
20
23
|
];
|
|
21
24
|
}
|
|
22
25
|
|
|
26
|
+
// Находки в порядке: план, нечитаемые файлы загрузчика, правила «только отчёт» из deps.ts; затем
|
|
27
|
+
// протухшие исключения. Все они проходят через исключения.
|
|
28
|
+
export function check(repo: Repo, canon: Canon, exceptions: Exception[]): Finding[] {
|
|
29
|
+
const r = resolve(
|
|
30
|
+
[
|
|
31
|
+
...plan(repo, canon),
|
|
32
|
+
...repo.unreadable,
|
|
33
|
+
...checkInlineVersions(repo, canon),
|
|
34
|
+
...checkEnginesNode(repo, canon),
|
|
35
|
+
...checkRenovatePreset(repo),
|
|
36
|
+
...checkDependabot(repo),
|
|
37
|
+
...checkMoonToolchains(repo, canon),
|
|
38
|
+
],
|
|
39
|
+
exceptions,
|
|
40
|
+
);
|
|
41
|
+
return [...r.findings, ...r.stale];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function planRepo(repoRoot: string, canon: Canon): Drift[] {
|
|
45
|
+
return plan(loadRepo(repoRoot, canon), canon);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function checkRepo(repoRoot: string, canon: Canon, exceptions: Exception[]): Finding[] {
|
|
49
|
+
return check(loadRepo(repoRoot, canon), canon, exceptions);
|
|
50
|
+
}
|
|
51
|
+
|
|
23
52
|
export interface SyncResult {
|
|
24
53
|
applied: Drift[];
|
|
25
|
-
held:
|
|
54
|
+
held: Held<Drift>[];
|
|
26
55
|
}
|
|
27
56
|
|
|
28
|
-
// sync — тот же план, но удержанное исключением не
|
|
29
|
-
//
|
|
57
|
+
// sync — тот же план, но удержанное исключением не применяется (почему — см. resolve):
|
|
58
|
+
// исключение держит и check, и sync, сопоставление у них одно. Диск читается один раз, загрузчиком:
|
|
59
|
+
// применитель берёт текущее содержимое из того же снимка.
|
|
30
60
|
export function syncRepo(repoRoot: string, canon: Canon, exceptions: Exception[]): SyncResult {
|
|
61
|
+
const repo = loadRepo(repoRoot, canon);
|
|
31
62
|
const result: SyncResult = { applied: [], held: [] };
|
|
32
|
-
for (const d of
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
result.held.push({ ...d, suppressedBy: e });
|
|
36
|
-
continue;
|
|
37
|
-
}
|
|
38
|
-
d.apply();
|
|
39
|
-
result.applied.push(d);
|
|
63
|
+
for (const d of resolve(plan(repo, canon), exceptions).findings) {
|
|
64
|
+
if (isHeld(d)) result.held.push(d);
|
|
65
|
+
else result.applied.push(d);
|
|
40
66
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
return applyExceptions(
|
|
47
|
-
[
|
|
48
|
-
...planRepo(repoRoot, canon),
|
|
49
|
-
...checkInlineVersions(repoRoot, canon),
|
|
50
|
-
...checkEnginesNode(repoRoot, canon),
|
|
51
|
-
...checkRenovatePreset(repoRoot),
|
|
52
|
-
...checkDependabot(repoRoot),
|
|
53
|
-
],
|
|
54
|
-
exceptions,
|
|
67
|
+
// Правки собираются по файлу: применитель пишет файл не больше одного раза.
|
|
68
|
+
applyChanges(
|
|
69
|
+
repoRoot,
|
|
70
|
+
result.applied.map((d) => d.change),
|
|
71
|
+
repo.files,
|
|
55
72
|
);
|
|
73
|
+
return result;
|
|
56
74
|
}
|
package/src/cli.ts
CHANGED
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
import { existsSync } from 'node:fs';
|
|
3
3
|
import { parseArgs } from 'node:util';
|
|
4
4
|
|
|
5
|
-
import { assertKnownGroups, loadCanon } from './canon.ts';
|
|
5
|
+
import { assertKnownGroups, loadCanon, readCanonSource } from './canon.ts';
|
|
6
6
|
import { checkRepo, syncRepo } from './check.ts';
|
|
7
7
|
import { type Profile, PROFILES, readStackConfig, StackConfigError } from './config.ts';
|
|
8
|
+
import { allowedLine, isHeld } from './exceptions.ts';
|
|
8
9
|
import { type Finding, isDrift } from './findings.ts';
|
|
9
10
|
import { initConfig } from './init.ts';
|
|
10
11
|
|
|
@@ -54,24 +55,22 @@ try {
|
|
|
54
55
|
if (!PROFILES.includes(profile as Profile)) {
|
|
55
56
|
fail(`unknown --profile "${profile}", expected one of: ${PROFILES.join(', ')}`);
|
|
56
57
|
}
|
|
57
|
-
assertKnownGroups(values.with ?? []);
|
|
58
|
+
assertKnownGroups(values.with ?? [], readCanonSource());
|
|
58
59
|
const path = initConfig(repoRoot, { profile: profile as Profile, with: values.with ?? [] });
|
|
59
60
|
console.log(`created ${path}`);
|
|
60
61
|
} else if (command === 'sync') {
|
|
61
62
|
const cfg = readStackConfig(repoRoot);
|
|
62
63
|
const { applied, held } = syncRepo(repoRoot, loadCanon(cfg), cfg.exceptions);
|
|
63
64
|
for (const f of held) {
|
|
64
|
-
console.warn(
|
|
65
|
+
console.warn(allowedLine(f));
|
|
65
66
|
}
|
|
66
67
|
for (const d of applied) console.log(d.fix);
|
|
67
68
|
console.log(`canon ${applied.length === 0 ? 'already up to date' : 'applied'}`);
|
|
68
69
|
} else if (command === 'check') {
|
|
69
70
|
const cfg = readStackConfig(repoRoot);
|
|
70
71
|
const findings = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions);
|
|
71
|
-
const blocking = findings.filter((f) => !f
|
|
72
|
-
for (const f of findings.filter(
|
|
73
|
-
console.warn(`allowed (${f.suppressedBy?.reason}): ${f.target} — ${f.message}`);
|
|
74
|
-
}
|
|
72
|
+
const blocking = findings.filter((f) => !isHeld(f));
|
|
73
|
+
for (const f of findings.filter(isHeld)) console.warn(allowedLine(f));
|
|
75
74
|
for (const f of blocking) console.error(`${f.code}: ${f.target} — ${f.message}`);
|
|
76
75
|
if (blocking.length) {
|
|
77
76
|
console.error(`\n${fixHint(blocking)}`);
|
package/src/config.ts
CHANGED
|
@@ -3,17 +3,12 @@ import { join } from 'node:path';
|
|
|
3
3
|
|
|
4
4
|
import { parse as parseJsonc, type ParseError } from 'jsonc-parser';
|
|
5
5
|
|
|
6
|
+
import { type Exception, exceptionProblem } from './exceptions.ts';
|
|
7
|
+
|
|
6
8
|
export const STACK_CONFIG_FILE = '.stack.jsonc';
|
|
7
9
|
export const PROFILES = ['node', 'contracts', 'infra'] as const;
|
|
8
10
|
export type Profile = (typeof PROFILES)[number];
|
|
9
11
|
|
|
10
|
-
export interface Exception {
|
|
11
|
-
file?: string;
|
|
12
|
-
catalog?: string;
|
|
13
|
-
name?: string;
|
|
14
|
-
reason: string;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
12
|
export interface StackConfig {
|
|
18
13
|
profile: Profile;
|
|
19
14
|
with: string[];
|
|
@@ -49,22 +44,9 @@ export function readStackConfig(repoRoot: string): StackConfig {
|
|
|
49
44
|
const exceptions = raw.exceptions ?? [];
|
|
50
45
|
if (!Array.isArray(exceptions))
|
|
51
46
|
throw new StackConfigError(`${STACK_CONFIG_FILE}: "exceptions" must be an array`);
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
// null/undefined, даже когда тип обещает Exception; проверяем честно, не полагаясь на "as".
|
|
56
|
-
for (const e of exceptions as (Exception | null | undefined)[]) {
|
|
57
|
-
if (e == null || !e.reason)
|
|
58
|
-
throw new StackConfigError(
|
|
59
|
-
`${STACK_CONFIG_FILE}: exception is missing "reason": ${JSON.stringify(e)}`,
|
|
60
|
-
);
|
|
61
|
-
const isFileOnly = nonEmpty(e.file) && !present(e.catalog) && !present(e.name);
|
|
62
|
-
const isEntryOnly = nonEmpty(e.catalog) && nonEmpty(e.name) && !present(e.file);
|
|
63
|
-
if (!isFileOnly && !isEntryOnly) {
|
|
64
|
-
throw new StackConfigError(
|
|
65
|
-
`${STACK_CONFIG_FILE}: an exception must address either "file" or a "catalog"+"name" pair: ${JSON.stringify(e)}`,
|
|
66
|
-
);
|
|
67
|
-
}
|
|
47
|
+
for (const e of exceptions) {
|
|
48
|
+
const problem = exceptionProblem(e);
|
|
49
|
+
if (problem) throw new StackConfigError(`${STACK_CONFIG_FILE}: ${problem}`);
|
|
68
50
|
}
|
|
69
51
|
return { profile: profile as Profile, with: groups, exceptions };
|
|
70
52
|
}
|