-
Notifications
You must be signed in to change notification settings - Fork 432
Expand file tree
/
Copy pathcheck-package-age.js
More file actions
141 lines (127 loc) · 4.42 KB
/
Copy pathcheck-package-age.js
File metadata and controls
141 lines (127 loc) · 4.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#!/usr/bin/env node
/**
* check-package-age.js
*
* 工程化"发布满 15 天才允许采用"的硬约束。
*
* 用法:
* node scripts/check-package-age.js # 默认读 package.json,校验 dependencies + devDependencies
* node scripts/check-package-age.js react-native # 只校验单个包当前已锁定版本
* MIN_RELEASE_AGE_DAYS=20 node scripts/check-package-age.js # 临时覆盖阈值
*
* 接入位置(建议):
* 1. package.json 的 "scripts" 增加 "check:age": "node scripts/check-package-age.js"
* 2. package.json 的 "scripts" 增加 "preinstall": "node scripts/check-package-age.js || true"
* (首次接入用 || true 软告警;稳定后去掉 || true 变硬阻断)
* 3. CI(GitHub Actions / GitLab CI)在 npm install 前先跑 npm run check:age
*
* 退出码:
* 0 全部通过
* 1 至少有一个包不满足 ≥ 15 天
* 2 网络 / 解析错误(可由 CI 决定是否阻断)
*
* 备注:
* - 该脚本只读 package.json 中明确写出的版本(exact 或 ^/~),不解析 package-lock;
* 完整覆盖请配合 npm 11+ 的 `cooldown`/`minimumReleaseAge` 配置(见 .npmrc)。
* - 不依赖任何三方库,可在升级期内单独使用。
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const MIN_DAYS = Number(process.env.MIN_RELEASE_AGE_DAYS || 15);
const NOW = Date.now();
function loadPackageJson() {
const file = path.join(process.cwd(), 'package.json');
return JSON.parse(fs.readFileSync(file, 'utf-8'));
}
function resolveVersion(rangeOrUrl) {
if (!rangeOrUrl) return null;
if (rangeOrUrl.startsWith('git+') || rangeOrUrl.startsWith('http') || rangeOrUrl.includes('/')) {
return null;
}
return rangeOrUrl.replace(/^[\^~]/, '');
}
function fetchPublishTime(pkg, version) {
try {
const out = execSync(`npm view ${pkg}@${version} time.${version}`, {
stdio: ['ignore', 'pipe', 'ignore'],
})
.toString()
.trim();
if (!out) return null;
return new Date(out);
} catch (_e) {
try {
const fallback = execSync(`npm view ${pkg} time --json`, {
stdio: ['ignore', 'pipe', 'ignore'],
}).toString();
const obj = JSON.parse(fallback);
if (obj[version]) return new Date(obj[version]);
return null;
} catch (_e2) {
return null;
}
}
}
function check(pkg, version) {
const v = resolveVersion(version);
if (!v) {
return { pkg, version, status: 'skip', reason: 'non-semver source (git/url)' };
}
const publishedAt = fetchPublishTime(pkg, v);
if (!publishedAt) {
return { pkg, version: v, status: 'unknown', reason: 'cannot resolve publish time' };
}
const ageDays = (NOW - publishedAt.getTime()) / (1000 * 60 * 60 * 24);
return {
pkg,
version: v,
publishedAt: publishedAt.toISOString(),
ageDays: Math.round(ageDays * 10) / 10,
status: ageDays >= MIN_DAYS ? 'ok' : 'fail',
};
}
function main() {
const pkgJson = loadPackageJson();
const targets = process.argv.slice(2);
const entries = [];
if (targets.length > 0) {
for (const name of targets) {
const v =
(pkgJson.dependencies || {})[name] || (pkgJson.devDependencies || {})[name] || null;
if (!v) {
console.error(`[skip] ${name}: not in package.json`);
continue;
}
entries.push([name, v]);
}
} else {
Object.entries(pkgJson.dependencies || {}).forEach((kv) => entries.push(kv));
Object.entries(pkgJson.devDependencies || {}).forEach((kv) => entries.push(kv));
}
let failCount = 0;
let unknownCount = 0;
const rows = [];
for (const [name, range] of entries) {
const r = check(name, range);
rows.push(r);
if (r.status === 'fail') failCount += 1;
if (r.status === 'unknown') unknownCount += 1;
}
rows.sort((a, b) => {
const order = { fail: 0, unknown: 1, skip: 2, ok: 3 };
return order[a.status] - order[b.status];
});
for (const r of rows) {
const tag = r.status.toUpperCase().padEnd(7);
const age = r.ageDays != null ? `${r.ageDays}d` : '-';
console.log(`[${tag}] ${r.pkg}@${r.version} (age=${age})${r.reason ? ' ' + r.reason : ''}`);
}
console.log(
`\nSummary: ${rows.length} packages | fail=${failCount} | unknown=${unknownCount} | threshold=${MIN_DAYS}d`,
);
if (failCount > 0) process.exit(1);
if (unknownCount > 0 && process.env.STRICT === '1') process.exit(2);
process.exit(0);
}
main();