@scalar/release-notes 0.1.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.
Files changed (65) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +21 -0
  3. package/README.md +132 -0
  4. package/dist/cli.d.ts +4 -0
  5. package/dist/cli.d.ts.map +1 -0
  6. package/dist/cli.js +18 -0
  7. package/dist/commands/generate.d.ts +5 -0
  8. package/dist/commands/generate.d.ts.map +1 -0
  9. package/dist/commands/generate.js +105 -0
  10. package/dist/commands/sync-markdown.d.ts +5 -0
  11. package/dist/commands/sync-markdown.d.ts.map +1 -0
  12. package/dist/commands/sync-markdown.js +25 -0
  13. package/dist/config/define-config.d.ts +6 -0
  14. package/dist/config/define-config.d.ts.map +1 -0
  15. package/dist/config/define-config.js +4 -0
  16. package/dist/config/read-config.d.ts +18 -0
  17. package/dist/config/read-config.d.ts.map +1 -0
  18. package/dist/config/read-config.js +86 -0
  19. package/dist/config/types.d.ts +70 -0
  20. package/dist/config/types.d.ts.map +1 -0
  21. package/dist/config/types.js +1 -0
  22. package/dist/core/detect-versioned-changelog-paths.d.ts +5 -0
  23. package/dist/core/detect-versioned-changelog-paths.d.ts.map +1 -0
  24. package/dist/core/detect-versioned-changelog-paths.js +56 -0
  25. package/dist/core/extract-changelog-section.d.ts +5 -0
  26. package/dist/core/extract-changelog-section.d.ts.map +1 -0
  27. package/dist/core/extract-changelog-section.js +16 -0
  28. package/dist/core/fetch-pull-requests.d.ts +28 -0
  29. package/dist/core/fetch-pull-requests.d.ts.map +1 -0
  30. package/dist/core/fetch-pull-requests.js +65 -0
  31. package/dist/core/generate-release-note.d.ts +45 -0
  32. package/dist/core/generate-release-note.d.ts.map +1 -0
  33. package/dist/core/generate-release-note.js +186 -0
  34. package/dist/core/paths.d.ts +7 -0
  35. package/dist/core/paths.d.ts.map +1 -0
  36. package/dist/core/paths.js +13 -0
  37. package/dist/core/products.d.ts +8 -0
  38. package/dist/core/products.d.ts.map +1 -0
  39. package/dist/core/products.js +12 -0
  40. package/dist/core/run-release-notes-generator.d.ts +26 -0
  41. package/dist/core/run-release-notes-generator.d.ts.map +1 -0
  42. package/dist/core/run-release-notes-generator.js +150 -0
  43. package/dist/index.d.ts +22 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +15 -0
  46. package/dist/providers/anthropic.d.ts +9 -0
  47. package/dist/providers/anthropic.d.ts.map +1 -0
  48. package/dist/providers/anthropic.js +53 -0
  49. package/dist/providers/openai.d.ts +9 -0
  50. package/dist/providers/openai.d.ts.map +1 -0
  51. package/dist/providers/openai.js +54 -0
  52. package/dist/types.d.ts +129 -0
  53. package/dist/types.d.ts.map +1 -0
  54. package/dist/types.js +167 -0
  55. package/dist/writers/write-release-notes-json.d.ts +15 -0
  56. package/dist/writers/write-release-notes-json.d.ts.map +1 -0
  57. package/dist/writers/write-release-notes-json.js +114 -0
  58. package/dist/writers/write-release-notes-markdown.d.ts +13 -0
  59. package/dist/writers/write-release-notes-markdown.d.ts.map +1 -0
  60. package/dist/writers/write-release-notes-markdown.js +23 -0
  61. package/dist/writers/write-release-notes-schema.d.ts +20 -0
  62. package/dist/writers/write-release-notes-schema.d.ts.map +1 -0
  63. package/dist/writers/write-release-notes-schema.js +37 -0
  64. package/package.json +68 -0
  65. package/schemas/release-notes.schema.json +232 -0
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Pull request context fetched from the GitHub REST API.
3
+ */
4
+ export type PullRequestSummary = {
5
+ number: number;
6
+ title: string;
7
+ body: string;
8
+ };
9
+ type FetchOptions = {
10
+ /** PR numbers to fetch. Duplicates are deduplicated internally. */
11
+ numbers: readonly number[];
12
+ /** `owner/repo` slug. */
13
+ repo: string;
14
+ /** Optional GitHub token. */
15
+ token?: string;
16
+ /** Optional `fetch` injection for tests. */
17
+ fetchImpl?: typeof fetch;
18
+ };
19
+ /**
20
+ * Extract unique PR numbers from a Changesets-style CHANGELOG section.
21
+ */
22
+ export declare const extractPullRequestNumbers: (markdown: string, repo?: string) => number[];
23
+ /**
24
+ * Fetch PR titles and descriptions for every requested number.
25
+ */
26
+ export declare const fetchPullRequests: (options: FetchOptions) => Promise<Map<number, PullRequestSummary>>;
27
+ export {};
28
+ //# sourceMappingURL=fetch-pull-requests.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-pull-requests.d.ts","sourceRoot":"","sources":["../../src/core/fetch-pull-requests.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,MAAM,EAAE,MAAM,CAAA;IACd,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED,KAAK,YAAY,GAAG;IAClB,mEAAmE;IACnE,OAAO,EAAE,SAAS,MAAM,EAAE,CAAA;IAC1B,yBAAyB;IACzB,IAAI,EAAE,MAAM,CAAA;IACZ,6BAA6B;IAC7B,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,4CAA4C;IAC5C,SAAS,CAAC,EAAE,OAAO,KAAK,CAAA;CACzB,CAAA;AAMD;;GAEG;AACH,eAAO,MAAM,yBAAyB,GAAI,UAAU,MAAM,EAAE,OAAO,MAAM,KAAG,MAAM,EAmBjF,CAAA;AAgBD;;GAEG;AACH,eAAO,MAAM,iBAAiB,GAAU,SAAS,YAAY,KAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAiCtG,CAAA"}
@@ -0,0 +1,65 @@
1
+ const MAX_BODY_LENGTH = 4000;
2
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
3
+ /**
4
+ * Extract unique PR numbers from a Changesets-style CHANGELOG section.
5
+ */
6
+ export const extractPullRequestNumbers = (markdown, repo) => {
7
+ const found = new Set();
8
+ const repoPattern = repo
9
+ ? `${escapeRegExp(repo)}\\/(?:pull|issues)\\/(\\d+)`
10
+ : '[\\w.-]+\\/[\\w.-]+\\/(?:pull|issues)\\/(\\d+)';
11
+ const pattern = new RegExp(`(?:${repoPattern})|#(\\d+)`, 'g');
12
+ for (const match of markdown.matchAll(pattern)) {
13
+ const raw = match[1] ?? match[2];
14
+ if (!raw) {
15
+ continue;
16
+ }
17
+ const parsed = Number.parseInt(raw, 10);
18
+ if (Number.isFinite(parsed) && parsed > 0) {
19
+ found.add(parsed);
20
+ }
21
+ }
22
+ return [...found].sort((a, b) => a - b);
23
+ };
24
+ const truncateBody = (body) => {
25
+ const trimmed = body.trim();
26
+ if (trimmed.length <= MAX_BODY_LENGTH) {
27
+ return trimmed;
28
+ }
29
+ return `${trimmed.slice(0, MAX_BODY_LENGTH)}\n\n[truncated]`;
30
+ };
31
+ /**
32
+ * Fetch PR titles and descriptions for every requested number.
33
+ */
34
+ export const fetchPullRequests = async (options) => {
35
+ const fetchImpl = options.fetchImpl ?? fetch;
36
+ const summaries = new Map();
37
+ const unique = [...new Set(options.numbers)].filter((value) => Number.isFinite(value) && value > 0);
38
+ const headers = {
39
+ accept: 'application/vnd.github+json',
40
+ 'x-github-api-version': '2022-11-28',
41
+ };
42
+ if (options.token) {
43
+ headers.authorization = `Bearer ${options.token}`;
44
+ }
45
+ for (const number of unique) {
46
+ try {
47
+ const response = await fetchImpl(`https://api.github.com/repos/${options.repo}/pulls/${number}`, { headers });
48
+ if (!response.ok) {
49
+ console.warn(`Skipping PR #${number}: GitHub returned ${response.status}`);
50
+ continue;
51
+ }
52
+ const payload = (await response.json());
53
+ const title = typeof payload.title === 'string' ? payload.title.trim() : '';
54
+ const body = typeof payload.body === 'string' ? truncateBody(payload.body) : '';
55
+ if (!title) {
56
+ continue;
57
+ }
58
+ summaries.set(number, { number, title, body });
59
+ }
60
+ catch (error) {
61
+ console.warn(`Skipping PR #${number}: ${error.message}`);
62
+ }
63
+ }
64
+ return summaries;
65
+ };
@@ -0,0 +1,45 @@
1
+ import type { ProductPromptContext, PromptOptions, ReleaseNotesProvider } from '../config/types.js';
2
+ import { type ReleaseNote } from '../types.js';
3
+ import type { PullRequestSummary } from './fetch-pull-requests.js';
4
+ /**
5
+ * One CHANGELOG section pulled from a dependency that ships inside the release.
6
+ */
7
+ export type DependencyChangelog = {
8
+ packageName: string;
9
+ version: string;
10
+ changelogSection: string;
11
+ };
12
+ export type GenerateReleaseNoteOptions = {
13
+ packageName: string;
14
+ version: string;
15
+ date: string;
16
+ changelogSection: string;
17
+ releaseUrl: string;
18
+ provider: ReleaseNotesProvider;
19
+ model?: string;
20
+ product?: ProductPromptContext;
21
+ prompts?: PromptOptions;
22
+ dependencyChangelogs?: readonly DependencyChangelog[];
23
+ pullRequests?: ReadonlyMap<number, PullRequestSummary>;
24
+ maxOutputTokens?: number;
25
+ signal?: AbortSignal;
26
+ };
27
+ export declare const buildDefaultSystemPrompt: (product: ProductPromptContext) => string;
28
+ export declare const buildSystemPrompt: (options: {
29
+ product: ProductPromptContext;
30
+ prompts?: PromptOptions;
31
+ }) => string;
32
+ export declare const buildPullRequestContext: (pullRequests: ReadonlyMap<number, PullRequestSummary> | undefined) => string;
33
+ export declare const buildDependencyChangelogContext: (dependencyChangelogs: readonly DependencyChangelog[] | undefined) => string;
34
+ export declare const buildUserPrompt: (options: Pick<GenerateReleaseNoteOptions, "packageName" | "version" | "date" | "changelogSection" | "releaseUrl" | "pullRequests" | "dependencyChangelogs">) => string;
35
+ /**
36
+ * Turn changelog context into a validated release note with a pluggable provider.
37
+ *
38
+ * The provider output is non-deterministic, so a single run occasionally trips
39
+ * a schema limit (for example a highlight that runs past 280 characters).
40
+ * Rather than hard-failing the release pipeline on a cosmetic slip, we feed the
41
+ * previous output and the validation error back into the prompt and retry up to
42
+ * `MAX_ATTEMPTS` times.
43
+ */
44
+ export declare const generateReleaseNote: (options: GenerateReleaseNoteOptions) => Promise<ReleaseNote>;
45
+ //# sourceMappingURL=generate-release-note.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-release-note.d.ts","sourceRoot":"","sources":["../../src/core/generate-release-note.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAA;AAChG,OAAO,EAAE,KAAK,WAAW,EAAqD,MAAM,UAAU,CAAA;AAC9F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAA;AAa/D;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC,WAAW,EAAE,MAAM,CAAA;IACnB,OAAO,EAAE,MAAM,CAAA;IACf,gBAAgB,EAAE,MAAM,CAAA;CACzB,CAAA;AAED,MAAM,MAAM,0BAA0B,GAAG;IACvC,WAAW,EAAE,MAAM,CAAA;IACnB,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,gBAAgB,EAAE,MAAM,CAAA;IACxB,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,EAAE,oBAAoB,CAAA;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,OAAO,CAAC,EAAE,oBAAoB,CAAA;IAC9B,OAAO,CAAC,EAAE,aAAa,CAAA;IACvB,oBAAoB,CAAC,EAAE,SAAS,mBAAmB,EAAE,CAAA;IACrD,YAAY,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAA;IACtD,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB,CAAA;AAED,eAAO,MAAM,wBAAwB,GAAI,SAAS,oBAAoB,KAAG,MAyBxE,CAAA;AAED,eAAO,MAAM,iBAAiB,GAAI,SAAS;IAAE,OAAO,EAAE,oBAAoB,CAAC;IAAC,OAAO,CAAC,EAAE,aAAa,CAAA;CAAE,KAAG,MAEvG,CAAA;AAED,eAAO,MAAM,uBAAuB,GAAI,cAAc,WAAW,CAAC,MAAM,EAAE,kBAAkB,CAAC,GAAG,SAAS,KAAG,MAU3G,CAAA;AAED,eAAO,MAAM,+BAA+B,GAC1C,sBAAsB,SAAS,mBAAmB,EAAE,GAAG,SAAS,KAC/D,MAkBF,CAAA;AAED,eAAO,MAAM,eAAe,GAC1B,SAAS,IAAI,CACX,0BAA0B,EAC1B,aAAa,GAAG,SAAS,GAAG,MAAM,GAAG,kBAAkB,GAAG,YAAY,GAAG,cAAc,GAAG,sBAAsB,CACjH,KACA,MAyBF,CAAA;AA8DD;;;;;;;;GAQG;AACH,eAAO,MAAM,mBAAmB,GAAU,SAAS,0BAA0B,KAAG,OAAO,CAAC,WAAW,CAyClG,CAAA"}
@@ -0,0 +1,186 @@
1
+ import { aiReleaseNoteSchema, buildReleaseNoteFromAiOutput } from '../types.js';
2
+ const DEFAULT_MAX_OUTPUT_TOKENS = 1024;
3
+ /**
4
+ * How many times to ask the provider for a note before giving up. The output
5
+ * is non-deterministic, so a single run occasionally trips a schema limit
6
+ * (for example a highlight that runs past 280 characters). Rather than
7
+ * hard-failing the release pipeline on a cosmetic slip, we feed the
8
+ * validation error back to the provider and let it correct itself.
9
+ */
10
+ const MAX_ATTEMPTS = 3;
11
+ export const buildDefaultSystemPrompt = (product) => {
12
+ return [
13
+ `You write release notes for ${product.displayName} - ${product.description}.`,
14
+ 'You are summarising a Changesets-style CHANGELOG section for users reading curated release notes.',
15
+ '',
16
+ 'Tone and style:',
17
+ '- Friendly, human, Linear / Vercel-like.',
18
+ '- Do not use contractions (write "do not", not "don\'t").',
19
+ '- Sentence case for the title. No exclamation marks.',
20
+ '- Talk about user-facing changes only. Skip refactors, dependency bumps, internal CI changes, and chores.',
21
+ '- If every entry is a chore or dependency bump, return a single short note that says polish and bug fixes shipped.',
22
+ '',
23
+ 'Inputs:',
24
+ '- The CHANGELOG section is the source of truth for what changed in the released package.',
25
+ '- "Dependency CHANGELOG" blocks may follow with sections from dependencies that ship inside this release. Treat their entries as user-facing changes that landed in the parent release.',
26
+ '- A "Pull request context" block may follow with each PR\'s title and description. Use it to understand the why behind each entry, but do not invent details that are not supported by these inputs.',
27
+ '',
28
+ 'Output format:',
29
+ '- You MUST respond with a single JSON object and nothing else. No markdown fences, no commentary.',
30
+ '- Keys only: version, title, description (optional), highlights (optional array, max 5). No other keys.',
31
+ '- version must match the package version from the user message (semver string).',
32
+ '- title is one short sentence (max 120 characters).',
33
+ '- description is one paragraph that sets context (max 500 characters). Omit it when there is only one thing to say.',
34
+ '- highlights are single-sentence bullet points (at most 5, each max 280 characters). Keep each one short and split a long highlight into two rather than letting it run over. Omit the array when there are fewer than two interesting changes.',
35
+ ].join('\n');
36
+ };
37
+ export const buildSystemPrompt = (options) => {
38
+ return options.prompts?.systemPrompt?.({ product: options.product }) ?? buildDefaultSystemPrompt(options.product);
39
+ };
40
+ export const buildPullRequestContext = (pullRequests) => {
41
+ if (!pullRequests || pullRequests.size === 0) {
42
+ return '';
43
+ }
44
+ const ordered = [...pullRequests.values()].sort((a, b) => a.number - b.number);
45
+ const blocks = ordered.map((pr) => {
46
+ const body = pr.body.length > 0 ? pr.body : '(no description)';
47
+ return [`### PR #${pr.number}: ${pr.title}`, '', body].join('\n');
48
+ });
49
+ return ['Pull request context (titles and descriptions for each PR referenced above):', '', ...blocks].join('\n');
50
+ };
51
+ export const buildDependencyChangelogContext = (dependencyChangelogs) => {
52
+ if (!dependencyChangelogs || dependencyChangelogs.length === 0) {
53
+ return '';
54
+ }
55
+ const blocks = dependencyChangelogs.map((entry) => {
56
+ return [
57
+ `### Dependency CHANGELOG: ${entry.packageName}@${entry.version}`,
58
+ '',
59
+ '```markdown',
60
+ entry.changelogSection,
61
+ '```',
62
+ ].join('\n');
63
+ });
64
+ return [
65
+ 'Dependency CHANGELOG sections (changes from dependencies that ship inside this release):',
66
+ '',
67
+ ...blocks,
68
+ ].join('\n');
69
+ };
70
+ export const buildUserPrompt = (options) => {
71
+ const sections = [
72
+ `Package: ${options.packageName}`,
73
+ `Version: ${options.version}`,
74
+ `Date: ${options.date}`,
75
+ `Release URL (for maintainers only - do not include this in your JSON): ${options.releaseUrl}`,
76
+ '',
77
+ `CHANGELOG section for ${options.packageName}@${options.version}:`,
78
+ '```markdown',
79
+ options.changelogSection,
80
+ '```',
81
+ ];
82
+ const dependencyContext = buildDependencyChangelogContext(options.dependencyChangelogs);
83
+ if (dependencyContext) {
84
+ sections.push('', dependencyContext);
85
+ }
86
+ const pullRequestContext = buildPullRequestContext(options.pullRequests);
87
+ if (pullRequestContext) {
88
+ sections.push('', pullRequestContext);
89
+ }
90
+ sections.push('', 'Return ONLY the JSON object.');
91
+ return sections.join('\n');
92
+ };
93
+ const parseProviderJson = (payload) => {
94
+ if (typeof payload === 'string') {
95
+ const text = payload.trim();
96
+ const fenced = text.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
97
+ const jsonText = (fenced?.[1] ?? text).trim();
98
+ try {
99
+ return JSON.parse(jsonText);
100
+ }
101
+ catch (error) {
102
+ throw new Error(`AI provider returned invalid JSON: ${error.message}\nRaw text:\n${jsonText}`);
103
+ }
104
+ }
105
+ return payload;
106
+ };
107
+ /**
108
+ * Parse and validate one provider response. Returns the validated payload on
109
+ * success, or a structured failure carrying both a terse `feedback` line to
110
+ * send back to the provider on the next attempt and the verbose `fatalError`
111
+ * to surface if we run out of attempts.
112
+ */
113
+ const validateProviderResponse = (raw) => {
114
+ let parsed;
115
+ try {
116
+ parsed = parseProviderJson(raw);
117
+ }
118
+ catch (error) {
119
+ return {
120
+ ok: false,
121
+ feedback: `Your previous response was not valid JSON (${error.message}). Respond with a single valid JSON object and nothing else.`,
122
+ fatalError: error,
123
+ };
124
+ }
125
+ if (typeof parsed !== 'object' || parsed === null) {
126
+ return {
127
+ ok: false,
128
+ feedback: 'Your previous response was not a JSON object. Respond with a single JSON object and nothing else.',
129
+ fatalError: new Error(`AI provider returned JSON that is not an object.\nPayload:\n${JSON.stringify(parsed, null, 2)}`),
130
+ };
131
+ }
132
+ const aiResult = aiReleaseNoteSchema.safeParse(parsed);
133
+ if (!aiResult.success) {
134
+ return {
135
+ ok: false,
136
+ feedback: `Your previous response failed validation:\n${aiResult.error.message}\nReturn a corrected JSON object that satisfies every constraint. Respond with the JSON object only.`,
137
+ fatalError: new Error(`AI-generated release note failed validation:\n${aiResult.error.message}\nPayload:\n${JSON.stringify(parsed, null, 2)}`),
138
+ };
139
+ }
140
+ return { ok: true, data: aiResult.data };
141
+ };
142
+ /**
143
+ * Turn changelog context into a validated release note with a pluggable provider.
144
+ *
145
+ * The provider output is non-deterministic, so a single run occasionally trips
146
+ * a schema limit (for example a highlight that runs past 280 characters).
147
+ * Rather than hard-failing the release pipeline on a cosmetic slip, we feed the
148
+ * previous output and the validation error back into the prompt and retry up to
149
+ * `MAX_ATTEMPTS` times.
150
+ */
151
+ export const generateReleaseNote = async (options) => {
152
+ const product = options.product ?? {
153
+ displayName: options.packageName,
154
+ description: options.prompts?.productDescriptionFallback ?? 'an open-source package',
155
+ };
156
+ const systemPrompt = buildSystemPrompt({ product, prompts: options.prompts });
157
+ const baseUserPrompt = buildUserPrompt(options);
158
+ let userPrompt = baseUserPrompt;
159
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
160
+ const raw = await options.provider.generateJson({
161
+ model: options.model ?? options.provider.defaultModel,
162
+ systemPrompt,
163
+ userPrompt,
164
+ schema: aiReleaseNoteSchema,
165
+ maxOutputTokens: options.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,
166
+ signal: options.signal,
167
+ });
168
+ const result = validateProviderResponse(raw);
169
+ if (result.ok) {
170
+ return buildReleaseNoteFromAiOutput(result.data, {
171
+ version: options.version,
172
+ date: options.date,
173
+ href: options.releaseUrl,
174
+ });
175
+ }
176
+ if (attempt >= MAX_ATTEMPTS) {
177
+ throw result.fatalError;
178
+ }
179
+ // Feed the previous output and failure back so the next attempt can self-correct.
180
+ console.warn(`Release note attempt ${attempt} failed validation; retrying with feedback.`);
181
+ const previousOutput = typeof raw === 'string' ? raw : JSON.stringify(raw);
182
+ userPrompt = [baseUserPrompt, '', 'Your previous response was:', previousOutput, '', result.feedback].join('\n');
183
+ }
184
+ // Unreachable: the loop either returns a note or throws on the final attempt.
185
+ throw new Error('Failed to generate a release note after exhausting all attempts.');
186
+ };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Resolve paths against the directory the user invoked the command from.
3
+ */
4
+ export declare const resolveUserPath: (input: string, cwd?: string) => string;
5
+ export declare const normalizeRelativePath: (input: string) => string;
6
+ export declare const toWorkspaceRelativePath: (input: string, cwd?: string) => string;
7
+ //# sourceMappingURL=paths.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paths.d.ts","sourceRoot":"","sources":["../../src/core/paths.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,eAAe,GAAI,OAAO,MAAM,EAAE,YAA2C,KAAG,MAE5F,CAAA;AAED,eAAO,MAAM,qBAAqB,GAAI,OAAO,MAAM,KAAG,MAErD,CAAA;AAED,eAAO,MAAM,uBAAuB,GAAI,OAAO,MAAM,EAAE,YAA2C,KAAG,MAEpG,CAAA"}
@@ -0,0 +1,13 @@
1
+ import { relative, resolve } from 'node:path';
2
+ /**
3
+ * Resolve paths against the directory the user invoked the command from.
4
+ */
5
+ export const resolveUserPath = (input, cwd = process.env.INIT_CWD ?? process.cwd()) => {
6
+ return resolve(cwd, input);
7
+ };
8
+ export const normalizeRelativePath = (input) => {
9
+ return input.replace(/^\.\/+/, '').replace(/\\/g, '/');
10
+ };
11
+ export const toWorkspaceRelativePath = (input, cwd = process.env.INIT_CWD ?? process.cwd()) => {
12
+ return relative(cwd, resolve(cwd, input)).replace(/\\/g, '/');
13
+ };
@@ -0,0 +1,8 @@
1
+ import type { ReleaseNotesProduct } from '../config/types.js';
2
+ /** Derive the sibling markdown path from a JSON output path. */
3
+ export declare const deriveMarkdownPath: (jsonPath: string) => string;
4
+ /**
5
+ * Resolve a registered product from an on-disk release notes JSON path.
6
+ */
7
+ export declare const findReleaseNotesProductByJsonPath: (jsonPath: string, products: readonly ReleaseNotesProduct[]) => ReleaseNotesProduct | undefined;
8
+ //# sourceMappingURL=products.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"products.d.ts","sourceRoot":"","sources":["../../src/core/products.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAA;AAG1D,gEAAgE;AAChE,eAAO,MAAM,kBAAkB,GAAI,UAAU,MAAM,KAAG,MAErD,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,iCAAiC,GAC5C,UAAU,MAAM,EAChB,UAAU,SAAS,mBAAmB,EAAE,KACvC,mBAAmB,GAAG,SAGxB,CAAA"}
@@ -0,0 +1,12 @@
1
+ import { toWorkspaceRelativePath } from './paths.js';
2
+ /** Derive the sibling markdown path from a JSON output path. */
3
+ export const deriveMarkdownPath = (jsonPath) => {
4
+ return jsonPath.endsWith('.json') ? `${jsonPath.slice(0, -'.json'.length)}.md` : `${jsonPath}.md`;
5
+ };
6
+ /**
7
+ * Resolve a registered product from an on-disk release notes JSON path.
8
+ */
9
+ export const findReleaseNotesProductByJsonPath = (jsonPath, products) => {
10
+ const normalized = toWorkspaceRelativePath(jsonPath);
11
+ return products.find((product) => product.outputPath === normalized);
12
+ };
@@ -0,0 +1,26 @@
1
+ import type { GithubOptions, PromptOptions, ReleaseNotesProduct, ReleaseNotesProvider } from '../config/types.js';
2
+ export type RunReleaseNotesGeneratorOptions = {
3
+ product: ReleaseNotesProduct;
4
+ provider: ReleaseNotesProvider;
5
+ version?: string;
6
+ date?: string;
7
+ model?: string;
8
+ dryRun?: boolean;
9
+ writeMarkdown?: boolean;
10
+ changedPaths?: ReadonlySet<string> | null;
11
+ github?: GithubOptions;
12
+ prompts?: PromptOptions;
13
+ fetchImpl?: typeof fetch;
14
+ };
15
+ export type RunReleaseNotesGeneratorResult = {
16
+ generated: boolean;
17
+ outputPath: string;
18
+ };
19
+ export declare const buildChangelogUrl: (options: {
20
+ repo?: string;
21
+ baseBranch?: string;
22
+ changelogPath: string;
23
+ version: string;
24
+ }) => string;
25
+ export declare const runReleaseNotesGeneratorForProduct: (options: RunReleaseNotesGeneratorOptions) => Promise<RunReleaseNotesGeneratorResult>;
26
+ //# sourceMappingURL=run-release-notes-generator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-release-notes-generator.d.ts","sourceRoot":"","sources":["../../src/core/run-release-notes-generator.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAA;AAe9G,MAAM,MAAM,+BAA+B,GAAG;IAC5C,OAAO,EAAE,mBAAmB,CAAA;IAC5B,QAAQ,EAAE,oBAAoB,CAAA;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,YAAY,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,IAAI,CAAA;IACzC,MAAM,CAAC,EAAE,aAAa,CAAA;IACtB,OAAO,CAAC,EAAE,aAAa,CAAA;IACvB,SAAS,CAAC,EAAE,OAAO,KAAK,CAAA;CACzB,CAAA;AAED,MAAM,MAAM,8BAA8B,GAAG;IAC3C,SAAS,EAAE,OAAO,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;CACnB,CAAA;AAkDD,eAAO,MAAM,iBAAiB,GAAI,SAAS;IACzC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,aAAa,EAAE,MAAM,CAAA;IACrB,OAAO,EAAE,MAAM,CAAA;CAChB,KAAG,MAMH,CAAA;AAED,eAAO,MAAM,kCAAkC,GAC7C,SAAS,+BAA+B,KACvC,OAAO,CAAC,8BAA8B,CAmHxC,CAAA"}
@@ -0,0 +1,150 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { buildReleaseNotesPreamble } from '@scalar/helpers/markdown/release-notes';
4
+ import { writeReleaseNoteJson } from '../writers/write-release-notes-json.js';
5
+ import { writeReleaseNotesMarkdown } from '../writers/write-release-notes-markdown.js';
6
+ import { shouldGenerateReleaseNotesForProduct, wasChangelogVersioned } from './detect-versioned-changelog-paths.js';
7
+ import { extractChangelogSection } from './extract-changelog-section.js';
8
+ import { extractPullRequestNumbers, fetchPullRequests } from './fetch-pull-requests.js';
9
+ import { generateReleaseNote } from './generate-release-note.js';
10
+ import { normalizeRelativePath, resolveUserPath } from './paths.js';
11
+ import { deriveMarkdownPath } from './products.js';
12
+ const readPackageJsonNextToChangelog = async (changelogPath) => {
13
+ const packageJsonPath = resolve(dirname(changelogPath), 'package.json');
14
+ try {
15
+ const contents = await readFile(packageJsonPath, 'utf-8');
16
+ const parsed = JSON.parse(contents);
17
+ return {
18
+ name: typeof parsed.name === 'string' ? parsed.name : null,
19
+ version: typeof parsed.version === 'string' ? parsed.version : null,
20
+ };
21
+ }
22
+ catch {
23
+ return { name: null, version: null };
24
+ }
25
+ };
26
+ const loadDependencyChangelog = async (changelogPath) => {
27
+ const resolvedPath = resolveUserPath(changelogPath);
28
+ const info = await readPackageJsonNextToChangelog(resolvedPath);
29
+ if (!info.version) {
30
+ console.warn(`Skipping dependency changelog ${changelogPath}: could not detect a version from the adjacent package.json.`);
31
+ return null;
32
+ }
33
+ let changelog;
34
+ try {
35
+ changelog = await readFile(resolvedPath, 'utf-8');
36
+ }
37
+ catch (error) {
38
+ console.warn(`Skipping dependency changelog ${changelogPath}: ${error.message}`);
39
+ return null;
40
+ }
41
+ const section = extractChangelogSection(changelog, info.version);
42
+ if (!section) {
43
+ console.warn(`Skipping dependency changelog ${changelogPath}: no changelog section found for version ${info.version}.`);
44
+ return null;
45
+ }
46
+ return {
47
+ packageName: info.name ?? changelogPath,
48
+ version: info.version,
49
+ changelogSection: section,
50
+ };
51
+ };
52
+ export const buildChangelogUrl = (options) => {
53
+ const repo = options.repo ?? 'scalar/scalar';
54
+ const baseBranch = options.baseBranch ?? 'main';
55
+ const repoRelativePath = normalizeRelativePath(options.changelogPath);
56
+ const anchor = options.version.replace(/[^a-zA-Z0-9]/g, '');
57
+ return `https://github.com/${repo}/blob/${baseBranch}/${repoRelativePath}#${anchor}`;
58
+ };
59
+ export const runReleaseNotesGeneratorForProduct = async (options) => {
60
+ const { product, provider } = options;
61
+ const changedPaths = options.changedPaths ?? null;
62
+ const changelogPath = resolveUserPath(product.changelogPath);
63
+ const outputPath = resolveUserPath(product.outputPath);
64
+ const markdownPath = resolveUserPath(product.markdownPath ?? deriveMarkdownPath(product.outputPath));
65
+ if (changedPaths !== null && !shouldGenerateReleaseNotesForProduct(product, changedPaths)) {
66
+ console.warn(`Skipping ${product.slug}: no version bump in this release.`);
67
+ return { generated: false, outputPath };
68
+ }
69
+ const version = options.version ?? (await readPackageJsonNextToChangelog(changelogPath)).version;
70
+ if (!version) {
71
+ console.warn(`Could not determine the release version for ${product.slug}. Pass --version explicitly or ensure ${dirname(changelogPath)}/package.json has a "version" field; skipping.`);
72
+ return { generated: false, outputPath };
73
+ }
74
+ const changelog = await readFile(changelogPath, 'utf-8');
75
+ const section = extractChangelogSection(changelog, version);
76
+ const dependencyChangelogs = [];
77
+ for (const path of product.dependencyChangelogPaths ?? []) {
78
+ if (changedPaths !== null && !wasChangelogVersioned(path, changedPaths)) {
79
+ continue;
80
+ }
81
+ const resolved = await loadDependencyChangelog(path);
82
+ if (resolved) {
83
+ dependencyChangelogs.push(resolved);
84
+ }
85
+ }
86
+ if (!section && dependencyChangelogs.length === 0) {
87
+ console.warn(`No changelog section found for version ${version} in ${product.changelogPath} and no dependency changelog sections were found; skipping.`);
88
+ return { generated: false, outputPath };
89
+ }
90
+ if (!section) {
91
+ console.warn(`No changelog section found for version ${version} in ${product.changelogPath}; continuing with dependency changelog context only.`);
92
+ }
93
+ const date = options.date ?? new Date().toISOString().slice(0, 10);
94
+ const releaseUrl = buildChangelogUrl({
95
+ repo: options.github?.repo,
96
+ baseBranch: options.github?.baseBranch,
97
+ changelogPath: product.changelogPath,
98
+ version,
99
+ });
100
+ const changelogSection = section ?? '';
101
+ const dependencyChangelogText = dependencyChangelogs.map((entry) => entry.changelogSection).join('\n');
102
+ const pullRequestNumbers = extractPullRequestNumbers([changelogSection, dependencyChangelogText].filter(Boolean).join('\n'), options.github?.repo);
103
+ const pullRequests = pullRequestNumbers.length && options.github?.repo
104
+ ? await fetchPullRequests({
105
+ numbers: pullRequestNumbers,
106
+ repo: options.github.repo,
107
+ token: options.github.token,
108
+ fetchImpl: options.fetchImpl,
109
+ })
110
+ : new Map();
111
+ if (pullRequestNumbers.length && pullRequests.size === 0) {
112
+ console.warn('Could not fetch any pull request descriptions; continuing with CHANGELOG-only context.');
113
+ }
114
+ const dependencySummary = dependencyChangelogs.length
115
+ ? ` (with dependency context from ${dependencyChangelogs.map((entry) => `${entry.packageName}@${entry.version}`).join(', ')})`
116
+ : '';
117
+ console.log(`Generating release note for ${product.packageName}@${version}${dependencySummary}...`);
118
+ const note = await generateReleaseNote({
119
+ packageName: product.packageName,
120
+ version,
121
+ date,
122
+ changelogSection,
123
+ releaseUrl,
124
+ provider,
125
+ model: options.model,
126
+ pullRequests,
127
+ dependencyChangelogs,
128
+ prompts: options.prompts,
129
+ product: {
130
+ displayName: product.displayName,
131
+ description: product.description,
132
+ },
133
+ });
134
+ if (options.dryRun) {
135
+ console.log('Dry run - generated release note:');
136
+ console.log(JSON.stringify(note, null, 2));
137
+ return { generated: true, outputPath };
138
+ }
139
+ const jsonResult = await writeReleaseNoteJson({ path: outputPath, note });
140
+ console.log(`${jsonResult.created ? 'Created' : 'Updated'} ${jsonResult.path}`);
141
+ if (options.writeMarkdown !== false) {
142
+ const markdownResult = await writeReleaseNotesMarkdown({
143
+ path: markdownPath,
144
+ entries: jsonResult.entries,
145
+ preamble: buildReleaseNotesPreamble(product.displayName),
146
+ });
147
+ console.log(`${markdownResult.created ? 'Created' : 'Updated'} ${markdownResult.path}`);
148
+ }
149
+ return { generated: true, outputPath };
150
+ };
@@ -0,0 +1,22 @@
1
+ export { createReleaseNotesGeneratorCommand, releaseNotesGenerator } from './commands/generate.js';
2
+ export { createSyncReleaseNotesMarkdownCommand, syncReleaseNotesMarkdown } from './commands/sync-markdown.js';
3
+ export { defineReleaseNotesConfig } from './config/define-config.js';
4
+ export { createBuiltInProvider, readReleaseNotesConfig } from './config/read-config.js';
5
+ export type { BuiltInProviderName, GithubOptions, ProductPromptContext, PromptOptions, ReleaseNotesConfig, ReleaseNotesProduct, ReleaseNotesProvider, ResolvedReleaseNotesConfig, } from './config/types.js';
6
+ export { getChangedPathsForReleaseFiltering } from './core/detect-versioned-changelog-paths.js';
7
+ export { extractChangelogSection } from './core/extract-changelog-section.js';
8
+ export type { PullRequestSummary } from './core/fetch-pull-requests.js';
9
+ export { extractPullRequestNumbers, fetchPullRequests } from './core/fetch-pull-requests.js';
10
+ export type { DependencyChangelog, GenerateReleaseNoteOptions } from './core/generate-release-note.js';
11
+ export { buildDefaultSystemPrompt, buildDependencyChangelogContext, buildPullRequestContext, buildSystemPrompt, buildUserPrompt, generateReleaseNote, } from './core/generate-release-note.js';
12
+ export type { RunReleaseNotesGeneratorOptions, RunReleaseNotesGeneratorResult, } from './core/run-release-notes-generator.js';
13
+ export { buildChangelogUrl, runReleaseNotesGeneratorForProduct } from './core/run-release-notes-generator.js';
14
+ export { createAnthropicProvider } from './providers/anthropic.js';
15
+ export { createOpenAIProvider } from './providers/openai.js';
16
+ export type { ReleaseNote, ReleaseNoteContentBlock } from './types.js';
17
+ export { aiReleaseNoteSchema, buildReleaseNoteFromAiOutput, releaseNoteSchema, releaseNotesFileSchema, } from './types.js';
18
+ export { mergeReleaseNotes, readReleaseNotesJsonFile, writeReleaseNoteJson } from './writers/write-release-notes-json.js';
19
+ export { writeReleaseNotesMarkdown } from './writers/write-release-notes-markdown.js';
20
+ export type { ReleaseNotesJsonSchemaMetadata } from './writers/write-release-notes-schema.js';
21
+ export { DEFAULT_RELEASE_NOTES_SCHEMA_ID, DEFAULT_RELEASE_NOTES_SCHEMA_PATH, DEFAULT_RELEASE_NOTES_SCHEMA_TITLE, buildReleaseNotesJsonSchema, writeReleaseNotesJsonSchema, } from './writers/write-release-notes-schema.js';
22
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAA;AAC/F,OAAO,EAAE,qCAAqC,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAA;AAC1G,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAA;AACjE,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAA;AACpF,YAAY,EACV,mBAAmB,EACnB,aAAa,EACb,oBAAoB,EACpB,aAAa,EACb,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,0BAA0B,GAC3B,MAAM,gBAAgB,CAAA;AACvB,OAAO,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAA;AAC5F,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAA;AAC1E,YAAY,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAA;AACpE,OAAO,EAAE,yBAAyB,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAA;AACzF,YAAY,EAAE,mBAAmB,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAA;AACnG,OAAO,EACL,wBAAwB,EACxB,+BAA+B,EAC/B,uBAAuB,EACvB,iBAAiB,EACjB,eAAe,EACf,mBAAmB,GACpB,MAAM,8BAA8B,CAAA;AACrC,YAAY,EACV,+BAA+B,EAC/B,8BAA8B,GAC/B,MAAM,oCAAoC,CAAA;AAC3C,OAAO,EAAE,iBAAiB,EAAE,kCAAkC,EAAE,MAAM,oCAAoC,CAAA;AAC1G,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAA;AAC/D,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAA;AACzD,YAAY,EAAE,WAAW,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAA;AACnE,OAAO,EACL,mBAAmB,EACnB,4BAA4B,EAC5B,iBAAiB,EACjB,sBAAsB,GACvB,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAA;AACtH,OAAO,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAA;AAClF,YAAY,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAA;AAC1F,OAAO,EACL,+BAA+B,EAC/B,iCAAiC,EACjC,kCAAkC,EAClC,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,sCAAsC,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ export { createReleaseNotesGeneratorCommand, releaseNotesGenerator } from './commands/generate.js';
2
+ export { createSyncReleaseNotesMarkdownCommand, syncReleaseNotesMarkdown } from './commands/sync-markdown.js';
3
+ export { defineReleaseNotesConfig } from './config/define-config.js';
4
+ export { createBuiltInProvider, readReleaseNotesConfig } from './config/read-config.js';
5
+ export { getChangedPathsForReleaseFiltering } from './core/detect-versioned-changelog-paths.js';
6
+ export { extractChangelogSection } from './core/extract-changelog-section.js';
7
+ export { extractPullRequestNumbers, fetchPullRequests } from './core/fetch-pull-requests.js';
8
+ export { buildDefaultSystemPrompt, buildDependencyChangelogContext, buildPullRequestContext, buildSystemPrompt, buildUserPrompt, generateReleaseNote, } from './core/generate-release-note.js';
9
+ export { buildChangelogUrl, runReleaseNotesGeneratorForProduct } from './core/run-release-notes-generator.js';
10
+ export { createAnthropicProvider } from './providers/anthropic.js';
11
+ export { createOpenAIProvider } from './providers/openai.js';
12
+ export { aiReleaseNoteSchema, buildReleaseNoteFromAiOutput, releaseNoteSchema, releaseNotesFileSchema, } from './types.js';
13
+ export { mergeReleaseNotes, readReleaseNotesJsonFile, writeReleaseNoteJson } from './writers/write-release-notes-json.js';
14
+ export { writeReleaseNotesMarkdown } from './writers/write-release-notes-markdown.js';
15
+ export { DEFAULT_RELEASE_NOTES_SCHEMA_ID, DEFAULT_RELEASE_NOTES_SCHEMA_PATH, DEFAULT_RELEASE_NOTES_SCHEMA_TITLE, buildReleaseNotesJsonSchema, writeReleaseNotesJsonSchema, } from './writers/write-release-notes-schema.js';
@@ -0,0 +1,9 @@
1
+ import type { ReleaseNotesProvider } from '../config/types.js';
2
+ type AnthropicProviderOptions = {
3
+ apiKey?: string;
4
+ model?: string;
5
+ fetchImpl?: typeof fetch;
6
+ };
7
+ export declare const createAnthropicProvider: (options?: AnthropicProviderOptions) => ReleaseNotesProvider;
8
+ export {};
9
+ //# sourceMappingURL=anthropic.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../src/providers/anthropic.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAA;AAM3D,KAAK,wBAAwB,GAAG;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,SAAS,CAAC,EAAE,OAAO,KAAK,CAAA;CACzB,CAAA;AAgBD,eAAO,MAAM,uBAAuB,GAAI,UAAS,wBAA6B,KAAG,oBA6ChF,CAAA"}