changeguard 0.0.0-stage → 0.7.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 (69) hide show
  1. package/CHANGELOG.md +440 -0
  2. package/LICENSE +202 -0
  3. package/LICENSE-PROPRIETARY +94 -0
  4. package/README.md +317 -2
  5. package/SECURITY.md +40 -0
  6. package/data/changes/openai.seed.json +87 -0
  7. package/data/changes/shopify.seed.json +42 -0
  8. package/data/changes/stripe.seed.json +60 -0
  9. package/data/changes/supabase.seed.json +56 -0
  10. package/data/changes/twilio.seed.json +63 -0
  11. package/data/openapi/openai/meta.json +9 -0
  12. package/data/openapi/openai/new.json +24 -0
  13. package/data/openapi/openai/old.json +68 -0
  14. package/data/providers/openai.json +60 -0
  15. package/data/providers/shopify.json +52 -0
  16. package/data/providers/stripe.json +57 -0
  17. package/data/providers/supabase.json +56 -0
  18. package/data/providers/twilio.json +57 -0
  19. package/dist/analyze/go-analyzer.js +343 -0
  20. package/dist/analyze/index.js +77 -0
  21. package/dist/analyze/js-analyzer.js +380 -0
  22. package/dist/analyze/parser.js +78 -0
  23. package/dist/analyze/py-analyzer.js +313 -0
  24. package/dist/analyze/rules.js +1 -0
  25. package/dist/analyze/ts-utils.js +62 -0
  26. package/dist/cli.js +335 -0
  27. package/dist/codemod/apply.js +159 -0
  28. package/dist/config.js +121 -0
  29. package/dist/deps/manifests.js +145 -0
  30. package/dist/github/api.js +136 -0
  31. package/dist/github/auth.js +54 -0
  32. package/dist/impact/engine.js +384 -0
  33. package/dist/ingest/canonical.js +52 -0
  34. package/dist/ingest/changelog-html.js +63 -0
  35. package/dist/ingest/feed-client.js +99 -0
  36. package/dist/ingest/feed-keys.js +198 -0
  37. package/dist/ingest/feed.js +178 -0
  38. package/dist/ingest/github-releases.js +59 -0
  39. package/dist/ingest/note-parser.js +274 -0
  40. package/dist/ingest/openapi-diff.js +217 -0
  41. package/dist/ingest/store.js +181 -0
  42. package/dist/llm/explanation.js +273 -0
  43. package/dist/mcp/format.js +116 -0
  44. package/dist/mcp/index.js +29 -0
  45. package/dist/mcp/protocol.js +36 -0
  46. package/dist/mcp/server.js +110 -0
  47. package/dist/mcp/standalone.js +12 -0
  48. package/dist/mcp/tools.js +189 -0
  49. package/dist/notify/index.js +174 -0
  50. package/dist/providers/registry.js +215 -0
  51. package/dist/report/html.js +194 -0
  52. package/dist/report/markdown.js +90 -0
  53. package/dist/report/pr-draft.js +37 -0
  54. package/dist/scan.js +168 -0
  55. package/dist/source/repo-source.js +100 -0
  56. package/dist/types.js +6 -0
  57. package/dist/util/http.js +40 -0
  58. package/dist/util/logger.js +61 -0
  59. package/dist/util/metrics.js +99 -0
  60. package/dist/util/request-context.js +22 -0
  61. package/dist/util/task-queue.js +69 -0
  62. package/dist/util/versions.js +52 -0
  63. package/fixtures/sample-repo/cmd/billing/main.go +47 -0
  64. package/fixtures/sample-repo/go.mod +12 -0
  65. package/fixtures/sample-repo/package.json +17 -0
  66. package/fixtures/sample-repo/requirements.txt +7 -0
  67. package/fixtures/sample-repo/services/ai.py +65 -0
  68. package/fixtures/sample-repo/src/billing.ts +68 -0
  69. package/package.json +84 -4
