@releasekit/notes 0.2.0-next.9 → 0.2.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/dist/index.cjs DELETED
@@ -1,1656 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- ChangelogCreatorError: () => NotesError,
34
- ConfigError: () => ConfigError,
35
- EXIT_CODES: () => import_core2.EXIT_CODES,
36
- GitHubError: () => GitHubError,
37
- InputParseError: () => InputParseError,
38
- LLMError: () => LLMError,
39
- NotesError: () => NotesError,
40
- TemplateError: () => TemplateError,
41
- aggregateToRoot: () => aggregateToRoot,
42
- createTemplateContext: () => createTemplateContext,
43
- detectMonorepo: () => detectMonorepo,
44
- getDefaultConfig: () => getDefaultConfig,
45
- getExitCode: () => getExitCode,
46
- loadAuth: () => import_config.loadAuth,
47
- loadConfig: () => loadConfig,
48
- parsePackageVersioner: () => parsePackageVersioner,
49
- parsePackageVersionerFile: () => parsePackageVersionerFile,
50
- parsePackageVersionerStdin: () => parsePackageVersionerStdin,
51
- processInput: () => processInput,
52
- renderJson: () => renderJson,
53
- renderMarkdown: () => renderMarkdown,
54
- runPipeline: () => runPipeline,
55
- saveAuth: () => import_config.saveAuth,
56
- writeJson: () => writeJson,
57
- writeMarkdown: () => writeMarkdown,
58
- writeMonorepoChangelogs: () => writeMonorepoChangelogs
59
- });
60
- module.exports = __toCommonJS(index_exports);
61
-
62
- // src/core/config.ts
63
- var import_config = require("@releasekit/config");
64
- function loadConfig(projectDir = process.cwd(), configFile) {
65
- const options = { cwd: projectDir, configPath: configFile };
66
- return (0, import_config.loadNotesConfig)(options) ?? getDefaultConfig();
67
- }
68
- function getDefaultConfig() {
69
- return {
70
- output: [{ format: "markdown", file: "CHANGELOG.md" }],
71
- updateStrategy: "prepend"
72
- };
73
- }
74
-
75
- // src/core/pipeline.ts
76
- var fs8 = __toESM(require("fs"), 1);
77
- var path6 = __toESM(require("path"), 1);
78
- var import_core8 = require("@releasekit/core");
79
-
80
- // src/input/package-versioner.ts
81
- var fs = __toESM(require("fs"), 1);
82
-
83
- // src/errors/index.ts
84
- var import_core = require("@releasekit/core");
85
- var import_core2 = require("@releasekit/core");
86
- var NotesError = class extends import_core.ReleaseKitError {
87
- };
88
- var InputParseError = class extends NotesError {
89
- code = "INPUT_PARSE_ERROR";
90
- suggestions = [
91
- "Ensure input is valid JSON",
92
- "Check that input matches expected schema",
93
- "Use --input-source to specify format"
94
- ];
95
- };
96
- var TemplateError = class extends NotesError {
97
- code = "TEMPLATE_ERROR";
98
- suggestions = [
99
- "Check template syntax",
100
- "Ensure all required files exist (document, version, entry)",
101
- "Verify template engine matches file extension"
102
- ];
103
- };
104
- var LLMError = class extends NotesError {
105
- code = "LLM_ERROR";
106
- suggestions = [
107
- "Check API key is configured",
108
- "Verify model name is correct",
109
- "Check network connectivity",
110
- "Try with --no-llm to skip LLM processing"
111
- ];
112
- };
113
- var GitHubError = class extends NotesError {
114
- code = "GITHUB_ERROR";
115
- suggestions = [
116
- "Ensure GITHUB_TOKEN is set",
117
- "Check token has repo scope",
118
- "Verify repository exists and is accessible"
119
- ];
120
- };
121
- var ConfigError = class extends NotesError {
122
- code = "CONFIG_ERROR";
123
- suggestions = [
124
- "Check config file syntax",
125
- "Verify all required fields are present",
126
- "Run releasekit-notes init to create default config"
127
- ];
128
- };
129
- function getExitCode(error) {
130
- switch (error.code) {
131
- case "CONFIG_ERROR":
132
- return import_core.EXIT_CODES.CONFIG_ERROR;
133
- case "INPUT_PARSE_ERROR":
134
- return import_core.EXIT_CODES.INPUT_ERROR;
135
- case "TEMPLATE_ERROR":
136
- return import_core.EXIT_CODES.TEMPLATE_ERROR;
137
- case "LLM_ERROR":
138
- return import_core.EXIT_CODES.LLM_ERROR;
139
- case "GITHUB_ERROR":
140
- return import_core.EXIT_CODES.GITHUB_ERROR;
141
- default:
142
- return import_core.EXIT_CODES.GENERAL_ERROR;
143
- }
144
- }
145
-
146
- // src/input/package-versioner.ts
147
- function normalizeEntryType(type) {
148
- const typeMap = {
149
- added: "added",
150
- feat: "added",
151
- feature: "added",
152
- changed: "changed",
153
- update: "changed",
154
- refactor: "changed",
155
- deprecated: "deprecated",
156
- removed: "removed",
157
- fixed: "fixed",
158
- fix: "fixed",
159
- security: "security",
160
- sec: "security"
161
- };
162
- return typeMap[type.toLowerCase()] ?? "changed";
163
- }
164
- function parsePackageVersioner(json) {
165
- let data;
166
- try {
167
- data = JSON.parse(json);
168
- } catch (error) {
169
- throw new InputParseError(`Invalid JSON input: ${error instanceof Error ? error.message : String(error)}`);
170
- }
171
- if (!data.changelogs || !Array.isArray(data.changelogs)) {
172
- throw new InputParseError('Input must contain a "changelogs" array');
173
- }
174
- const packages = data.changelogs.map((changelog) => ({
175
- packageName: changelog.packageName,
176
- version: changelog.version,
177
- previousVersion: changelog.previousVersion,
178
- revisionRange: changelog.revisionRange,
179
- repoUrl: changelog.repoUrl,
180
- date: (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "",
181
- entries: changelog.entries.map((entry) => ({
182
- type: normalizeEntryType(entry.type),
183
- description: entry.description,
184
- issueIds: entry.issueIds,
185
- scope: entry.scope,
186
- originalType: entry.originalType,
187
- breaking: entry.breaking ?? entry.originalType?.includes("!") ?? false
188
- }))
189
- }));
190
- const repoUrl = packages[0]?.repoUrl ?? null;
191
- return {
192
- source: "package-versioner",
193
- packages,
194
- metadata: {
195
- repoUrl: repoUrl ?? void 0
196
- }
197
- };
198
- }
199
- function parsePackageVersionerFile(filePath) {
200
- const content = fs.readFileSync(filePath, "utf-8");
201
- return parsePackageVersioner(content);
202
- }
203
- async function parsePackageVersionerStdin() {
204
- const chunks = [];
205
- for await (const chunk of process.stdin) {
206
- chunks.push(chunk);
207
- }
208
- const content = chunks.join("");
209
- return parsePackageVersioner(content);
210
- }
211
-
212
- // src/llm/defaults.ts
213
- var LLM_DEFAULTS = {
214
- timeout: 6e4,
215
- maxTokens: 2e3,
216
- temperature: 0.7,
217
- concurrency: 5,
218
- retry: {
219
- maxAttempts: 3,
220
- initialDelay: 1e3,
221
- maxDelay: 3e4,
222
- backoffFactor: 2
223
- },
224
- models: {
225
- openai: "gpt-4o-mini",
226
- "openai-compatible": "gpt-4o-mini",
227
- anthropic: "claude-3-5-haiku-latest",
228
- ollama: "llama3.2"
229
- }
230
- };
231
-
232
- // src/llm/anthropic.ts
233
- var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
234
-
235
- // src/llm/base.ts
236
- var BaseLLMProvider = class {
237
- getTimeout(options) {
238
- return options?.timeout ?? LLM_DEFAULTS.timeout;
239
- }
240
- getMaxTokens(options) {
241
- return options?.maxTokens ?? LLM_DEFAULTS.maxTokens;
242
- }
243
- getTemperature(options) {
244
- return options?.temperature ?? LLM_DEFAULTS.temperature;
245
- }
246
- };
247
-
248
- // src/llm/anthropic.ts
249
- var AnthropicProvider = class extends BaseLLMProvider {
250
- name = "anthropic";
251
- client;
252
- model;
253
- constructor(config = {}) {
254
- super();
255
- const apiKey = config.apiKey ?? process.env.ANTHROPIC_API_KEY;
256
- if (!apiKey) {
257
- throw new LLMError("Anthropic API key not configured. Set ANTHROPIC_API_KEY or use --llm-api-key");
258
- }
259
- this.client = new import_sdk.default({ apiKey });
260
- this.model = config.model ?? LLM_DEFAULTS.models.anthropic;
261
- }
262
- async complete(prompt, options) {
263
- try {
264
- const response = await this.client.messages.create({
265
- model: this.model,
266
- max_tokens: this.getMaxTokens(options),
267
- messages: [{ role: "user", content: prompt }]
268
- });
269
- const firstBlock = response.content[0];
270
- if (!firstBlock || firstBlock.type !== "text") {
271
- throw new LLMError("Unexpected response format from Anthropic");
272
- }
273
- return firstBlock.text;
274
- } catch (error) {
275
- if (error instanceof LLMError) throw error;
276
- throw new LLMError(`Anthropic API error: ${error instanceof Error ? error.message : String(error)}`);
277
- }
278
- }
279
- };
280
-
281
- // src/llm/ollama.ts
282
- var OllamaProvider = class extends BaseLLMProvider {
283
- name = "ollama";
284
- baseURL;
285
- model;
286
- apiKey;
287
- constructor(config = {}) {
288
- super();
289
- this.baseURL = config.baseURL ?? process.env.OLLAMA_BASE_URL ?? "http://localhost:11434";
290
- this.model = config.model ?? LLM_DEFAULTS.models.ollama;
291
- this.apiKey = config.apiKey ?? process.env.OLLAMA_API_KEY;
292
- }
293
- async complete(prompt, options) {
294
- const requestBody = {
295
- model: this.model,
296
- messages: [{ role: "user", content: prompt }],
297
- stream: false,
298
- options: {
299
- num_predict: this.getMaxTokens(options),
300
- temperature: this.getTemperature(options)
301
- }
302
- };
303
- try {
304
- const headers = {
305
- "Content-Type": "application/json"
306
- };
307
- if (this.apiKey) {
308
- headers["Authorization"] = `Bearer ${this.apiKey}`;
309
- }
310
- const baseUrl = this.baseURL.endsWith("/api") ? this.baseURL.slice(0, -4) : this.baseURL;
311
- const response = await fetch(`${baseUrl}/api/chat`, {
312
- method: "POST",
313
- headers,
314
- body: JSON.stringify(requestBody)
315
- });
316
- if (!response.ok) {
317
- const text = await response.text();
318
- throw new LLMError(`Ollama request failed: ${response.status} ${text}`);
319
- }
320
- const data = await response.json();
321
- if (!data.message?.content) {
322
- throw new LLMError("Empty response from Ollama");
323
- }
324
- return data.message.content;
325
- } catch (error) {
326
- if (error instanceof LLMError) throw error;
327
- throw new LLMError(`Ollama error: ${error instanceof Error ? error.message : String(error)}`);
328
- }
329
- }
330
- };
331
-
332
- // src/llm/openai.ts
333
- var import_openai = __toESM(require("openai"), 1);
334
- var OpenAIProvider = class extends BaseLLMProvider {
335
- name = "openai";
336
- client;
337
- model;
338
- constructor(config = {}) {
339
- super();
340
- const apiKey = config.apiKey ?? process.env.OPENAI_API_KEY;
341
- if (!apiKey) {
342
- throw new LLMError("OpenAI API key not configured. Set OPENAI_API_KEY or use --llm-api-key");
343
- }
344
- this.client = new import_openai.default({
345
- apiKey,
346
- baseURL: config.baseURL
347
- });
348
- this.model = config.model ?? LLM_DEFAULTS.models.openai;
349
- }
350
- async complete(prompt, options) {
351
- try {
352
- const response = await this.client.chat.completions.create({
353
- model: this.model,
354
- messages: [{ role: "user", content: prompt }],
355
- max_tokens: this.getMaxTokens(options),
356
- temperature: this.getTemperature(options)
357
- });
358
- const content = response.choices[0]?.message?.content;
359
- if (!content) {
360
- throw new LLMError("Empty response from OpenAI");
361
- }
362
- return content;
363
- } catch (error) {
364
- if (error instanceof LLMError) throw error;
365
- throw new LLMError(`OpenAI API error: ${error instanceof Error ? error.message : String(error)}`);
366
- }
367
- }
368
- };
369
-
370
- // src/llm/openai-compatible.ts
371
- var import_openai2 = __toESM(require("openai"), 1);
372
- var OpenAICompatibleProvider = class extends BaseLLMProvider {
373
- name = "openai-compatible";
374
- client;
375
- model;
376
- constructor(config) {
377
- super();
378
- const apiKey = config.apiKey ?? process.env.OPENAI_API_KEY ?? "dummy";
379
- this.client = new import_openai2.default({
380
- apiKey,
381
- baseURL: config.baseURL
382
- });
383
- this.model = config.model ?? LLM_DEFAULTS.models["openai-compatible"];
384
- }
385
- async complete(prompt, options) {
386
- try {
387
- const response = await this.client.chat.completions.create({
388
- model: this.model,
389
- messages: [{ role: "user", content: prompt }],
390
- max_tokens: this.getMaxTokens(options),
391
- temperature: this.getTemperature(options)
392
- });
393
- const content = response.choices[0]?.message?.content;
394
- if (!content) {
395
- throw new LLMError("Empty response from LLM");
396
- }
397
- return content;
398
- } catch (error) {
399
- if (error instanceof LLMError) throw error;
400
- throw new LLMError(`LLM API error: ${error instanceof Error ? error.message : String(error)}`);
401
- }
402
- }
403
- };
404
-
405
- // src/llm/tasks/categorize.ts
406
- var import_core3 = require("@releasekit/core");
407
- var DEFAULT_CATEGORIZE_PROMPT = `You are categorizing changelog entries for a software release.
408
-
409
- Given the following entries, group them into meaningful categories (e.g., "Core", "UI", "API", "Performance", "Bug Fixes", "Documentation").
410
-
411
- Output a JSON object where keys are category names and values are arrays of entry indices (0-based).
412
-
413
- Entries:
414
- {{entries}}
415
-
416
- Output only valid JSON, nothing else:`;
417
- function buildCustomCategorizePrompt(categories) {
418
- const categoryList = categories.map((c) => `- "${c.name}": ${c.description}`).join("\n");
419
- const developerCategory = categories.find((c) => c.name === "Developer");
420
- let scopeInstructions = "";
421
- if (developerCategory) {
422
- const scopeMatch = developerCategory.description.match(/from:\s*([^.]+)/);
423
- if (scopeMatch?.[1]) {
424
- const scopes = scopeMatch[1].split(",").map((s) => s.trim()).filter(Boolean);
425
- if (scopes.length > 0) {
426
- scopeInstructions = `
427
-
428
- For the "Developer" category, you MUST assign a scope from this exact list: ${scopes.join(", ")}.
429
- `;
430
- }
431
- }
432
- }
433
- return `You are categorizing changelog entries for a software release.
434
-
435
- Given the following entries, group them into the specified categories. Only use the categories listed below in this exact order:
436
-
437
- Categories:
438
- ${categoryList}${scopeInstructions}
439
- Output a JSON object with two fields:
440
- - "categories": an object where keys are category names and values are arrays of entry indices (0-based)
441
- - "scopes": an object where keys are entry indices (as strings) and values are scope labels
442
-
443
- Entries:
444
- {{entries}}
445
-
446
- Output only valid JSON, nothing else:`;
447
- }
448
- async function categorizeEntries(provider, entries, context) {
449
- if (entries.length === 0) {
450
- return [];
451
- }
452
- const entriesText = entries.map((e, i) => `${i}. [${e.type}]${e.scope ? ` (${e.scope})` : ""}: ${e.description}`).join("\n");
453
- const hasCustomCategories = context.categories && context.categories.length > 0;
454
- const promptTemplate = hasCustomCategories ? buildCustomCategorizePrompt(context.categories) : DEFAULT_CATEGORIZE_PROMPT;
455
- const prompt = promptTemplate.replace("{{entries}}", entriesText);
456
- try {
457
- const response = await provider.complete(prompt);
458
- const cleaned = response.replace(/^```(?:json)?\n?/, "").replace(/\n?```$/, "").trim();
459
- const parsed = JSON.parse(cleaned);
460
- const result = [];
461
- if (hasCustomCategories && parsed.categories) {
462
- const categoryMap = parsed.categories;
463
- const scopeMap = parsed.scopes || {};
464
- for (const [indexStr, scope] of Object.entries(scopeMap)) {
465
- const idx = Number.parseInt(indexStr, 10);
466
- if (entries[idx] && scope) {
467
- entries[idx] = { ...entries[idx], scope };
468
- }
469
- }
470
- for (const [category, rawIndices] of Object.entries(categoryMap)) {
471
- const indices = Array.isArray(rawIndices) ? rawIndices : [];
472
- const categoryEntries = indices.map((i) => entries[i]).filter((e) => e !== void 0);
473
- if (categoryEntries.length > 0) {
474
- result.push({ category, entries: categoryEntries });
475
- }
476
- }
477
- } else {
478
- const categoryMap = parsed;
479
- for (const [category, rawIndices] of Object.entries(categoryMap)) {
480
- const indices = Array.isArray(rawIndices) ? rawIndices : [];
481
- const categoryEntries = indices.map((i) => entries[i]).filter((e) => e !== void 0);
482
- if (categoryEntries.length > 0) {
483
- result.push({ category, entries: categoryEntries });
484
- }
485
- }
486
- }
487
- return result;
488
- } catch (error) {
489
- (0, import_core3.warn)(
490
- `LLM categorization failed, falling back to General: ${error instanceof Error ? error.message : String(error)}`
491
- );
492
- return [{ category: "General", entries }];
493
- }
494
- }
495
-
496
- // src/llm/tasks/enhance.ts
497
- var ENHANCE_PROMPT = `You are improving changelog entries for a software project.
498
- Given a technical commit message, rewrite it as a clear, user-friendly changelog entry.
499
-
500
- Rules:
501
- - Be concise (1-2 sentences max)
502
- - Focus on user impact, not implementation details
503
- - Don't use technical jargon unless necessary
504
- - Preserve the scope if mentioned (e.g., "core:", "api:")
505
- {{style}}
506
-
507
- Original entry:
508
- Type: {{type}}
509
- {{#if scope}}Scope: {{scope}}{{/if}}
510
- Description: {{description}}
511
-
512
- Rewritten description (only output the new description, nothing else):`;
513
- async function enhanceEntry(provider, entry, _context) {
514
- const styleText = _context.style ? `- ${_context.style}` : '- Use present tense ("Add feature" not "Added feature")';
515
- const prompt = ENHANCE_PROMPT.replace("{{style}}", styleText).replace("{{type}}", entry.type).replace("{{#if scope}}Scope: {{scope}}{{/if}}", entry.scope ? `Scope: ${entry.scope}` : "").replace("{{description}}", entry.description);
516
- const response = await provider.complete(prompt);
517
- return response.trim();
518
- }
519
- async function enhanceEntries(provider, entries, context, concurrency = LLM_DEFAULTS.concurrency) {
520
- const results = [];
521
- for (let i = 0; i < entries.length; i += concurrency) {
522
- const batch = entries.slice(i, i + concurrency);
523
- const batchResults = await Promise.all(
524
- batch.map(async (entry) => {
525
- try {
526
- const newDescription = await enhanceEntry(provider, entry, context);
527
- return { ...entry, description: newDescription };
528
- } catch {
529
- return entry;
530
- }
531
- })
532
- );
533
- results.push(...batchResults);
534
- }
535
- return results;
536
- }
537
-
538
- // src/llm/tasks/enhance-and-categorize.ts
539
- var import_core4 = require("@releasekit/core");
540
-
541
- // src/utils/retry.ts
542
- function sleep(ms) {
543
- return new Promise((resolve2) => setTimeout(resolve2, ms));
544
- }
545
- async function withRetry(fn, options = {}) {
546
- const maxAttempts = options.maxAttempts ?? 3;
547
- const initialDelay = options.initialDelay ?? 1e3;
548
- const maxDelay = options.maxDelay ?? 3e4;
549
- const backoffFactor = options.backoffFactor ?? 2;
550
- let lastError;
551
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
552
- try {
553
- return await fn();
554
- } catch (error) {
555
- lastError = error;
556
- if (attempt < maxAttempts - 1) {
557
- const base = Math.min(initialDelay * backoffFactor ** attempt, maxDelay);
558
- const jitter = base * 0.2 * (Math.random() * 2 - 1);
559
- await sleep(Math.max(0, base + jitter));
560
- }
561
- }
562
- }
563
- throw lastError;
564
- }
565
-
566
- // src/llm/tasks/enhance-and-categorize.ts
567
- function buildPrompt(entries, categories, style) {
568
- const entriesText = entries.map((e, i) => `${i}. [${e.type}]${e.scope ? ` (${e.scope})` : ""}: ${e.description}`).join("\n");
569
- const styleText = style || 'Use present tense ("Add feature" not "Added feature"). Be concise.';
570
- const categorySection = categories ? `Categories (use ONLY these):
571
- ${categories.map((c) => `- "${c.name}": ${c.description}`).join("\n")}` : `Categories: Group into meaningful categories (e.g., "New", "Fixed", "Changed", "Removed").`;
572
- return `You are generating release notes for a software project. Given the following changelog entries, do two things:
573
-
574
- 1. **Rewrite** each entry as a clear, user-friendly description
575
- 2. **Categorize** each entry into the appropriate category
576
-
577
- Style guidelines:
578
- - ${styleText}
579
- - Be concise (1 short sentence per entry)
580
- - Focus on what changed, not implementation details
581
-
582
- ${categorySection}
583
-
584
- ${categories ? 'For entries in categories involving internal/developer changes, set a "scope" field with a short subcategory label (e.g., "CI", "Dependencies", "Testing").' : ""}
585
-
586
- Entries:
587
- ${entriesText}
588
-
589
- Output a JSON object with:
590
- - "entries": array of objects, one per input entry (same order), each with: { "description": "rewritten text", "category": "CategoryName", "scope": "optional subcategory label or null" }
591
-
592
- Output only valid JSON, nothing else:`;
593
- }
594
- async function enhanceAndCategorize(provider, entries, context) {
595
- if (entries.length === 0) {
596
- return { enhancedEntries: [], categories: [] };
597
- }
598
- const retryOpts = LLM_DEFAULTS.retry;
599
- try {
600
- return await withRetry(async () => {
601
- const prompt = buildPrompt(entries, context.categories, context.style);
602
- const response = await provider.complete(prompt);
603
- const cleaned = response.replace(/^```(?:json)?\n?/, "").replace(/\n?```$/, "").trim();
604
- const parsed = JSON.parse(cleaned);
605
- if (!Array.isArray(parsed.entries)) {
606
- throw new Error('Response missing "entries" array');
607
- }
608
- const enhancedEntries = entries.map((original, i) => {
609
- const result = parsed.entries[i];
610
- if (!result) return original;
611
- return {
612
- ...original,
613
- description: result.description || original.description,
614
- scope: result.scope || original.scope
615
- };
616
- });
617
- const categoryMap = /* @__PURE__ */ new Map();
618
- for (let i = 0; i < parsed.entries.length; i++) {
619
- const result = parsed.entries[i];
620
- const category = result?.category || "General";
621
- const entry = enhancedEntries[i];
622
- if (!entry) continue;
623
- if (!categoryMap.has(category)) {
624
- categoryMap.set(category, []);
625
- }
626
- categoryMap.get(category).push(entry);
627
- }
628
- const categories = [];
629
- for (const [category, catEntries] of categoryMap) {
630
- categories.push({ category, entries: catEntries });
631
- }
632
- return { enhancedEntries, categories };
633
- }, retryOpts);
634
- } catch (error) {
635
- (0, import_core4.warn)(
636
- `Combined enhance+categorize failed after ${retryOpts.maxAttempts} attempts: ${error instanceof Error ? error.message : String(error)}`
637
- );
638
- return {
639
- enhancedEntries: entries,
640
- categories: [{ category: "General", entries }]
641
- };
642
- }
643
- }
644
-
645
- // src/llm/tasks/release-notes.ts
646
- var RELEASE_NOTES_PROMPT = `You are writing release notes for a software project.
647
-
648
- Create engaging, user-friendly release notes for the following changes.
649
-
650
- Rules:
651
- - Start with a brief introduction (1-2 sentences)
652
- - Group related changes into sections
653
- - Use friendly, approachable language
654
- - Highlight breaking changes prominently
655
- - End with a brief conclusion or call to action
656
- - Use markdown formatting
657
-
658
- Version: {{version}}
659
- {{#if previousVersion}}Previous version: {{previousVersion}}{{/if}}
660
- Date: {{date}}
661
-
662
- Changes:
663
- {{entries}}
664
-
665
- Release notes (output only the markdown content):`;
666
- async function generateReleaseNotes(provider, entries, context) {
667
- if (entries.length === 0) {
668
- return `## Release ${context.version ?? "v1.0.0"}
669
-
670
- No notable changes in this release.`;
671
- }
672
- const entriesText = entries.map((e) => {
673
- let line = `- [${e.type}]`;
674
- if (e.scope) line += ` (${e.scope})`;
675
- line += `: ${e.description}`;
676
- if (e.breaking) line += " **BREAKING**";
677
- return line;
678
- }).join("\n");
679
- const prompt = RELEASE_NOTES_PROMPT.replace("{{version}}", context.version ?? "v1.0.0").replace(
680
- "{{#if previousVersion}}Previous version: {{previousVersion}}{{/if}}",
681
- context.previousVersion ? `Previous version: ${context.previousVersion}` : ""
682
- ).replace("{{date}}", context.date ?? (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "").replace("{{entries}}", entriesText);
683
- const response = await provider.complete(prompt);
684
- return response.trim();
685
- }
686
-
687
- // src/llm/tasks/summarize.ts
688
- var SUMMARIZE_PROMPT = `You are creating a summary of changes for a software release.
689
-
690
- Given the following changelog entries, create a brief summary (2-3 sentences) that captures the main themes of this release.
691
-
692
- Entries:
693
- {{entries}}
694
-
695
- Summary (only output the summary, nothing else):`;
696
- async function summarizeEntries(provider, entries, _context) {
697
- if (entries.length === 0) {
698
- return "";
699
- }
700
- const entriesText = entries.map((e) => `- [${e.type}]${e.scope ? ` (${e.scope})` : ""}: ${e.description}`).join("\n");
701
- const prompt = SUMMARIZE_PROMPT.replace("{{entries}}", entriesText);
702
- const response = await provider.complete(prompt);
703
- return response.trim();
704
- }
705
-
706
- // src/llm/index.ts
707
- function createProvider(config) {
708
- const authKeys = (0, import_config.loadAuth)();
709
- const apiKey = config.apiKey ?? authKeys[config.provider];
710
- switch (config.provider) {
711
- case "openai":
712
- return new OpenAIProvider({
713
- apiKey,
714
- baseURL: config.baseURL,
715
- model: config.model
716
- });
717
- case "anthropic":
718
- return new AnthropicProvider({
719
- apiKey,
720
- model: config.model
721
- });
722
- case "ollama":
723
- return new OllamaProvider({
724
- apiKey,
725
- baseURL: config.baseURL,
726
- model: config.model
727
- });
728
- case "openai-compatible": {
729
- if (!config.baseURL) {
730
- throw new LLMError("openai-compatible provider requires baseURL");
731
- }
732
- return new OpenAICompatibleProvider({
733
- apiKey,
734
- baseURL: config.baseURL,
735
- model: config.model
736
- });
737
- }
738
- default:
739
- throw new LLMError(`Unknown LLM provider: ${config.provider}`);
740
- }
741
- }
742
-
743
- // src/output/github-release.ts
744
- var import_rest = require("@octokit/rest");
745
- var import_core6 = require("@releasekit/core");
746
-
747
- // src/output/markdown.ts
748
- var fs2 = __toESM(require("fs"), 1);
749
- var path = __toESM(require("path"), 1);
750
- var import_core5 = require("@releasekit/core");
751
- var TYPE_ORDER = ["added", "changed", "deprecated", "removed", "fixed", "security"];
752
- var TYPE_LABELS = {
753
- added: "Added",
754
- changed: "Changed",
755
- deprecated: "Deprecated",
756
- removed: "Removed",
757
- fixed: "Fixed",
758
- security: "Security"
759
- };
760
- function groupEntriesByType(entries) {
761
- const grouped = /* @__PURE__ */ new Map();
762
- for (const type of TYPE_ORDER) {
763
- grouped.set(type, []);
764
- }
765
- for (const entry of entries) {
766
- const existing = grouped.get(entry.type) ?? [];
767
- existing.push(entry);
768
- grouped.set(entry.type, existing);
769
- }
770
- return grouped;
771
- }
772
- function formatEntry(entry) {
773
- let line;
774
- if (entry.breaking && entry.scope) {
775
- line = `- **BREAKING** **${entry.scope}**: ${entry.description}`;
776
- } else if (entry.breaking) {
777
- line = `- **BREAKING** ${entry.description}`;
778
- } else if (entry.scope) {
779
- line = `- **${entry.scope}**: ${entry.description}`;
780
- } else {
781
- line = `- ${entry.description}`;
782
- }
783
- if (entry.issueIds && entry.issueIds.length > 0) {
784
- line += ` (${entry.issueIds.join(", ")})`;
785
- }
786
- return line;
787
- }
788
- function formatVersion(context) {
789
- const lines = [];
790
- const versionHeader = context.previousVersion ? `## [${context.version}]` : `## ${context.version}`;
791
- lines.push(`${versionHeader} - ${context.date}`);
792
- lines.push("");
793
- if (context.compareUrl) {
794
- lines.push(`[Full Changelog](${context.compareUrl})`);
795
- lines.push("");
796
- }
797
- if (context.enhanced?.summary) {
798
- lines.push(context.enhanced.summary);
799
- lines.push("");
800
- }
801
- const grouped = groupEntriesByType(context.entries);
802
- for (const [type, entries] of grouped) {
803
- if (entries.length === 0) continue;
804
- lines.push(`### ${TYPE_LABELS[type]}`);
805
- for (const entry of entries) {
806
- lines.push(formatEntry(entry));
807
- }
808
- lines.push("");
809
- }
810
- return lines.join("\n");
811
- }
812
- function formatHeader() {
813
- return `# Changelog
814
-
815
- All notable changes to this project will be documented in this file.
816
-
817
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
818
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
819
-
820
- `;
821
- }
822
- function renderMarkdown(contexts) {
823
- const sections = [formatHeader()];
824
- for (const context of contexts) {
825
- sections.push(formatVersion(context));
826
- }
827
- return sections.join("\n");
828
- }
829
- function prependVersion(existingPath, context) {
830
- let existing = "";
831
- if (fs2.existsSync(existingPath)) {
832
- existing = fs2.readFileSync(existingPath, "utf-8");
833
- const headerEnd = existing.indexOf("\n## ");
834
- if (headerEnd >= 0) {
835
- const header = existing.slice(0, headerEnd);
836
- const body = existing.slice(headerEnd + 1);
837
- const newVersion = formatVersion(context);
838
- return `${header}
839
-
840
- ${newVersion}
841
- ${body}`;
842
- }
843
- }
844
- return renderMarkdown([context]);
845
- }
846
- function writeMarkdown(outputPath, contexts, config, dryRun) {
847
- const content = renderMarkdown(contexts);
848
- if (dryRun) {
849
- (0, import_core5.info)("--- Changelog Preview ---");
850
- console.log(content);
851
- (0, import_core5.info)("--- End Preview ---");
852
- return;
853
- }
854
- const dir = path.dirname(outputPath);
855
- if (!fs2.existsSync(dir)) {
856
- fs2.mkdirSync(dir, { recursive: true });
857
- }
858
- if (outputPath === "-") {
859
- process.stdout.write(content);
860
- return;
861
- }
862
- if (config.updateStrategy === "prepend" && fs2.existsSync(outputPath) && contexts.length === 1) {
863
- const firstContext = contexts[0];
864
- if (firstContext) {
865
- const updated = prependVersion(outputPath, firstContext);
866
- fs2.writeFileSync(outputPath, updated, "utf-8");
867
- }
868
- } else {
869
- fs2.writeFileSync(outputPath, content, "utf-8");
870
- }
871
- (0, import_core5.success)(`Changelog written to ${outputPath}`);
872
- }
873
-
874
- // src/output/github-release.ts
875
- var GitHubClient = class {
876
- octokit;
877
- owner;
878
- repo;
879
- constructor(options) {
880
- const token = options.token ?? process.env.GITHUB_TOKEN;
881
- if (!token) {
882
- throw new GitHubError("GITHUB_TOKEN not set. Set it as an environment variable.");
883
- }
884
- this.octokit = new import_rest.Octokit({ auth: token });
885
- this.owner = options.owner;
886
- this.repo = options.repo;
887
- }
888
- async createRelease(context, options = {}) {
889
- const tagName = `v${context.version}`;
890
- let body;
891
- if (context.enhanced?.releaseNotes) {
892
- body = context.enhanced.releaseNotes;
893
- } else {
894
- body = renderMarkdown([context]);
895
- }
896
- (0, import_core6.info)(`Creating GitHub release for ${tagName}`);
897
- try {
898
- const response = await this.octokit.repos.createRelease({
899
- owner: this.owner,
900
- repo: this.repo,
901
- tag_name: tagName,
902
- name: tagName,
903
- body,
904
- draft: options.draft ?? false,
905
- prerelease: options.prerelease ?? false,
906
- generate_release_notes: options.generateNotes ?? false
907
- });
908
- (0, import_core6.success)(`Release created: ${response.data.html_url}`);
909
- return {
910
- id: response.data.id,
911
- htmlUrl: response.data.html_url,
912
- tagName
913
- };
914
- } catch (error) {
915
- throw new GitHubError(`Failed to create release: ${error instanceof Error ? error.message : String(error)}`);
916
- }
917
- }
918
- async updateRelease(releaseId, context, options = {}) {
919
- const tagName = `v${context.version}`;
920
- let body;
921
- if (context.enhanced?.releaseNotes) {
922
- body = context.enhanced.releaseNotes;
923
- } else {
924
- body = renderMarkdown([context]);
925
- }
926
- (0, import_core6.info)(`Updating GitHub release ${releaseId}`);
927
- try {
928
- const response = await this.octokit.repos.updateRelease({
929
- owner: this.owner,
930
- repo: this.repo,
931
- release_id: releaseId,
932
- tag_name: tagName,
933
- name: tagName,
934
- body,
935
- draft: options.draft ?? false,
936
- prerelease: options.prerelease ?? false
937
- });
938
- (0, import_core6.success)(`Release updated: ${response.data.html_url}`);
939
- return {
940
- id: response.data.id,
941
- htmlUrl: response.data.html_url,
942
- tagName
943
- };
944
- } catch (error) {
945
- throw new GitHubError(`Failed to update release: ${error instanceof Error ? error.message : String(error)}`);
946
- }
947
- }
948
- async getReleaseByTag(tag) {
949
- try {
950
- const response = await this.octokit.repos.getReleaseByTag({
951
- owner: this.owner,
952
- repo: this.repo,
953
- tag
954
- });
955
- return {
956
- id: response.data.id,
957
- htmlUrl: response.data.html_url,
958
- tagName: response.data.tag_name
959
- };
960
- } catch {
961
- return null;
962
- }
963
- }
964
- };
965
- function parseRepoUrl(repoUrl) {
966
- const patterns = [
967
- /^https:\/\/github\.com\/([^/]+)\/([^/]+)/,
968
- /^git@github\.com:([^/]+)\/([^/]+)/,
969
- /^github\.com\/([^/]+)\/([^/]+)/
970
- ];
971
- for (const pattern of patterns) {
972
- const match = repoUrl.match(pattern);
973
- if (match?.[1] && match[2]) {
974
- return {
975
- owner: match[1],
976
- repo: match[2].replace(/\.git$/, "")
977
- };
978
- }
979
- }
980
- return null;
981
- }
982
- async function createGitHubRelease(context, options) {
983
- const client = new GitHubClient(options);
984
- return client.createRelease(context, options);
985
- }
986
-
987
- // src/output/json.ts
988
- var fs3 = __toESM(require("fs"), 1);
989
- var path2 = __toESM(require("path"), 1);
990
- var import_core7 = require("@releasekit/core");
991
- function renderJson(contexts) {
992
- return JSON.stringify(
993
- {
994
- versions: contexts.map((ctx) => ({
995
- packageName: ctx.packageName,
996
- version: ctx.version,
997
- previousVersion: ctx.previousVersion,
998
- date: ctx.date,
999
- entries: ctx.entries,
1000
- compareUrl: ctx.compareUrl
1001
- }))
1002
- },
1003
- null,
1004
- 2
1005
- );
1006
- }
1007
- function writeJson(outputPath, contexts, dryRun) {
1008
- const content = renderJson(contexts);
1009
- if (dryRun) {
1010
- (0, import_core7.info)("--- JSON Output Preview ---");
1011
- console.log(content);
1012
- (0, import_core7.info)("--- End Preview ---");
1013
- return;
1014
- }
1015
- const dir = path2.dirname(outputPath);
1016
- if (!fs3.existsSync(dir)) {
1017
- fs3.mkdirSync(dir, { recursive: true });
1018
- }
1019
- fs3.writeFileSync(outputPath, content, "utf-8");
1020
- (0, import_core7.success)(`JSON output written to ${outputPath}`);
1021
- }
1022
-
1023
- // src/templates/ejs.ts
1024
- var fs4 = __toESM(require("fs"), 1);
1025
- var import_ejs = __toESM(require("ejs"), 1);
1026
- function renderEjs(template, context) {
1027
- try {
1028
- return import_ejs.default.render(template, context);
1029
- } catch (error) {
1030
- throw new TemplateError(`EJS render error: ${error instanceof Error ? error.message : String(error)}`);
1031
- }
1032
- }
1033
- function renderEjsFile(filePath, context) {
1034
- if (!fs4.existsSync(filePath)) {
1035
- throw new TemplateError(`Template file not found: ${filePath}`);
1036
- }
1037
- const template = fs4.readFileSync(filePath, "utf-8");
1038
- return renderEjs(template, context);
1039
- }
1040
-
1041
- // src/templates/handlebars.ts
1042
- var fs5 = __toESM(require("fs"), 1);
1043
- var path3 = __toESM(require("path"), 1);
1044
- var import_handlebars = __toESM(require("handlebars"), 1);
1045
- function registerHandlebarsHelpers() {
1046
- import_handlebars.default.registerHelper("capitalize", (str) => {
1047
- return str.charAt(0).toUpperCase() + str.slice(1);
1048
- });
1049
- import_handlebars.default.registerHelper("eq", (a, b) => {
1050
- return a === b;
1051
- });
1052
- import_handlebars.default.registerHelper("ne", (a, b) => {
1053
- return a !== b;
1054
- });
1055
- import_handlebars.default.registerHelper("join", (arr, separator) => {
1056
- return Array.isArray(arr) ? arr.join(separator) : "";
1057
- });
1058
- }
1059
- function renderHandlebars(template, context) {
1060
- registerHandlebarsHelpers();
1061
- try {
1062
- const compiled = import_handlebars.default.compile(template);
1063
- return compiled(context);
1064
- } catch (error) {
1065
- throw new TemplateError(`Handlebars render error: ${error instanceof Error ? error.message : String(error)}`);
1066
- }
1067
- }
1068
- function renderHandlebarsFile(filePath, context) {
1069
- if (!fs5.existsSync(filePath)) {
1070
- throw new TemplateError(`Template file not found: ${filePath}`);
1071
- }
1072
- const template = fs5.readFileSync(filePath, "utf-8");
1073
- return renderHandlebars(template, context);
1074
- }
1075
- function renderHandlebarsComposable(templateDir, context) {
1076
- registerHandlebarsHelpers();
1077
- const versionPath = path3.join(templateDir, "version.hbs");
1078
- const entryPath = path3.join(templateDir, "entry.hbs");
1079
- const documentPath = path3.join(templateDir, "document.hbs");
1080
- if (!fs5.existsSync(documentPath)) {
1081
- throw new TemplateError(`Document template not found: ${documentPath}`);
1082
- }
1083
- if (fs5.existsSync(versionPath)) {
1084
- import_handlebars.default.registerPartial("version", fs5.readFileSync(versionPath, "utf-8"));
1085
- }
1086
- if (fs5.existsSync(entryPath)) {
1087
- import_handlebars.default.registerPartial("entry", fs5.readFileSync(entryPath, "utf-8"));
1088
- }
1089
- try {
1090
- const compiled = import_handlebars.default.compile(fs5.readFileSync(documentPath, "utf-8"));
1091
- return compiled(context);
1092
- } catch (error) {
1093
- throw new TemplateError(`Handlebars render error: ${error instanceof Error ? error.message : String(error)}`);
1094
- }
1095
- }
1096
-
1097
- // src/templates/liquid.ts
1098
- var fs6 = __toESM(require("fs"), 1);
1099
- var path4 = __toESM(require("path"), 1);
1100
- var import_liquidjs = require("liquidjs");
1101
- function createLiquidEngine(root) {
1102
- return new import_liquidjs.Liquid({
1103
- root: root ? [root] : [],
1104
- extname: ".liquid",
1105
- cache: false
1106
- });
1107
- }
1108
- function renderLiquid(template, context) {
1109
- const engine = createLiquidEngine();
1110
- try {
1111
- return engine.renderSync(engine.parse(template), context);
1112
- } catch (error) {
1113
- throw new TemplateError(`Liquid render error: ${error instanceof Error ? error.message : String(error)}`);
1114
- }
1115
- }
1116
- function renderLiquidFile(filePath, context) {
1117
- if (!fs6.existsSync(filePath)) {
1118
- throw new TemplateError(`Template file not found: ${filePath}`);
1119
- }
1120
- const template = fs6.readFileSync(filePath, "utf-8");
1121
- return renderLiquid(template, context);
1122
- }
1123
- function renderLiquidComposable(templateDir, context) {
1124
- const documentPath = path4.join(templateDir, "document.liquid");
1125
- if (!fs6.existsSync(documentPath)) {
1126
- throw new TemplateError(`Document template not found: ${documentPath}`);
1127
- }
1128
- const engine = createLiquidEngine(templateDir);
1129
- try {
1130
- return engine.renderFileSync("document", context);
1131
- } catch (error) {
1132
- throw new TemplateError(`Liquid render error: ${error instanceof Error ? error.message : String(error)}`);
1133
- }
1134
- }
1135
-
1136
- // src/templates/loader.ts
1137
- var fs7 = __toESM(require("fs"), 1);
1138
- var path5 = __toESM(require("path"), 1);
1139
- function getEngineFromFile(filePath) {
1140
- const ext = path5.extname(filePath).toLowerCase();
1141
- switch (ext) {
1142
- case ".liquid":
1143
- return "liquid";
1144
- case ".hbs":
1145
- case ".handlebars":
1146
- return "handlebars";
1147
- case ".ejs":
1148
- return "ejs";
1149
- default:
1150
- throw new TemplateError(`Unknown template extension: ${ext}`);
1151
- }
1152
- }
1153
- function getRenderFn(engine) {
1154
- switch (engine) {
1155
- case "liquid":
1156
- return renderLiquid;
1157
- case "handlebars":
1158
- return renderHandlebars;
1159
- case "ejs":
1160
- return renderEjs;
1161
- }
1162
- }
1163
- function getRenderFileFn(engine) {
1164
- switch (engine) {
1165
- case "liquid":
1166
- return renderLiquidFile;
1167
- case "handlebars":
1168
- return renderHandlebarsFile;
1169
- case "ejs":
1170
- return renderEjsFile;
1171
- }
1172
- }
1173
- function detectTemplateMode(templatePath) {
1174
- if (!fs7.existsSync(templatePath)) {
1175
- throw new TemplateError(`Template path not found: ${templatePath}`);
1176
- }
1177
- const stat = fs7.statSync(templatePath);
1178
- if (stat.isFile()) {
1179
- return "single";
1180
- }
1181
- if (stat.isDirectory()) {
1182
- return "composable";
1183
- }
1184
- throw new TemplateError(`Invalid template path: ${templatePath}`);
1185
- }
1186
- function renderSingleFile(templatePath, context, engine) {
1187
- const resolvedEngine = engine ?? getEngineFromFile(templatePath);
1188
- const renderFile = getRenderFileFn(resolvedEngine);
1189
- return {
1190
- content: renderFile(templatePath, context),
1191
- engine: resolvedEngine
1192
- };
1193
- }
1194
- function renderComposable(templateDir, context, engine) {
1195
- const files = fs7.readdirSync(templateDir);
1196
- const engineMap = {
1197
- liquid: { document: "document.liquid", version: "version.liquid", entry: "entry.liquid" },
1198
- handlebars: { document: "document.hbs", version: "version.hbs", entry: "entry.hbs" },
1199
- ejs: { document: "document.ejs", version: "version.ejs", entry: "entry.ejs" }
1200
- };
1201
- let resolvedEngine;
1202
- if (engine) {
1203
- resolvedEngine = engine;
1204
- } else {
1205
- const detected = detectEngineFromFiles(templateDir, files);
1206
- if (!detected) {
1207
- throw new TemplateError(`Could not detect template engine. Found files: ${files.join(", ")}`);
1208
- }
1209
- resolvedEngine = detected;
1210
- }
1211
- if (resolvedEngine === "liquid") {
1212
- return { content: renderLiquidComposable(templateDir, context), engine: resolvedEngine };
1213
- }
1214
- if (resolvedEngine === "handlebars") {
1215
- return { content: renderHandlebarsComposable(templateDir, context), engine: resolvedEngine };
1216
- }
1217
- const expectedFiles = engineMap[resolvedEngine];
1218
- const documentPath = path5.join(templateDir, expectedFiles.document);
1219
- if (!fs7.existsSync(documentPath)) {
1220
- throw new TemplateError(`Document template not found: ${expectedFiles.document}`);
1221
- }
1222
- const versionPath = path5.join(templateDir, expectedFiles.version);
1223
- const entryPath = path5.join(templateDir, expectedFiles.entry);
1224
- const render = getRenderFn(resolvedEngine);
1225
- const entryTemplate = fs7.existsSync(entryPath) ? fs7.readFileSync(entryPath, "utf-8") : null;
1226
- const versionTemplate = fs7.existsSync(versionPath) ? fs7.readFileSync(versionPath, "utf-8") : null;
1227
- if (entryTemplate && versionTemplate) {
1228
- const versionsWithEntries = context.versions.map((versionCtx) => {
1229
- const entries = versionCtx.entries.map((entry) => {
1230
- const entryCtx = { ...entry, packageName: versionCtx.packageName, version: versionCtx.version };
1231
- return render(entryTemplate, entryCtx);
1232
- });
1233
- return render(versionTemplate, { ...versionCtx, renderedEntries: entries });
1234
- });
1235
- const docContext = { ...context, renderedVersions: versionsWithEntries };
1236
- return {
1237
- content: render(fs7.readFileSync(documentPath, "utf-8"), docContext),
1238
- engine: resolvedEngine
1239
- };
1240
- }
1241
- return renderSingleFile(documentPath, context, resolvedEngine);
1242
- }
1243
- function detectEngineFromFiles(_dir, files) {
1244
- if (files.some((f) => f.endsWith(".liquid"))) return "liquid";
1245
- if (files.some((f) => f.endsWith(".hbs") || f.endsWith(".handlebars"))) return "handlebars";
1246
- if (files.some((f) => f.endsWith(".ejs"))) return "ejs";
1247
- return null;
1248
- }
1249
- function validateDocumentContext(context, templatePath) {
1250
- if (!context.project?.name) {
1251
- throw new TemplateError(`${templatePath}: DocumentContext missing required field "project.name"`);
1252
- }
1253
- if (!Array.isArray(context.versions)) {
1254
- throw new TemplateError(`${templatePath}: DocumentContext missing required field "versions" (must be an array)`);
1255
- }
1256
- const requiredVersionFields = ["packageName", "version", "date", "entries"];
1257
- for (const [i, v] of context.versions.entries()) {
1258
- for (const field of requiredVersionFields) {
1259
- if (v[field] === void 0 || v[field] === null) {
1260
- throw new TemplateError(`${templatePath}: versions[${i}] missing required field "${field}"`);
1261
- }
1262
- }
1263
- if (!Array.isArray(v.entries)) {
1264
- throw new TemplateError(`${templatePath}: versions[${i}].entries must be an array`);
1265
- }
1266
- }
1267
- }
1268
- function renderTemplate(templatePath, context, engine) {
1269
- validateDocumentContext(context, templatePath);
1270
- const mode = detectTemplateMode(templatePath);
1271
- if (mode === "single") {
1272
- return renderSingleFile(templatePath, context, engine);
1273
- }
1274
- return renderComposable(templatePath, context, engine);
1275
- }
1276
-
1277
- // src/core/pipeline.ts
1278
- var import_meta = {};
1279
- function generateCompareUrl(repoUrl, from, to) {
1280
- if (/gitlab\.com/i.test(repoUrl)) {
1281
- return `${repoUrl}/-/compare/${from}...${to}`;
1282
- }
1283
- if (/bitbucket\.org/i.test(repoUrl)) {
1284
- return `${repoUrl}/branches/compare/${from}..${to}`;
1285
- }
1286
- return `${repoUrl}/compare/${from}...${to}`;
1287
- }
1288
- function createTemplateContext(pkg) {
1289
- const compareUrl = pkg.repoUrl && pkg.previousVersion ? generateCompareUrl(pkg.repoUrl, pkg.previousVersion, pkg.version) : void 0;
1290
- return {
1291
- packageName: pkg.packageName,
1292
- version: pkg.version,
1293
- previousVersion: pkg.previousVersion,
1294
- date: pkg.date,
1295
- repoUrl: pkg.repoUrl,
1296
- entries: pkg.entries,
1297
- compareUrl
1298
- };
1299
- }
1300
- function createDocumentContext(contexts, repoUrl) {
1301
- const compareUrls = {};
1302
- for (const ctx of contexts) {
1303
- if (ctx.compareUrl) {
1304
- compareUrls[ctx.version] = ctx.compareUrl;
1305
- }
1306
- }
1307
- return {
1308
- project: {
1309
- name: contexts[0]?.packageName ?? "project",
1310
- repoUrl
1311
- },
1312
- versions: contexts,
1313
- compareUrls: Object.keys(compareUrls).length > 0 ? compareUrls : void 0
1314
- };
1315
- }
1316
- async function processWithLLM(context, config) {
1317
- if (!config.llm) {
1318
- return context;
1319
- }
1320
- const tasks = config.llm.tasks ?? {};
1321
- const llmContext = {
1322
- packageName: context.packageName,
1323
- version: context.version,
1324
- previousVersion: context.previousVersion ?? void 0,
1325
- date: context.date,
1326
- categories: config.llm.categories,
1327
- style: config.llm.style
1328
- };
1329
- const enhanced = {
1330
- entries: context.entries
1331
- };
1332
- try {
1333
- (0, import_core8.info)(`Using LLM provider: ${config.llm.provider}${config.llm.model ? ` (${config.llm.model})` : ""}`);
1334
- if (config.llm.baseURL) {
1335
- (0, import_core8.info)(`LLM base URL: ${config.llm.baseURL}`);
1336
- }
1337
- const rawProvider = createProvider(config.llm);
1338
- const retryOpts = config.llm.retry ?? LLM_DEFAULTS.retry;
1339
- const provider = {
1340
- name: rawProvider.name,
1341
- complete: (prompt, opts) => withRetry(() => rawProvider.complete(prompt, opts), retryOpts)
1342
- };
1343
- const activeTasks = Object.entries(tasks).filter(([, enabled]) => enabled).map(([name]) => name);
1344
- (0, import_core8.info)(`Running LLM tasks: ${activeTasks.join(", ")}`);
1345
- if (tasks.enhance && tasks.categorize) {
1346
- (0, import_core8.info)("Enhancing and categorizing entries with LLM...");
1347
- const result = await enhanceAndCategorize(provider, context.entries, llmContext);
1348
- enhanced.entries = result.enhancedEntries;
1349
- enhanced.categories = {};
1350
- for (const cat of result.categories) {
1351
- enhanced.categories[cat.category] = cat.entries;
1352
- }
1353
- (0, import_core8.info)(`Enhanced ${enhanced.entries.length} entries into ${result.categories.length} categories`);
1354
- } else {
1355
- if (tasks.enhance) {
1356
- (0, import_core8.info)("Enhancing entries with LLM...");
1357
- enhanced.entries = await enhanceEntries(provider, context.entries, llmContext, config.llm.concurrency);
1358
- (0, import_core8.info)(`Enhanced ${enhanced.entries.length} entries`);
1359
- }
1360
- if (tasks.categorize) {
1361
- (0, import_core8.info)("Categorizing entries with LLM...");
1362
- const categorized = await categorizeEntries(provider, enhanced.entries, llmContext);
1363
- enhanced.categories = {};
1364
- for (const cat of categorized) {
1365
- enhanced.categories[cat.category] = cat.entries;
1366
- }
1367
- (0, import_core8.info)(`Created ${categorized.length} categories`);
1368
- }
1369
- }
1370
- if (tasks.summarize) {
1371
- (0, import_core8.info)("Summarizing entries with LLM...");
1372
- enhanced.summary = await summarizeEntries(provider, enhanced.entries, llmContext);
1373
- if (enhanced.summary) {
1374
- (0, import_core8.info)("Summary generated successfully");
1375
- (0, import_core8.debug)(`Summary: ${enhanced.summary.substring(0, 100)}...`);
1376
- } else {
1377
- (0, import_core8.warn)("Summary generation returned empty result");
1378
- }
1379
- }
1380
- if (tasks.releaseNotes) {
1381
- (0, import_core8.info)("Generating release notes with LLM...");
1382
- enhanced.releaseNotes = await generateReleaseNotes(provider, enhanced.entries, llmContext);
1383
- if (enhanced.releaseNotes) {
1384
- (0, import_core8.info)("Release notes generated successfully");
1385
- } else {
1386
- (0, import_core8.warn)("Release notes generation returned empty result");
1387
- }
1388
- }
1389
- return {
1390
- ...context,
1391
- entries: enhanced.entries,
1392
- enhanced
1393
- };
1394
- } catch (error) {
1395
- (0, import_core8.warn)(`LLM processing failed: ${error instanceof Error ? error.message : String(error)}`);
1396
- (0, import_core8.warn)("Falling back to raw entries");
1397
- return context;
1398
- }
1399
- }
1400
- function getBuiltinTemplatePath(style) {
1401
- let packageRoot;
1402
- try {
1403
- const currentUrl = import_meta.url;
1404
- packageRoot = path6.dirname(new URL(currentUrl).pathname);
1405
- packageRoot = path6.join(packageRoot, "..", "..");
1406
- } catch {
1407
- packageRoot = __dirname;
1408
- }
1409
- return path6.join(packageRoot, "templates", style);
1410
- }
1411
- async function generateWithTemplate(contexts, config, outputPath, dryRun) {
1412
- let templatePath;
1413
- if (config.templates?.path) {
1414
- templatePath = path6.resolve(config.templates.path);
1415
- } else {
1416
- templatePath = getBuiltinTemplatePath("keep-a-changelog");
1417
- }
1418
- const documentContext = createDocumentContext(
1419
- contexts,
1420
- config.templates?.path ? void 0 : contexts[0]?.repoUrl ?? void 0
1421
- );
1422
- const result = renderTemplate(templatePath, documentContext, config.templates?.engine);
1423
- if (dryRun) {
1424
- (0, import_core8.info)("--- Changelog Preview ---");
1425
- console.log(result.content);
1426
- (0, import_core8.info)("--- End Preview ---");
1427
- return;
1428
- }
1429
- if (outputPath === "-") {
1430
- process.stdout.write(result.content);
1431
- return;
1432
- }
1433
- const dir = path6.dirname(outputPath);
1434
- if (!fs8.existsSync(dir)) {
1435
- fs8.mkdirSync(dir, { recursive: true });
1436
- }
1437
- fs8.writeFileSync(outputPath, result.content, "utf-8");
1438
- (0, import_core8.success)(`Changelog written to ${outputPath} (using ${result.engine} template)`);
1439
- }
1440
- async function runPipeline(input, config, dryRun) {
1441
- (0, import_core8.debug)(`Processing ${input.packages.length} package(s)`);
1442
- let contexts = input.packages.map(createTemplateContext);
1443
- if (config.llm && !process.env.CHANGELOG_NO_LLM) {
1444
- (0, import_core8.info)("Processing with LLM enhancement");
1445
- contexts = await Promise.all(contexts.map((ctx) => processWithLLM(ctx, config)));
1446
- }
1447
- for (const output of config.output) {
1448
- (0, import_core8.info)(`Generating ${output.format} output`);
1449
- switch (output.format) {
1450
- case "markdown": {
1451
- const file = output.file ?? "CHANGELOG.md";
1452
- if (config.templates?.path || output.options?.template) {
1453
- await generateWithTemplate(contexts, config, file, dryRun);
1454
- } else {
1455
- writeMarkdown(file, contexts, config, dryRun);
1456
- }
1457
- break;
1458
- }
1459
- case "json": {
1460
- const file = output.file ?? "changelog.json";
1461
- writeJson(file, contexts, dryRun);
1462
- break;
1463
- }
1464
- case "github-release": {
1465
- if (dryRun) {
1466
- (0, import_core8.info)("[DRY RUN] Would create GitHub release");
1467
- break;
1468
- }
1469
- const firstContext = contexts[0];
1470
- if (!firstContext) {
1471
- (0, import_core8.warn)("No context available for GitHub release");
1472
- break;
1473
- }
1474
- const repoUrl = firstContext.repoUrl;
1475
- if (!repoUrl) {
1476
- (0, import_core8.warn)("No repo URL available, cannot create GitHub release");
1477
- break;
1478
- }
1479
- const parsed = parseRepoUrl(repoUrl);
1480
- if (!parsed) {
1481
- (0, import_core8.warn)(`Could not parse repo URL: ${repoUrl}`);
1482
- break;
1483
- }
1484
- await createGitHubRelease(firstContext, {
1485
- owner: parsed.owner,
1486
- repo: parsed.repo,
1487
- draft: output.options?.draft,
1488
- prerelease: output.options?.prerelease
1489
- });
1490
- break;
1491
- }
1492
- }
1493
- }
1494
- }
1495
- async function processInput(inputJson, config, dryRun) {
1496
- const input = parsePackageVersioner(inputJson);
1497
- await runPipeline(input, config, dryRun);
1498
- }
1499
-
1500
- // src/monorepo/aggregator.ts
1501
- var fs9 = __toESM(require("fs"), 1);
1502
- var path7 = __toESM(require("path"), 1);
1503
- var import_core9 = require("@releasekit/core");
1504
-
1505
- // src/monorepo/splitter.ts
1506
- function splitByPackage(contexts) {
1507
- const byPackage = /* @__PURE__ */ new Map();
1508
- for (const ctx of contexts) {
1509
- byPackage.set(ctx.packageName, ctx);
1510
- }
1511
- return byPackage;
1512
- }
1513
-
1514
- // src/monorepo/aggregator.ts
1515
- function writeFile(outputPath, content, dryRun) {
1516
- if (dryRun) {
1517
- (0, import_core9.info)(`[DRY RUN] Would write to ${outputPath}`);
1518
- console.log(content);
1519
- return;
1520
- }
1521
- const dir = path7.dirname(outputPath);
1522
- if (!fs9.existsSync(dir)) {
1523
- fs9.mkdirSync(dir, { recursive: true });
1524
- }
1525
- fs9.writeFileSync(outputPath, content, "utf-8");
1526
- (0, import_core9.success)(`Changelog written to ${outputPath}`);
1527
- }
1528
- function aggregateToRoot(contexts) {
1529
- const aggregated = {
1530
- packageName: "monorepo",
1531
- version: contexts[0]?.version ?? "0.0.0",
1532
- previousVersion: contexts[0]?.previousVersion ?? null,
1533
- date: (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "",
1534
- repoUrl: contexts[0]?.repoUrl ?? null,
1535
- entries: []
1536
- };
1537
- for (const ctx of contexts) {
1538
- for (const entry of ctx.entries) {
1539
- aggregated.entries.push({
1540
- ...entry,
1541
- scope: entry.scope ? `${ctx.packageName}/${entry.scope}` : ctx.packageName
1542
- });
1543
- }
1544
- }
1545
- return aggregated;
1546
- }
1547
- function writeMonorepoChangelogs(contexts, options, config, dryRun) {
1548
- if (options.mode === "root" || options.mode === "both") {
1549
- const aggregated = aggregateToRoot(contexts);
1550
- const rootPath = path7.join(options.rootPath, "CHANGELOG.md");
1551
- (0, import_core9.info)(`Writing root changelog to ${rootPath}`);
1552
- const rootContent = config.updateStrategy === "prepend" && fs9.existsSync(rootPath) ? prependVersion(rootPath, aggregated) : renderMarkdown([aggregated]);
1553
- writeFile(rootPath, rootContent, dryRun);
1554
- }
1555
- if (options.mode === "packages" || options.mode === "both") {
1556
- const byPackage = splitByPackage(contexts);
1557
- const packageDirMap = buildPackageDirMap(options.rootPath, options.packagesPath);
1558
- for (const [packageName, ctx] of byPackage) {
1559
- const simpleName = packageName.split("/").pop();
1560
- const packageDir = packageDirMap.get(packageName) ?? (simpleName ? packageDirMap.get(simpleName) : void 0) ?? null;
1561
- if (packageDir) {
1562
- const changelogPath = path7.join(packageDir, "CHANGELOG.md");
1563
- (0, import_core9.info)(`Writing changelog for ${packageName} to ${changelogPath}`);
1564
- const pkgContent = config.updateStrategy === "prepend" && fs9.existsSync(changelogPath) ? prependVersion(changelogPath, ctx) : renderMarkdown([ctx]);
1565
- writeFile(changelogPath, pkgContent, dryRun);
1566
- } else {
1567
- (0, import_core9.info)(`Could not find directory for package ${packageName}, skipping`);
1568
- }
1569
- }
1570
- }
1571
- }
1572
- function buildPackageDirMap(rootPath, packagesPath) {
1573
- const map = /* @__PURE__ */ new Map();
1574
- const packagesDir = path7.join(rootPath, packagesPath);
1575
- if (!fs9.existsSync(packagesDir)) {
1576
- return map;
1577
- }
1578
- for (const entry of fs9.readdirSync(packagesDir, { withFileTypes: true })) {
1579
- if (!entry.isDirectory()) continue;
1580
- const dirPath = path7.join(packagesDir, entry.name);
1581
- map.set(entry.name, dirPath);
1582
- const packageJsonPath = path7.join(dirPath, "package.json");
1583
- if (fs9.existsSync(packageJsonPath)) {
1584
- try {
1585
- const pkg = JSON.parse(fs9.readFileSync(packageJsonPath, "utf-8"));
1586
- if (pkg.name) {
1587
- map.set(pkg.name, dirPath);
1588
- }
1589
- } catch {
1590
- }
1591
- }
1592
- }
1593
- return map;
1594
- }
1595
- function detectMonorepo(cwd) {
1596
- const pnpmWorkspacesPath = path7.join(cwd, "pnpm-workspace.yaml");
1597
- const packageJsonPath = path7.join(cwd, "package.json");
1598
- if (fs9.existsSync(pnpmWorkspacesPath)) {
1599
- const content = fs9.readFileSync(pnpmWorkspacesPath, "utf-8");
1600
- const packagesMatch = content.match(/packages:\s*\n\s*-\s*['"]([^'"]+)['"]/);
1601
- if (packagesMatch?.[1]) {
1602
- const packagesGlob = packagesMatch[1];
1603
- const packagesPath = packagesGlob.replace(/\/?\*$/, "").replace(/\/\*\*$/, "");
1604
- return { isMonorepo: true, packagesPath: packagesPath || "packages" };
1605
- }
1606
- return { isMonorepo: true, packagesPath: "packages" };
1607
- }
1608
- if (fs9.existsSync(packageJsonPath)) {
1609
- try {
1610
- const content = fs9.readFileSync(packageJsonPath, "utf-8");
1611
- const pkg = JSON.parse(content);
1612
- if (pkg.workspaces) {
1613
- const workspaces = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces.packages;
1614
- if (workspaces?.length) {
1615
- const firstWorkspace = workspaces[0];
1616
- if (firstWorkspace) {
1617
- const packagesPath = firstWorkspace.replace(/\/?\*$/, "").replace(/\/\*\*$/, "");
1618
- return { isMonorepo: true, packagesPath: packagesPath || "packages" };
1619
- }
1620
- }
1621
- }
1622
- } catch {
1623
- return { isMonorepo: false, packagesPath: "" };
1624
- }
1625
- }
1626
- return { isMonorepo: false, packagesPath: "" };
1627
- }
1628
- // Annotate the CommonJS export names for ESM import in node:
1629
- 0 && (module.exports = {
1630
- ChangelogCreatorError,
1631
- ConfigError,
1632
- EXIT_CODES,
1633
- GitHubError,
1634
- InputParseError,
1635
- LLMError,
1636
- NotesError,
1637
- TemplateError,
1638
- aggregateToRoot,
1639
- createTemplateContext,
1640
- detectMonorepo,
1641
- getDefaultConfig,
1642
- getExitCode,
1643
- loadAuth,
1644
- loadConfig,
1645
- parsePackageVersioner,
1646
- parsePackageVersionerFile,
1647
- parsePackageVersionerStdin,
1648
- processInput,
1649
- renderJson,
1650
- renderMarkdown,
1651
- runPipeline,
1652
- saveAuth,
1653
- writeJson,
1654
- writeMarkdown,
1655
- writeMonorepoChangelogs
1656
- });