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