@@ -0,0 +1,189 @@
1
+ /**
2
+ * The three MCP tools — the only place that touches business logic.
3
+ *
4
+ * All three are READ-ONLY by contract: no persistence (persist:false), no
5
+ * file writes, no network (online:false), no codemods. Handlers are plain
6
+ * async functions so they can be unit-tested without stdio.
7
+ */
8
+ import { existsSync, statSync } from 'node:fs';
9
+ import { isAbsolute, resolve } from 'node:path';
10
+ import { collectChanges } from '../ingest/store.js';
11
+ import { loadVerifiedFeed } from '../ingest/feed-client.js';
12
+ import { PROVIDERS } from '../providers/registry.js';
13
+ import { scanRepository } from '../scan.js';
14
+ import { RPC_ERRORS, ToolError } from './protocol.js';
15
+ import { renderBreakingChanges, renderFeedStatusBuiltin, renderFeedStatusRejected, renderFeedStatusVerified, renderImpact, } from './format.js';
16
+ const PROVIDER_IDS = PROVIDERS.map((p) => p.id);
17
+ const DEFAULT_SINCE_DAYS = 365;
18
+ const SCAN_TIMEOUT_MS = 30_000;
19
+ function defaultSinceISO() {
20
+ return new Date(Date.now() - DEFAULT_SINCE_DAYS * 86_400_000).toISOString().slice(0, 10);
21
+ }
22
+ function sinceParam(args) {
23
+ const raw = args.since;
24
+ if (raw === undefined)
25
+ return defaultSinceISO();
26
+ if (typeof raw !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(raw)) {
27
+ throw new ToolError(RPC_ERRORS.invalidParams, 'since must be an ISO date string (YYYY-MM-DD)');
28
+ }
29
+ return raw;
30
+ }
31
+ function providerParam(args, required) {
32
+ const raw = args.provider;
33
+ if (raw === undefined) {
34
+ if (required)
35
+ throw new ToolError(RPC_ERRORS.invalidParams, 'provider is required');
36
+ return undefined;
37
+ }
38
+ if (typeof raw !== 'string' || !PROVIDER_IDS.includes(raw)) {
39
+ throw new ToolError(RPC_ERRORS.invalidParams, `provider must be one of: ${PROVIDER_IDS.join(', ')}`);
40
+ }
41
+ return raw;
42
+ }
43
+ /** repo_path: absolute, existing directory; optional allow-list via env. */
44
+ function repoPathParam(args) {
45
+ const raw = args.repo_path;
46
+ if (typeof raw !== 'string' || !raw.trim()) {
47
+ throw new ToolError(RPC_ERRORS.invalidParams, 'repo_path is required (absolute path)');
48
+ }
49
+ if (!isAbsolute(raw)) {
50
+ throw new ToolError(RPC_ERRORS.invalidParams, 'repo_path must be an absolute path');
51
+ }
52
+ const resolved = resolve(raw);
53
+ if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
54
+ throw new ToolError(RPC_ERRORS.invalidParams, `repo_path is not a directory: ${raw}`);
55
+ }
56
+ const allow = (process.env.CHANGEGUARD_MCP_ALLOWED_ROOTS ?? '')
57
+ .split(',')
58
+ .map((s) => s.trim())
59
+ .filter(Boolean)
60
+ .map((s) => resolve(s));
61
+ if (allow.length > 0 &&
62
+ !allow.some((root) => resolved === root ||
63
+ resolved.startsWith(`${root}${'\\'}`) ||
64
+ resolved.startsWith(`${root}/`))) {
65
+ throw new ToolError(RPC_ERRORS.invalidParams, `repo_path is outside CHANGEGUARD_MCP_ALLOWED_ROOTS (${allow.join(', ')})`);
66
+ }
67
+ return resolved;
68
+ }
69
+ function withTimeout(promise, ms, label) {
70
+ return new Promise((res, rej) => {
71
+ const timer = setTimeout(() => rej(new ToolError(RPC_ERRORS.internal, `${label} exceeded ${ms / 1000}s; narrow the scope with a smaller repo or a later since`)), ms);
72
+ timer.unref?.();
73
+ promise.then((v) => {
74
+ clearTimeout(timer);
75
+ res(v);
76
+ }, (e) => {
77
+ clearTimeout(timer);
78
+ rej(e);
79
+ });
80
+ });
81
+ }
82
+ function define(name, description, inputSchema) {
83
+ return { name, description, inputSchema };
84
+ }
85
+ export function buildTools() {
86
+ return [
87
+ {
88
+ definition: define('list_breaking_changes', 'List recorded breaking API/SDK changes for one provider within a time window. ' +
89
+ 'Use before writing integration code with that vendor, or when the user asks what changed recently.', {
90
+ type: 'object',
91
+ properties: {
92
+ provider: {
93
+ type: 'string',
94
+ enum: PROVIDER_IDS,
95
+ description: 'Vendor to inspect',
96
+ },
97
+ since: {
98
+ type: 'string',
99
+ description: 'ISO date (YYYY-MM-DD); default: one year ago',
100
+ },
101
+ },
102
+ required: ['provider'],
103
+ additionalProperties: false,
104
+ }),
105
+ handler: async (args) => {
106
+ const provider = providerParam(args, true);
107
+ const since = sinceParam(args);
108
+ const records = await collectChanges({
109
+ online: false,
110
+ sinceISO: since,
111
+ providers: [provider],
112
+ });
113
+ const breaking = records.filter((r) => r.kind === 'breaking');
114
+ return renderBreakingChanges(provider, since, breaking);
115
+ },
116
+ },
117
+ {
118
+ definition: define('check_impact', 'Check whether a repository is affected by recorded breaking changes. ' +
119
+ 'Returns concrete file:line positions with rule ids and evidence. ' +
120
+ 'READ-ONLY: scans the working tree without modifying anything.', {
121
+ type: 'object',
122
+ properties: {
123
+ repo_path: {
124
+ type: 'string',
125
+ description: 'Absolute path to the project root',
126
+ },
127
+ provider: {
128
+ type: 'string',
129
+ enum: PROVIDER_IDS,
130
+ description: 'Limit the check to one vendor (default: all detected)',
131
+ },
132
+ since: {
133
+ type: 'string',
134
+ description: 'ISO date (YYYY-MM-DD); default: one year ago',
135
+ },
136
+ },
137
+ required: ['repo_path'],
138
+ additionalProperties: false,
139
+ }),
140
+ handler: async (args) => {
141
+ const repoPath = repoPathParam(args);
142
+ const provider = providerParam(args, false);
143
+ const since = sinceParam(args);
144
+ const report = await withTimeout(scanRepository({
145
+ repoPath,
146
+ sinceISO: since,
147
+ online: false,
148
+ persist: false,
149
+ onlyMatched: true,
150
+ providers: provider ? [provider] : undefined,
151
+ }), SCAN_TIMEOUT_MS, 'scan');
152
+ return renderImpact(report);
153
+ },
154
+ },
155
+ {
156
+ definition: define('get_feed_status', 'Report the provenance and trust status of the change database this server uses: ' +
157
+ 'whether the data is a verified signed feed or the bundled offline snapshot. ' +
158
+ 'Call this before citing any answer as authoritative.', {
159
+ type: 'object',
160
+ properties: {},
161
+ additionalProperties: false,
162
+ }),
163
+ handler: async () => {
164
+ const feedPath = (process.env.CHANGEGUARD_MCP_FEED ?? '').trim();
165
+ if (feedPath) {
166
+ const outcome = await loadVerifiedFeed({
167
+ path: feedPath,
168
+ trustedKeys: process.env.CHANGEGUARD_FEED_KEYS,
169
+ });
170
+ if (outcome.ok) {
171
+ return renderFeedStatusVerified({
172
+ kid: outcome.kid,
173
+ rootKid: outcome.rootKid,
174
+ records: outcome.payload.records.length,
175
+ generatedAt: outcome.payload.generatedAt,
176
+ sourceKind: outcome.sourceKind,
177
+ keySource: outcome.keySource,
178
+ });
179
+ }
180
+ return renderFeedStatusRejected(outcome.reason, outcome.detail);
181
+ }
182
+ // Count the whole bundled database, not a time window — a windowed
183
+ // count reads as "0 records" whenever the curated snapshot predates it.
184
+ const all = await collectChanges({ online: false, sinceISO: '2000-01-01' });
185
+ return renderFeedStatusBuiltin(all.length);
186
+ },
187
+ },
188
+ ];
189
+ }
@@ -0,0 +1,174 @@
1
+ import { connect as tlsConnect } from 'node:tls';
2
+ import { config } from '../config.js';
3
+ import { fetchText } from '../util/http.js';
4
+ import { logger } from '../util/logger.js';
5
+ import { renderMarkdown } from '../report/markdown.js';
6
+ import { GitHubClient } from '../github/api.js';
7
+ export async function notifySlack(webhookUrl, report) {
8
+ const s = report.summary;
9
+ const lines = [
10
+ `*ChangeGuard 变更哨兵 — ${report.repoName}*`,
11
+ `🔴 高风险 ${s.high} · 🟡 中 ${s.medium} · ⚪ 低 ${s.low} · 文件 ${s.filesAffected}`,
12
+ ];
13
+ const high = report.findings.filter((f) => f.severity === 'high').slice(0, 10);
14
+ for (const f of high) {
15
+ lines.push(`• [${f.providerId}] ${f.change.title} — ${f.file ?? 'repo'}:${f.line ?? ''}`);
16
+ }
17
+ if (report.findings.length > high.length)
18
+ lines.push(`…另有 ${report.findings.length - high.length} 项`);
19
+ await fetchText(webhookUrl, {
20
+ method: 'POST',
21
+ body: JSON.stringify({ text: lines.join('\n') }),
22
+ headers: { 'content-type': 'application/json' },
23
+ });
24
+ }
25
+ /**
26
+ * Minimal SMTPS client (implicit TLS, port 465) with AUTH LOGIN.
27
+ * Enough for transaction providers (SendGrid/Mailgun/SES SMTP/Gmail).
28
+ */
29
+ export async function sendEmail(to, subject, body, smtpUrl = config.smtpUrl) {
30
+ if (!smtpUrl)
31
+ throw new Error('SMTP_URL is not configured (expected smtps://user:pass@host:465)');
32
+ const url = new URL(smtpUrl);
33
+ if (url.protocol !== 'smtps:')
34
+ throw new Error(`unsupported mail protocol: ${url.protocol}`);
35
+ const user = decodeURIComponent(url.username);
36
+ const pass = decodeURIComponent(url.password);
37
+ const from = user;
38
+ const port = Number(url.port || 465);
39
+ const socket = tlsConnect({ host: url.hostname, port, servername: url.hostname });
40
+ try {
41
+ await eventOnce(socket, 'secureConnect');
42
+ await expectCode(socket, 220);
43
+ await cmd(socket, `EHLO changeguard`, 250);
44
+ await cmd(socket, 'AUTH LOGIN', 334);
45
+ await cmd(socket, Buffer.from(user).toString('base64'), 334);
46
+ await cmd(socket, Buffer.from(pass).toString('base64'), 235);
47
+ await cmd(socket, `MAIL FROM:<${from}>`, 250);
48
+ for (const rcpt of to)
49
+ await cmd(socket, `RCPT TO:<${rcpt}>`, 250);
50
+ await cmd(socket, 'DATA', 354);
51
+ const message = [
52
+ `From: ChangeGuard <${from}>`,
53
+ `To: ${to.join(', ')}`,
54
+ `Subject: =?utf-8?B?${Buffer.from(subject).toString('base64')}?=`,
55
+ 'MIME-Version: 1.0',
56
+ 'Content-Type: text/plain; charset=utf-8',
57
+ 'Content-Transfer-Encoding: 8bit',
58
+ '',
59
+ body,
60
+ '.',
61
+ ].join('\r\n');
62
+ await cmd(socket, message, 250);
63
+ await cmd(socket, 'QUIT', 221).catch(() => undefined);
64
+ }
65
+ finally {
66
+ socket.destroy();
67
+ }
68
+ }
69
+ function eventOnce(emitter, event) {
70
+ return new Promise((resolve, reject) => {
71
+ emitter.once(event, () => resolve());
72
+ emitter.once('error', reject);
73
+ });
74
+ }
75
+ function readReply(socket) {
76
+ return new Promise((resolve, reject) => {
77
+ const onData = (chunk) => {
78
+ const text = chunk.toString();
79
+ const lines = text.trim().split(/\r?\n/);
80
+ const last = lines[lines.length - 1] ?? '';
81
+ if (/^\d{3}\s/.test(last)) {
82
+ socket.off('data', onData);
83
+ socket.off('error', onErr);
84
+ resolve(last);
85
+ }
86
+ };
87
+ const onErr = (err) => reject(err);
88
+ socket.on('data', onData);
89
+ socket.on('error', onErr);
90
+ });
91
+ }
92
+ async function expectCode(socket, code) {
93
+ const reply = await readReply(socket);
94
+ if (!reply.startsWith(String(code)))
95
+ throw new Error(`SMTP expected ${code}, got: ${reply}`);
96
+ return reply;
97
+ }
98
+ async function cmd(socket, text, code) {
99
+ socket.write(`${text}\r\n`);
100
+ return expectCode(socket, code);
101
+ }
102
+ export async function notifyEmail(report) {
103
+ if (config.emailTo.length === 0)
104
+ throw new Error('EMAIL_TO is not configured');
105
+ const s = report.summary;
106
+ await sendEmail(config.emailTo, `[ChangeGuard] ${report.repoName}: ${s.high} high / ${s.medium} medium API changes`, renderMarkdown(report));
107
+ }
108
+ /**
109
+ * Stable short string derived from the findings set — used to distinguish
110
+ * "same repo same batch" from "same repo new batch" so we don't erroneously
111
+ * reuse an older issue that referenced a different breaking API change.
112
+ */
113
+ function findingsHash(report) {
114
+ const ids = report.findings
115
+ .map((f) => f.changeId)
116
+ .filter(Boolean)
117
+ .sort();
118
+ let hash = 0;
119
+ for (const id of ids) {
120
+ for (let i = 0; i < id.length; i++)
121
+ hash = (hash * 31 + id.charCodeAt(i)) | 0;
122
+ }
123
+ return Math.abs(hash).toString(36).padStart(6, '0');
124
+ }
125
+ /** Open (or reuse) a GitHub issue carrying the Markdown report.
126
+ *
127
+ * Marker is `<!-- changeguard:<repo>:<since>:<hash> -->`. The hash covers the
128
+ * change IDs — if a previous scan of the same repo produced a different
129
+ * findings batch we open a new issue instead of silently appending to an
130
+ * outdated one.
131
+ */
132
+ export async function notifyGitHubIssue(report, target) {
133
+ const client = await GitHubClient.forInstallation(target.installationId);
134
+ const marker = `<!-- changeguard:${report.repoName}:${report.since ?? 'all'}:${findingsHash(report)} -->`;
135
+ const open = await client.get(`/repos/${target.owner}/${target.repo}/issues?state=open&per_page=50`);
136
+ const existing = open.find((i) => i.body?.includes(marker));
137
+ if (existing) {
138
+ logger.info(`GitHub issue #${existing.number} already exists for ${target.owner}/${target.repo}`);
139
+ return { number: existing.number, html_url: existing.html_url };
140
+ }
141
+ const s = report.summary;
142
+ return client.createIssue(target.owner, target.repo, {
143
+ title: `ChangeGuard: ${s.high} high / ${s.medium} medium breaking API changes detected`,
144
+ body: `${marker}\n\n${renderMarkdown(report)}`,
145
+ labels: ['changeguard', 'dependencies'],
146
+ });
147
+ }
148
+ /** Fire every configured channel; collect failures as logs, never throw. */
149
+ export async function dispatchNotifications(report, issueTarget) {
150
+ if (config.slackWebhookUrl) {
151
+ try {
152
+ await notifySlack(config.slackWebhookUrl, report);
153
+ }
154
+ catch (err) {
155
+ logger.warn(`Slack notification failed: ${err.message}`);
156
+ }
157
+ }
158
+ if (config.smtpUrl && config.emailTo.length) {
159
+ try {
160
+ await notifyEmail(report);
161
+ }
162
+ catch (err) {
163
+ logger.warn(`Email notification failed: ${err.message}`);
164
+ }
165
+ }
166
+ if (issueTarget) {
167
+ try {
168
+ await notifyGitHubIssue(report, issueTarget);
169
+ }
170
+ catch (err) {
171
+ logger.warn(`GitHub issue failed: ${err.message}`);
172
+ }
173
+ }
174
+ }
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Provider registry.
3
+ *
4
+ * Vendors are pure data: each provider is a JSON manifest in
5
+ * `data/providers/<id>.json`, loaded and strictly validated at startup.
6
+ * Adding a vendor is therefore a data change — a new manifest (plus optional
7
+ * `data/changes/<id>.seed.json` records for offline mode) — with no code
8
+ * changes. Malformed manifests fail fast at import time; the error names the
9
+ * offending file and field.
10
+ */
11
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
12
+ import { dirname, join } from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ const HERE = dirname(fileURLToPath(import.meta.url));
15
+ const DEFAULT_PROVIDER_DIR = join(HERE, '..', '..', 'data', 'providers');
16
+ const ECOSYSTEMS = new Set(['npm', 'pypi', 'go']);
17
+ const LANGUAGES = new Set(['javascript', 'python', 'go']);
18
+ const CHANGELOG_KINDS = new Set(['html', 'atom']);
19
+ function fail(source, message) {
20
+ throw new Error(`provider manifest ${source}: ${message}`);
21
+ }
22
+ function isStringArray(v) {
23
+ return Array.isArray(v) && v.every((x) => typeof x === 'string');
24
+ }
25
+ function isRecord(v) {
26
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
27
+ }
28
+ /** Structural validation of one manifest; returns the normalized config. */
29
+ export function validateProviderManifest(raw, source = 'manifest') {
30
+ if (!isRecord(raw))
31
+ fail(source, 'expected a JSON object');
32
+ if (typeof raw.id !== 'string' || !/^[a-z0-9][a-z0-9_-]*$/.test(raw.id)) {
33
+ fail(source, 'id must be a lowercase slug (a-z0-9, starting alphanumeric)');
34
+ }
35
+ if (typeof raw.name !== 'string' || !raw.name.trim())
36
+ fail(source, 'name must be a non-empty string');
37
+ if (typeof raw.website !== 'string' || !raw.website.trim()) {
38
+ fail(source, 'website must be a non-empty string');
39
+ }
40
+ if (!isRecord(raw.packages))
41
+ fail(source, 'packages must be an object');
42
+ const pkgEntries = Object.entries(raw.packages);
43
+ if (pkgEntries.length === 0)
44
+ fail(source, 'packages must declare at least one ecosystem');
45
+ for (const [eco, list] of pkgEntries) {
46
+ if (!ECOSYSTEMS.has(eco))
47
+ fail(source, `unsupported ecosystem "${eco}" (npm|pypi|go)`);
48
+ if (!isStringArray(list) || list.length === 0) {
49
+ fail(source, `packages.${eco} must be a non-empty string[]`);
50
+ }
51
+ }
52
+ if (raw.hosts !== undefined && !isStringArray(raw.hosts))
53
+ fail(source, 'hosts must be a string[]');
54
+ if (raw.factories !== undefined) {
55
+ if (!isRecord(raw.factories))
56
+ fail(source, 'factories must be an object');
57
+ for (const [lang, list] of Object.entries(raw.factories)) {
58
+ if (!LANGUAGES.has(lang))
59
+ fail(source, `unsupported factory language "${lang}" (javascript|python|go)`);
60
+ if (!isStringArray(list))
61
+ fail(source, `factories.${lang} must be a string[]`);
62
+ }
63
+ }
64
+ if (!isRecord(raw.sources))
65
+ fail(source, 'sources must be an object');
66
+ const sources = raw.sources;
67
+ if (!Array.isArray(sources.githubReleases)) {
68
+ fail(source, 'sources.githubReleases must be an array (may be empty)');
69
+ }
70
+ sources.githubReleases.forEach((rel, i) => {
71
+ if (!isRecord(rel))
72
+ fail(source, `sources.githubReleases[${i}] must be an object`);
73
+ if (!ECOSYSTEMS.has(String(rel.ecosystem))) {
74
+ fail(source, `sources.githubReleases[${i}].ecosystem must be npm|pypi|go`);
75
+ }
76
+ if (!LANGUAGES.has(String(rel.language))) {
77
+ fail(source, `sources.githubReleases[${i}].language must be javascript|python|go`);
78
+ }
79
+ if (typeof rel.owner !== 'string' || !rel.owner)
80
+ fail(source, `sources.githubReleases[${i}].owner required`);
81
+ if (typeof rel.repo !== 'string' || !rel.repo)
82
+ fail(source, `sources.githubReleases[${i}].repo required`);
83
+ });
84
+ if (sources.changelog !== undefined) {
85
+ const c = sources.changelog;
86
+ if (!isRecord(c))
87
+ fail(source, 'sources.changelog must be an object');
88
+ if (typeof c.url !== 'string' || !c.url)
89
+ fail(source, 'sources.changelog.url required');
90
+ if (!CHANGELOG_KINDS.has(String(c.kind)))
91
+ fail(source, 'sources.changelog.kind must be html|atom');
92
+ }
93
+ if (sources.openapiSpecs !== undefined) {
94
+ if (!Array.isArray(sources.openapiSpecs))
95
+ fail(source, 'sources.openapiSpecs must be an array');
96
+ sources.openapiSpecs.forEach((spec, i) => {
97
+ if (!isRecord(spec) || typeof spec.name !== 'string' || !spec.name) {
98
+ fail(source, `sources.openapiSpecs[${i}] must be an object with a name`);
99
+ }
100
+ });
101
+ }
102
+ return {
103
+ id: raw.id,
104
+ name: raw.name,
105
+ website: raw.website,
106
+ packages: raw.packages,
107
+ hosts: raw.hosts ?? [],
108
+ factories: raw.factories ?? {},
109
+ sources: sources,
110
+ };
111
+ }
112
+ /**
113
+ * Load and validate every `*.json` manifest in `dir` (defaults to
114
+ * `data/providers`). Files are processed in name order; the file stem must
115
+ * equal the manifest id, and ids must be unique. Throws with the file name
116
+ * and field on any defect (fail-fast — a typo must not silently disable a
117
+ * vendor).
118
+ */
119
+ export function loadProviderManifests(dir = DEFAULT_PROVIDER_DIR) {
120
+ if (!existsSync(dir)) {
121
+ throw new Error(`provider manifest directory missing: ${dir} — the package must ship data/providers/*.json`);
122
+ }
123
+ const files = readdirSync(dir)
124
+ .filter((f) => f.endsWith('.json'))
125
+ .sort();
126
+ if (files.length === 0)
127
+ throw new Error(`no provider manifests found in ${dir}`);
128
+ const providers = [];
129
+ const seen = new Set();
130
+ for (const file of files) {
131
+ let raw;
132
+ try {
133
+ raw = JSON.parse(readFileSync(join(dir, file), 'utf8'));
134
+ }
135
+ catch (err) {
136
+ fail(file, `not valid JSON: ${err.message}`);
137
+ }
138
+ const provider = validateProviderManifest(raw, file);
139
+ const stem = file.replace(/\.json$/, '');
140
+ if (provider.id !== stem)
141
+ fail(file, `file stem "${stem}" must equal provider id "${provider.id}"`);
142
+ if (seen.has(provider.id))
143
+ fail(file, `duplicate provider id "${provider.id}"`);
144
+ seen.add(provider.id);
145
+ providers.push(provider);
146
+ }
147
+ return providers;
148
+ }
149
+ export const PROVIDERS = loadProviderManifests();
150
+ export const PROVIDER_BY_ID = new Map(PROVIDERS.map((p) => [p.id, p]));
151
+ export function providerForPackage(ecosystem, name, providers = PROVIDERS) {
152
+ const needle = name.toLowerCase();
153
+ for (const p of providers) {
154
+ const list = p.packages[ecosystem];
155
+ if (!list)
156
+ continue;
157
+ // Compare case-insensitively on both sides: registry entries mix case for
158
+ // Go module paths (e.g. github.com/Shopify/go-shopify), and Go import
159
+ // paths are case-insensitive in practice (GitHub owner casing varies).
160
+ if (list.some((pkg) => {
161
+ const target = pkg.toLowerCase();
162
+ return needle === target || needle.startsWith(`${target}/`);
163
+ })) {
164
+ return p.id;
165
+ }
166
+ }
167
+ return undefined;
168
+ }
169
+ export function providerForHost(hostname, providers = PROVIDERS) {
170
+ const h = hostname.toLowerCase();
171
+ for (const p of providers) {
172
+ if (p.hosts.some((suffix) => h === suffix || h.endsWith(`.${suffix}`)))
173
+ return p.id;
174
+ }
175
+ return undefined;
176
+ }
177
+ /**
178
+ * Build the analyzer index. Rules are permissive on aliases because each
179
+ * analyzer resolves imports per-file and only activates a rule when the
180
+ * provider's package is actually imported in that file.
181
+ */
182
+ export function buildAnalyzerIndex(providers = PROVIDERS) {
183
+ const rules = {
184
+ javascript: [],
185
+ python: [],
186
+ go: [],
187
+ };
188
+ const hosts = [];
189
+ for (const p of providers) {
190
+ for (const suffix of p.hosts)
191
+ hosts.push({ suffix, providerId: p.id });
192
+ const js = p.packages.npm ?? [];
193
+ rules.javascript.push({
194
+ providerId: p.id,
195
+ packageName: js[0] ?? p.id,
196
+ roots: [p.id, ...(p.factories.javascript ?? [])],
197
+ factories: p.factories.javascript ?? [],
198
+ });
199
+ rules.python.push({
200
+ providerId: p.id,
201
+ packageName: (p.packages.pypi ?? [p.id])[0],
202
+ roots: [p.id, ...(p.factories.python ?? [])],
203
+ factories: p.factories.python ?? [],
204
+ });
205
+ const goPrefixes = p.packages.go ?? [];
206
+ rules.go.push({
207
+ providerId: p.id,
208
+ packageName: goPrefixes[0] ?? p.id,
209
+ roots: [p.id, ...(p.factories.go ?? [])],
210
+ factories: p.factories.go ?? [],
211
+ goModulePrefixes: goPrefixes,
212
+ });
213
+ }
214
+ return { rules, hosts };
215
+ }