@kaynooo/cli-changelog 0.0.0-stage → 2.4.2
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/LICENSE +21 -0
- package/README.md +212 -2
- package/dist/cli.js +84 -0
- package/package.json +42 -4
- package/src/changelog.ts +150 -0
- package/src/cli.ts +298 -0
- package/src/config.ts +147 -0
- package/src/discord.ts +158 -0
- package/src/flags.ts +92 -0
- package/src/generate.ts +23 -0
- package/src/git.ts +166 -0
- package/src/gitea.ts +326 -0
- package/src/highlights.ts +142 -0
- package/src/index.ts +9 -0
- package/src/markdown.ts +199 -0
- package/src/parse.ts +8 -0
- package/src/types.ts +185 -0
- package/src/ui.ts +20 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Anthony Fu <https://github.com/antfu>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,213 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kaynooo/cli-changelog
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Generate changelog for Forgejo, Gitea or GitHub releases from [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/), and post it to Discord.
|
|
4
|
+
|
|
5
|
+
> **Bun only.** This tool runs on [Bun](https://bun.sh) and uses Bun-native APIs (`Bun.$`, `Bun.file`, `Bun.Glob`, global `fetch`). It is not meant to run under Node.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- Support exclamation mark as breaking change, e.g. `chore!: drop node v10`
|
|
10
|
+
- Grouped scope in changelog
|
|
11
|
+
- Issues linked from the subject (`#12`) and from `#12 - title` lines in the commit body
|
|
12
|
+
- Create the release note, or update the existing one
|
|
13
|
+
- Post the release to a Discord webhook
|
|
14
|
+
- Open the notes with the release's section of a hand-written "what's new" page
|
|
15
|
+
- List contributors with their avatars
|
|
16
|
+
- Upload assets to the release
|
|
17
|
+
|
|
18
|
+
## Format
|
|
19
|
+
|
|
20
|
+
A note opens with a one-line summary (`3 new · 3 fixed · 6 maintenance · by @kaynooo · v1.5.0 → v1.6.6`), then lists:
|
|
21
|
+
|
|
22
|
+
- **⚠️ Breaking**, **✨ New**, **🔧 Fixed** and **⚡ Faster**, each line ending with its commit and issue links
|
|
23
|
+
- refactor, docs, build, types, test, style and ci commits folded into one collapsed **🧹 Maintenance** block
|
|
24
|
+
- the contributors' avatars and a link to the full diff
|
|
25
|
+
|
|
26
|
+
A type set to `{ title, folded: true }` in `types` joins the maintenance block, and `titles.maintenance` renames it.
|
|
27
|
+
|
|
28
|
+
With [`highlights`](#open-the-notes-with-highlights), a **🌟 Highlights** section comes right after the summary.
|
|
29
|
+
|
|
30
|
+
## Discord
|
|
31
|
+
|
|
32
|
+
Once the release is out, it is posted to the webhook in `DISCORD_WEBHOOK` (or `discordWebhook` / `--discord-webhook`) as one embed: the same sections with each issue's title beside it, maintenance as a count line, and links to the full note and the diff. A note too long for Discord's 4096 characters ends with `…and N more`. Nothing is posted when no webhook is set.
|
|
33
|
+
|
|
34
|
+
```yml
|
|
35
|
+
- run: bunx @kaynooo/cli-changelog
|
|
36
|
+
env:
|
|
37
|
+
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
|
38
|
+
DISCORD_WEBHOOK: ${{secrets.DISCORD_WEBHOOK}}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Forge
|
|
42
|
+
|
|
43
|
+
A repo whose origin is on github.com releases to GitHub, with `GITHUB_TOKEN` or else `gh auth token`. Any other repo releases to Forgejo or Gitea at the `forge` host of `~/.config/kaynooo-cli/config.json`, or at origin's host when that is unset. `baseUrl` and `provider` (`gitea` or `github`) in the config override both.
|
|
44
|
+
|
|
45
|
+
## Usage
|
|
46
|
+
|
|
47
|
+
In Forgejo, Gitea or GitHub Actions (under `.github/workflows/` on GitHub):
|
|
48
|
+
|
|
49
|
+
```yml
|
|
50
|
+
# .gitea/workflows/release.yml
|
|
51
|
+
|
|
52
|
+
name: Release
|
|
53
|
+
|
|
54
|
+
permissions:
|
|
55
|
+
contents: write
|
|
56
|
+
|
|
57
|
+
on:
|
|
58
|
+
push:
|
|
59
|
+
tags:
|
|
60
|
+
- 'v*'
|
|
61
|
+
|
|
62
|
+
jobs:
|
|
63
|
+
release:
|
|
64
|
+
runs-on: ubuntu-latest
|
|
65
|
+
steps:
|
|
66
|
+
- uses: actions/checkout@v4
|
|
67
|
+
with:
|
|
68
|
+
fetch-depth: 0
|
|
69
|
+
|
|
70
|
+
- name: Setup Bun
|
|
71
|
+
uses: oven-sh/setup-bun@v2
|
|
72
|
+
with:
|
|
73
|
+
bun-version: latest
|
|
74
|
+
|
|
75
|
+
- run: bunx @kaynooo/cli-changelog
|
|
76
|
+
env:
|
|
77
|
+
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
It will be triggered whenever you push a tag that starts with `v`.
|
|
81
|
+
|
|
82
|
+
## Configuration
|
|
83
|
+
|
|
84
|
+
Put a `changelog.config.{ts,mts,js,mjs,json}` file in the project root, or a `changelog` field in `package.json`. CLI flags override the file, which overrides `package.json`.
|
|
85
|
+
|
|
86
|
+
### Roll up patches into minor releases
|
|
87
|
+
|
|
88
|
+
If you cut several patches between minor releases, `rollup` makes a minor (or major) note list every commit since the previous minor (or major), instead of only since the last patch:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
// changelog.config.ts
|
|
92
|
+
import { defineConfig } from '@kaynooo/cli-changelog'
|
|
93
|
+
|
|
94
|
+
export default defineConfig({
|
|
95
|
+
rollup: {
|
|
96
|
+
// On a `x.y.0` release, start from the previous `x.(y-1).0` tag,
|
|
97
|
+
// absorbing every patch in between.
|
|
98
|
+
minor: true,
|
|
99
|
+
// On a `x.0.0` release, start from the previous `(x-1).0.0` tag,
|
|
100
|
+
// absorbing every minor and patch in between.
|
|
101
|
+
major: true,
|
|
102
|
+
},
|
|
103
|
+
})
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Both default to `false`.
|
|
107
|
+
|
|
108
|
+
### Follow only the first parent
|
|
109
|
+
|
|
110
|
+
After a `git merge --allow-unrelated-histories` (or any big merge), the note would list every commit the merge brought in. `firstParent` walks only the first parent of each merge, so the merge shows as itself:
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
// changelog.config.ts
|
|
114
|
+
import { defineConfig } from '@kaynooo/cli-changelog'
|
|
115
|
+
|
|
116
|
+
export default defineConfig({
|
|
117
|
+
firstParent: true,
|
|
118
|
+
})
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
It defaults to `false`. The tag the range starts from and the first commit are also looked up along the first parent.
|
|
122
|
+
|
|
123
|
+
This also drops the commits of a feature branch merged with a merge commit: only the merge's own message is read. It suits repos that squash or fast-forward, plus a one-off import.
|
|
124
|
+
|
|
125
|
+
### Open the notes with highlights
|
|
126
|
+
|
|
127
|
+
Commit lines say what changed, not why it matters. `highlights` points at a Markdown page you write by hand, one `## <version>` section per release, and opens the notes with the section of the version being released, under **🌟 Highlights**, ending on a link to it:
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
// changelog.config.ts
|
|
131
|
+
import { defineConfig } from '@kaynooo/cli-changelog'
|
|
132
|
+
|
|
133
|
+
export default defineConfig({
|
|
134
|
+
highlights: {
|
|
135
|
+
file: 'docs/whats-new.md',
|
|
136
|
+
url: 'https://docs.example.com/whats-new/',
|
|
137
|
+
},
|
|
138
|
+
})
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
```md
|
|
142
|
+
## 1.4.0
|
|
143
|
+
|
|
144
|
+
- `render` prints a page without a server: see [the CLI](/reference/cli#render).
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
- The section is found by the version without the tag's prefix: `## 1.4.0` for `v1.4.0`. It runs to the next `## ` heading; its own headings are demoted one level, and the page's frontmatter is skipped.
|
|
148
|
+
- Links resolve against `url`, so `/reference/cli` becomes `https://docs.example.com/reference/cli`. When the site serves a page elsewhere than its file, `link` maps each target as written before it resolves, `undefined` keeping it: `link: target => target.replace(/\.md(?=#|$)/, '')` turns `cli.md#render` into `cli#render`. The closing link goes to the version's heading on the page, slugged as GitHub does (`#140`).
|
|
149
|
+
- The Discord post opens with the same section, its headings in bold. When the post runs past Discord's limit, commits are dropped first, then the section's last lines, the link to the page always kept.
|
|
150
|
+
- Without the file or a section for the version, the notes are as they would be without the option. `titles.highlights` renames the section.
|
|
151
|
+
|
|
152
|
+
## Preview Locally
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
bunx @kaynooo/cli-changelog --dry-run
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## JSON output
|
|
159
|
+
|
|
160
|
+
`--json` prints the result as JSON on stdout and nothing else: the progress goes to stderr, and a failure is `{"error": "...", "hint"?: "..."}` on stderr with the usual exit code.
|
|
161
|
+
|
|
162
|
+
`changelog --json` (also with `--dry-run` or `--output`):
|
|
163
|
+
|
|
164
|
+
```json
|
|
165
|
+
{ "command": "release", "status": "released", "from": "v1.4.2", "to": "main", "commits": 3, "notes": "...", "url": "https://git.example.org/o/r/releases/tag/v1.4.3", "output": null, "assetsFailed": 0, "discord": null }
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`status` is `released`, `dry-run` or `saved`; `url` is the release page once released, `output` the file written by `--output`, `discord` is `posted`, `failed` or `null` without a webhook. The exit code is 1 when an asset upload or the Discord post failed, with the report still printed.
|
|
169
|
+
|
|
170
|
+
`changelog undo --json` asks no question, so removing something needs `--yes` (or `--dry-run`, exit 2 otherwise) and the release note goes only with `--note`:
|
|
171
|
+
|
|
172
|
+
```json
|
|
173
|
+
{ "command": "undo", "status": "undone", "tag": "v1.4.2", "releaseNote": false, "remoteTag": true, "localTag": true, "commitReset": { "hash": "...", "subject": "chore: release v1.4.2" } }
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
`status` is `undone`, `nothing`, `dry-run` or `declined`; each flag says whether that step was taken (or, on a dry run, would be), and `commitReset` is `null` when the commit is left alone.
|
|
177
|
+
|
|
178
|
+
## Undo a Release
|
|
179
|
+
|
|
180
|
+
Rolled a bad release? `undo` deletes the remote tag, the local tag, and soft-resets the version-bump commit (changes are kept in your working tree). The commit is only reset when the tag points at `HEAD`.
|
|
181
|
+
|
|
182
|
+
```bash
|
|
183
|
+
bunx @kaynooo/cli-changelog undo v1.4.2
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
The tag is optional - omit it to undo the latest tag (you'll be warned which one):
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
bunx @kaynooo/cli-changelog undo
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
The Gitea release note is **not** removed by default - you're asked about it interactively. Pass `--note` to include it non-interactively.
|
|
193
|
+
|
|
194
|
+
| Flag | Description |
|
|
195
|
+
| ----------------- | ----------------------------------------------------------------------------------- |
|
|
196
|
+
| `--note` | Also delete the Gitea release note (skips the question) |
|
|
197
|
+
| `--dry-run` | Preview what would be removed, without deleting (`--dry` is kept as an alias) |
|
|
198
|
+
| `--yes` | Skip confirmation prompts (for CI/scripts) |
|
|
199
|
+
| `-r`, `--repo` | Repository to undo in, e.g. `kaynooo/cli` (`--gitea` is kept as an alias) |
|
|
200
|
+
|
|
201
|
+
The short `-t` for `--token` was removed, pass `--token` or set `GITHUB_TOKEN`.
|
|
202
|
+
|
|
203
|
+
## Why?
|
|
204
|
+
|
|
205
|
+
I used to use [`conventional-github-releaser`](https://github.com/conventional-changelog/releaser-tools/tree/master/packages/conventional-github-releaser) for almost all my projects. Until I found that it [does NOT support using exclamation marks for breaking changes](https://github.com/conventional-changelog/conventional-changelog/issues/648) - hiding those important breaking changes in the changelog without the awareness from maintainers.
|
|
206
|
+
|
|
207
|
+
## Credits
|
|
208
|
+
|
|
209
|
+
This is a Gitea / Forgejo port of [`changelogithub`](https://github.com/antfu/changelogithub) by [Anthony Fu](https://github.com/antfu).
|
|
210
|
+
|
|
211
|
+
## License
|
|
212
|
+
|
|
213
|
+
[MIT](./LICENSE) License © 2022 [Anthony Fu](https://github.com/antfu)
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
// @bun 2>/dev/null; exec bun --config=/dev/null "$0" "$@"
|
|
3
|
+
var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};var M,n;var init_chunk_yfkscv18=__esm(()=>{M=new TextDecoder("utf-8",{fatal:!0}),n={y:31536000000,M:2592000000,w:604800000,d:86400000,h:3600000,m:60000,s:1000}});function d(t){return t.charAt(0).toUpperCase()+t.slice(1)}function G(t,e,{plural:r,zero:n="singular"}={}){if(e===1||e===0&&n==="singular")return t;if(r!==void 0)return r;if(t.endsWith("y")&&!ct.test(t))return`${t.slice(0,-1)}ies`;if(t.endsWith("s")||t.endsWith("x")||t.endsWith("z")||t.endsWith("ch")||t.endsWith("sh"))return`${t}es`;if(Ot.test(t))return`${t.slice(0,-1)}ves`;return Gt.test(t)?`${t.slice(0,-2)}ves`:`${t}s`}var ct,Ot,Gt,be;var init_chunk_rkhsft4a=__esm(()=>{ct=/[aeiou]y$/;Ot=/(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/,Gt=/(?:knife|life|wife)$/;be=new Map(["\u20AC","","\u201A","\u0192","\u201E","\u2026","\u2020","\u2021","\u02C6","\u2030","\u0160","\u2039","\u0152","","\u017D","","","\u2018","\u2019","\u201C","\u201D","\u2022","\u2013","\u2014","\u02DC","\u2122","\u0161","\u203A","\u0153","","\u017E","\u0178"].map((t,e)=>[t,128+e]).filter(([t])=>t))});var init_text=__esm(()=>{init_chunk_rkhsft4a()});import process2 from"process";function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process2.stdout,env=process2.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}function isInteractive(streams=process2){return streams.stdin?.isTTY===!0&&streams.stderr?.isTTY===!0}var MODES,AGENT_VARIABLES;var init_mode=__esm(()=>{MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"]});function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var G2,B,h,o;var init_chunk_x450vn3m=__esm(()=>{G2=/^[a-f0-9]+$/i;B={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49],rgb:(r,e,l,n="fg")=>[`${n==="fg"?38:48};2;${r};${e};${l}`,n==="fg"?39:49],hex:(r,e="fg")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);o=Fe()});var init_colors=__esm(()=>{init_chunk_x450vn3m()});import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process3 from"process";function findUp(names,from=process3.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}var init_config=__esm(()=>{init_args()});import{existsSync as existsSync2,readFileSync}from"fs";import{homedir}from"os";import{isAbsolute,join as join2}from"path";import process4 from"process";function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process4.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function userConfigReadPath(bin,legacy=[],where={}){let current=userConfigPath(bin,where);if(existsSync2(current))return current;let base=configBase(where);return legacy.map((parts)=>join2(base,...parts)).find((path)=>existsSync2(path))??current}function readUserConfig(bin,where={},legacy=[]){let path=userConfigReadPath(bin,legacy,where);if(!existsSync2(path))return{};try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8"));return typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:{}}catch{return{}}}function configuredForge(where={}){let value=readUserConfig("config",where).forge;if(typeof value!=="string"||value.trim()==="")return;let url=(URL_SCHEME.test(value.trim())?value.trim():`https://${value.trim()}`).replace(TRAILING_SLASHES,"");return URL.canParse(url)?{host:new URL(url).host,url}:void 0}var URL_SCHEME,TRAILING_SLASHES;var init_user_config=__esm(()=>{URL_SCHEME=/^[a-z][a-z\d+.-]*:\/\//i,TRAILING_SLASHES=/\/+$/});import{existsSync as existsSync3,readFileSync as readFileSync2,statSync}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process5 from"process";function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process5.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=JSON.parse(readFileSync2(path,"utf8"));if(isRecord(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}function warnOnce(message){if(warned.has(message))return;warned.add(message),console.error(`warning: theme ${message}`)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process5.env,from=process5.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}function activeTheme(){let key=`${process5.cwd()}\x00${process5.env.KIT_THEME??""}\x00${process5.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var DEFAULT,BRIGHT,LIGHT,MONO,ASCII,PRESETS,STYLES,HEX,CONTROL,MAX_FILE_BYTES=65536,SPACES,CUBE,warned,current,currentKey="";var init_theme=__esm(()=>{init_config();init_user_config();DEFAULT={colors:{accent:"cyan",id:"yellow",path:"blue",label:"dim",value:"bold",ok:"green",warn:"yellow",problem:"red",note:"dim",plan:"magenta",passed:"green",failed:"red",running:"cyan",queued:"yellow",skipped:"dim"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",rule:"\u2500",corner:"\u256D",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",ok:"greenBright",warn:"yellowBright",problem:"redBright",note:"white",plan:"magentaBright",passed:"greenBright",failed:"redBright",running:"cyanBright",queued:"yellowBright",skipped:"white"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},MONO={accent:"bold",id:"bold",path:"underline",label:"dim",value:"bold",ok:"bold",warn:"bold",problem:"bold",note:"dim",plan:"dim",passed:"bold",failed:"bold",running:"bold",queued:"dim",skipped:"dim"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",rule:"-",corner:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},STYLES=new Set(["bold","dim","italic","underline","inverse","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,SPACES=/\s+/;CUBE=[0,95,135,175,215,255];warned=new Set});import process6 from"process";function takesControlCodes(stream,env=process6.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process6.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function role(name,stream,env=process6.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}var STATUS_WORDS,STATUS_OF;var init_style=__esm(()=>{init_colors();init_mode();init_theme();STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])))});function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}var ESC,ESCAPE_CODE,RESET_STYLE,CLOSE_LINK;var init_text2=__esm(()=>{ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`});import process7 from"process";function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function textWidth(text){return Bun.stringWidth(text)}function jsonText(value,replacer,{stream=process7.stdout,env=process7.env}={}){return JSON.stringify(value,replacer,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}var UNITS;var init_format=__esm(()=>{init_mode();init_style();init_text2();init_theme();UNITS=[["d",86400],["h",3600],["m",60],["s",1]]});import process8 from"process";function usageLine(usage,colors=paint(process8.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
4
|
+
`),blank=lines.indexOf(""),synopses=blank===-1?lines:lines.slice(0,blank),details=blank===-1?[]:lines.slice(blank+1),colon=synopses[0].indexOf(": "),inline=synopses[0].slice(colon+2),summary=colon===-1?details.shift():`${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;if(colon!==-1)synopses[0]=synopses[0].slice(0,colon);let head=`${colors.bold("Usage:")} ${synopses.map((line)=>line.replaceAll(OPTIONAL,(part)=>colors.dim(part))).join(`
|
|
5
|
+
`)}`,lead=summary===void 0||!withSummary?[]:["",colors.bold(prose(summary,colors))],rest=details.length===0?[]:["",...details.map((line)=>prose(line,colors))];return[head,...lead,...rest].join(`
|
|
6
|
+
`)}function prose(line,colors){if(colors.cyan("x")==="x")return line;return line.replaceAll(PROSE_MARKS,(match,code,flag)=>code===void 0?colors.cyan(flag??match):colors.bold(code))}function helpText(usage,options,colors=paint(process8.stdout),{examples=[],exits=[],bin,columns}={}){let{summary}=description(usage);return[...bin===void 0?[usageLine(usage,colors)]:[`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary===""?"":` ${summary}`}`,"",usageLine(usage,colors,{summary:!1})],"",colors.bold("Options:"),...optionRows(options,colors,columns),...exitRows(exits,colors),...exampleRows(examples,colors)].join(`
|
|
7
|
+
`)}function exitRows(exits,colors=paint(process8.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process8.env){return env.KIT_HELP==="json"}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
|
|
8
|
+
`),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}function exampleRows(examples,colors=paint(process8.stdout)){if(examples.length===0||outputMode()==="agent")return[];return["",colors.bold("Examples:"),...examples.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}function wrapText(text,limit){if(text.length<=limit)return[text];let lines=[],current="";for(let word of text.split(" "))if(current==="")current=word;else if(current.length+1+word.length<=limit)current=`${current} ${word}`;else lines.push(current),current=word;if(current!=="")lines.push(current);return lines}function optionRows(options,colors=paint(process8.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapText(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}var OPTIONAL,USAGE_PREFIX,FULL_STOP,PROSE_MARKS,MAX_INLINE_CHOICES=24;var init_help=__esm(()=>{init_mode();init_style();OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi});var init_input=__esm(()=>{init_args()});import process9 from"process";import{parseArgs}from"util";function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}function badUsage(message){throw new UsageError(message)}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}function applyOutput(color,plain,env=process9.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(own,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process9.stdout)?process9.stdout.columns:void 0;throw console.log(wantsHelpJson()?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}var DASHES,EXIT,Exit,UsageError,HelpShown,completion,heading,OUTPUT_OPTIONS,UNKNOWN_OPTION;var init_args=__esm(()=>{init_format();init_help();init_style();init_text2();init_help();init_input();DASHES=/^-+/;EXIT=Symbol.for("@kaynooo/cli-kit/Exit");Exit=class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}};UsageError=class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}};HelpShown=class HelpShown extends Exit{constructor(){super("help shown",0)}};completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};UNKNOWN_OPTION=/^unknown option '(-[^']+)'/});var init_folders=__esm(()=>{init_user_config()});var init_answers=__esm(()=>{init_folders()});import process16 from"process";function stopJob(){process16.kill(0,"SIGTSTP")}var init_job=()=>{};function isEditKey(key){return EDIT_KEYS.has(key)}var EDIT_KEYS;var init_line=__esm(()=>{EDIT_KEYS=new Set(["left","right","wordleft","wordright","linestart","lineend","erase","delete","word","killword","killnext","clear","killend","yank"])});var NONE;var init_score=__esm(()=>{NONE=Number.NEGATIVE_INFINITY});function repeat(value,count){return Array.from({length:count}).fill(value)}function parseKeys(input,paste={active:!1},ctrls=[]){let codes=new Map(ctrls.map((name)=>[String.fromCharCode(name.codePointAt(name.length-1)-96),name]));return(input.match(KEY_SEQUENCES)??[]).flatMap((sequence)=>{let wheel=MOUSE.exec(sequence)?.[1];if(wheel!==void 0)return repeat(wheel==="64"?"up":"down",wheel==="64"||wheel==="65"?WHEEL_LINES:0);let named=codes.get(sequence),key=named===void 0?KEYS[sequence]:{ctrl:named};if(sequence===PASTE_START||sequence===PASTE_END)return paste.active=sequence===PASTE_START,[];if(paste.active&&(sequence==="\r"||sequence===`
|
|
9
|
+
`))return[];if(key!==void 0)return[key];return IS_CONTROL.test(sequence)||sequence.startsWith("\x1B")?[]:[{text:sequence}]})}var IS_CONTROL,PASTE_START="\x1B[200~",PASTE_END="\x1B[201~",KEY_SEQUENCES,MOUSE,WHEEL_LINES=3,KEYS;var init_state=__esm(()=>{init_text2();init_line();init_score();IS_CONTROL=/[\x00-\x1F\x7F-\x9F]/,KEY_SEQUENCES=/\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu,MOUSE=/^\x1B\[<(\d+);\d+;\d+[a-z]$/i,KEYS={"\x1B[A":"up","\x1BOA":"up","\x10":"up","\x1B[B":"down","\x1BOB":"down","\x0E":"down","\x1B[5~":"pageup","\x1B[6~":"pagedown","\x1B[H":"home","\x1B[1~":"home","\x1BOH":"home","\x1B[F":"end","\x1B[4~":"end","\x1BOF":"end","\r":"enter","\n":"enter","\x03":"cancel","\x1B":"cancel","\x1B[D":"left","\x1BOD":"left","\x1B[C":"right","\x1BOC":"right","\x1B[1;5D":"wordleft","\x1B[1;3D":"wordleft","\x1Bb":"wordleft","\x1B[1;5C":"wordright","\x1B[1;3C":"wordright","\x1Bf":"wordright","\x01":"linestart","\x05":"lineend","\x7F":"erase","\x1B[3~":"delete","\b":"killword","\x1B\x7F":"killword","\x1B[3;5~":"killnext","\x1Bd":"killnext","\x15":"clear","\v":"killend","\x17":"word","\x19":"yank","\x1A":"suspend","\t":"tab","\x1F":"help","\x1BOP":"help","\x1B[11~":"help"}});function overwrite(lines,columns){return lines.map((line)=>textWidth(line)%columns===0?`\x1B[2K${line}`:`${line}\x1B[K`).join(`
|
|
10
|
+
`)}function rowsTaken(lines,columns){return lines.reduce((rows,line)=>rows+Math.max(1,Math.ceil(textWidth(line)/columns)),0)}var SYNC_START="\x1B[?2026h",SYNC_END="\x1B[?2026l";var init_redraw=__esm(()=>{init_format()});import process17 from"process";function readKeys(input,paste={active:!1}){return parseKeys(input,paste).filter((key)=>typeof key==="object"?"text"in key:PROMPT_KEYS.has(key)||isEditKey(key))}async function confirm(question,{default:fallback,...settings}={}){let answered=fallback,choices={true:"Y/n",false:"y/N",undefined:"y/n"}[String(fallback)];return await ask(question,settings,(colors,state)=>[state==="asking"?asking(colors,question,"",choices):answer(colors,question,state,answered?"yes":"no")],(key)=>{if(key==="cancel")return"cancel";if(key==="enter")return answered===void 0?void 0:"enter";let letter=typeof key==="object"?key.text.toLowerCase():"";if(letter!=="y"&&letter!=="n")return;return answered=letter==="y","enter"})?answered:void 0}function asking(colors,question,typed,keys){return`${colors.cyan("?")} ${question} ${typed===""?colors.dim(`(${keys})`):typed}`}function answer(colors,question,state,picked){return state==="enter"?`${colors.green("\u2713")} ${question} ${colors.cyan(picked)}`:`${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`}async function ask(question,{hint,terminal=process17},render,press){let{stdin,stderr}=terminal;if(!isInteractive(terminal))fail(`cannot ask "${question}" off a terminal`,2,hint);let colors=paint(stderr),current="asking",outcome,columns=()=>stderr.columns||80,draw=(state,last=!1)=>{let frame=render(colors,state,{columns:columns(),rows:stderr.rows||24}),rows=rowsTaken(frame,columns());stderr.write(`${SYNC_START}\r${overwrite(frame,columns())}\x1B[0J${last||rows<2?"":`\x1B[${rows-1}A`}${last?"":"\r"}${SYNC_END}`),current=state},redraw=()=>draw(current),paste={active:!1},stop=terminal.stop??(terminal===process17?stopJob:void 0),suspend=()=>{if(stop===void 0)return;stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l"),stdin.setRawMode(!1),stop(),stdin.setRawMode(!0),stderr.write("\x1B[?25l\x1B[?2004h")};try{return stderr.on?.("resize",redraw),stdin.setRawMode(!0),stdin.resume(),stderr.write("\x1B[?25l\x1B[?2004h"),draw("asking"),await new Promise((resolve)=>{function onData(data){for(let key of readKeys(data.toString(),paste)){if(key==="suspend"){suspend();continue}let pressed=press(key);if(pressed!==void 0){settle(pressed);return}}draw("asking")}function onEnd(){settle("cancel")}function settle(settled){outcome=settled,stdin.off("data",onData),stdin.off("end",onEnd),resolve(settled==="enter")}stdin.on("data",onData),stdin.on("end",onEnd)})}finally{stderr.off?.("resize",redraw),draw(outcome??"cancel",!0),stderr.write(`
|
|
11
|
+
\x1B[?25h\x1B[?2004l`),stdin.setRawMode(!1),stdin.pause()}}var PROMPT_KEYS;var init_prompt=__esm(()=>{init_answers();init_args();init_format();init_job();init_mode();init_line();init_state();init_redraw();init_style();PROMPT_KEYS=new Set(["up","down","pageup","pagedown","home","end","enter","cancel","suspend","tab"])});import{tmpdir}from"os";import{join as join9}from"path";init_args();import{readFileSync as readFileSync3,realpathSync}from"fs";import{resolve as resolve3}from"path";import process10 from"process";function commandLine(){try{return readFileSync3("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve3(word))}catch{return}}function scriptArgs(argv=process10.argv.slice(2),cmdline=commandLine(),script=process10.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve3(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}init_format();init_mode();init_style();init_theme();init_args();init_format();init_format();init_style();init_text2();init_theme();init_style();init_format();init_args();import{readFileSync as readFileSync5,realpathSync as realpathSync2}from"fs";import{dirname as dirname3,join as join5}from"path";import process14 from"process";import process11 from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process11.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process11.env.SSH_ASKPASS_PROMPT==="none"?{notice:!0}:{}},{promise,resolve}=Promise.withResolvers(),received="";try{await Bun.connect({unix:socketPath,socket:{open:(socket)=>void socket.write(`${JSON.stringify(request)}
|
|
12
|
+
`),data:(_,chunk)=>{received+=chunk.toString()},close:()=>resolve(received),error:()=>resolve("")}})}catch{return 1}let reply=await promise;if(reply==="")return 1;let{answer}=JSON.parse(reply);if(request.notice===!0)return 0;if(answer===void 0)return 1;return process11.stdout.write(`${answer}
|
|
13
|
+
`),0}var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
|
|
14
|
+
functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
|
|
15
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
16
|
+
set -l current (commandline -ct)
|
|
17
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
18
|
+
if test "$line" = __files__
|
|
19
|
+
__fish_complete_path $current
|
|
20
|
+
else
|
|
21
|
+
echo $line
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
${bins.map((bin)=>`complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
26
|
+
`).join("")}`;if(shell==="bash")return`${header}
|
|
27
|
+
__kaynooo_cli_complete() {
|
|
28
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
29
|
+
local -a lines
|
|
30
|
+
COMPREPLY=()
|
|
31
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
32
|
+
for line in "\${lines[@]}"; do
|
|
33
|
+
if [[ $line == __files__ ]]; then
|
|
34
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
35
|
+
else
|
|
36
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
37
|
+
fi
|
|
38
|
+
done
|
|
39
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
40
|
+
}
|
|
41
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
42
|
+
`;return`${header}
|
|
43
|
+
__kaynooo_cli_complete() {
|
|
44
|
+
local line
|
|
45
|
+
local -a described plain
|
|
46
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
47
|
+
if [[ $line == __files__ ]]; then
|
|
48
|
+
_files
|
|
49
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
50
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
51
|
+
else
|
|
52
|
+
plain+=("$line")
|
|
53
|
+
fi
|
|
54
|
+
done
|
|
55
|
+
(( \${#described} )) && _describe -V value described
|
|
56
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
57
|
+
return 0
|
|
58
|
+
}
|
|
59
|
+
__kaynooo_cli_register() {
|
|
60
|
+
add-zsh-hook -d precmd __kaynooo_cli_register
|
|
61
|
+
(( $+functions[compdef] )) || { autoload -Uz compinit && compinit }
|
|
62
|
+
compdef __kaynooo_cli_complete $__kaynooo_cli_bins
|
|
63
|
+
}
|
|
64
|
+
autoload -Uz add-zsh-hook
|
|
65
|
+
add-zsh-hook precmd __kaynooo_cli_register
|
|
66
|
+
typeset -gaU __kaynooo_cli_bins
|
|
67
|
+
__kaynooo_cli_bins+=(${bins.join(" ")})
|
|
68
|
+
`}init_format();init_mode();import process12 from"process";var NOTIFY_AFTER_MS=1e4,CANCELLED=130;function base64(text){return Buffer.from(text).toString("base64")}function sanitizeOsc(text){return text.replaceAll(/[\x00-\x1F\x7F;]/g," ")}function wrapTmux(codes,env){return codes.map((code)=>env.TMUX===void 0||env.TMUX===""?code:`\x1BPtmux;${code.replaceAll("\x1B","\x1B\x1B")}\x1B\\`).join("")}function notification(title,body,env=process12.env){let program=env.TERM_PROGRAM??"",term=env.TERM??"";if(program==="WezTerm"||term.startsWith("foot")||term.startsWith("rxvt"))return wrapTmux([`\x1B]777;notify;${sanitizeOsc(title)};${sanitizeOsc(body)}\x1B\\`],env);if(program==="iTerm.app"||env.WT_SESSION!==void 0&&env.WT_SESSION!=="")return wrapTmux([`\x1B]9;${sanitizeOsc(title)}: ${sanitizeOsc(body)}\x1B\\`],env);let id=`kit${process12.pid}`,codes=[`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`,`\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];return wrapTmux(codes,env)}function notifyEnd(command,code,ms,{stream=process12.stderr,env=process12.env}={}){if(ms<NOTIFY_AFTER_MS||code===CANCELLED||outputMode(stream,env)!=="terminal")return;stream.write(notification(command,code===0?`done in ${formatDuration(ms)}`:`failed with exit ${code} after ${formatDuration(ms)}`,env))}init_style();init_text2();import{appendFileSync,mkdirSync,readFileSync as readFileSync4,renameSync,statSync as statSync2,writeFileSync}from"fs";import{homedir as homedir3}from"os";import{dirname as dirname2,join as join4}from"path";import process13 from"process";init_user_config();var CLI_FOLDER="kaynooo-cli";init_user_config();var MAX_USAGE_BYTES=2097152,UNKNOWN_OPTION2=/unknown option '(--[a-z][a-z0-9-]*)[=']/,FLAG_NAME=/^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/,LONGEST_NAME=40,usageError;function noteUsageError(message){usageError=message}function stateHome(env=process13.env){return xdgFolder(env.XDG_STATE_HOME,join4(homedir3(),".local","state"))}function usagePath(env=process13.env){return join4(stateHome(env),CLI_FOLDER,"usage.jsonl")}function usageRecorded(env=process13.env){let off=env.KAYNOOO_CLI_NO_USAGE;return env.NODE_ENV!=="test"&&(off===void 0||off===""||off==="0")}function flagNames(argv){let end=argv.indexOf("--"),names=(end===-1?argv:argv.slice(0,end)).filter((word)=>word.startsWith("-")&&word!=="-").map((word)=>word.includes("=")?word.slice(0,word.indexOf("=")):word);return[...new Set(names)].filter((name)=>name.length<=LONGEST_NAME&&FLAG_NAME.test(name))}function usageEntry(bin,command,argv,code,{ms,now=new Date}={}){let unknown=code===2&&usageError!==void 0?UNKNOWN_OPTION2.exec(usageError)?.[1]:void 0;return usageError=void 0,{at:now.toISOString(),bin,...command===void 0?{}:{command},flags:flagNames(argv),code,...unknown===void 0?{}:{unknown},...ms===void 0?{}:{ms:Math.round(ms)}}}function trimUsage(path,maxBytes){let info=statSync2(path,{throwIfNoEntry:!1});if(info===void 0||info.size<=maxBytes)return;let lines=readFileSync4(path,"utf8").split(`
|
|
69
|
+
`).filter(Boolean),kept=`${lines.slice(Math.floor(lines.length/2)).join(`
|
|
70
|
+
`)}
|
|
71
|
+
`,temp=`${path}.${process13.pid}.tmp`;writeFileSync(temp,kept,{mode:384}),renameSync(temp,path)}function recordUsage(entry,env=process13.env,maxBytes=MAX_USAGE_BYTES){if(!usageRecorded(env))return;try{let path=usagePath(env);mkdirSync(dirname2(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
|
|
72
|
+
`,{mode:384}),trimUsage(path,maxBytes)}catch{}}var LEVEL_OPTIONS={...OUTPUT_OPTIONS,help:{type:"boolean",short:"h",description:"show this help"}},TOP_OPTIONS={...LEVEL_OPTIONS,version:{type:"boolean",short:"v",description:"print the version"},completions:{type:"string",choices:COMPLETION_SHELLS,description:"print the shell completion script"}};async function commandRows(all,colors){let commands=shown(all),width=Math.max(0,...Object.keys(commands).map((name)=>name.length)),groups=new Map([["Commands:",[]]]),summaries=await Promise.all(Object.values(commands).map(async({summary})=>resolveSummary(summary)));for(let[index,[name,{group}]]of Object.entries(commands).entries()){let heading=group===void 0?"Commands:":`${group}:`,rows=groups.get(heading)??[];rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`),groups.set(heading,rows)}return[...groups].filter(([,rows])=>rows.length>0).flatMap(([heading,rows],index)=>[...index===0?[]:[""],colors.bold(heading),...rows])}function shown(commands){return Object.fromEntries(Object.entries(commands).filter(([,{hidden}])=>hidden!==!0))}function takeOutputFlags(argv){let index=0;for(;index<argv.length;index++){let word=argv[index];if(word==="--plain")applyOutput(void 0,!0);else if(word.startsWith("--color="))applyOutput(word.slice(8),void 0);else if(word==="--color"&&argv[index+1]!==void 0)applyOutput(argv[++index],void 0);else break}return argv.slice(index)}async function resolveSummary(summary){return typeof summary==="string"?summary:summary()}function lookup({commands,aliases},word){let name=aliases!==void 0&&Object.hasOwn(aliases,word)?aliases[word]??word:word;return Object.hasOwn(commands,name)?commands[name]:void 0}function scopeOf(commands,extra,aliases){return{commands:typeof commands==="function"?{}:commands,lazy:[...typeof commands==="function"?[commands]:[],...extra===void 0?[]:[extra]],aliases}}async function expand(scope,words){if(scope.lazy.length===0)return scope;let commands={...scope.commands};for(let added of await Promise.all(scope.lazy.map(async(lazy)=>lazy(words))))for(let[name,command]of Object.entries(added))commands[name]??=command;return{...scope,commands,lazy:[]}}async function help2({path,header,summary:lazySummary,commands,defaultCommand,examples,replaces},stream){let colors=paint(stream),prefix=path.join(" "),summary=await resolveSummary(lazySummary);if(wantsHelpJson())return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`,{examples,replaces}));let columns=takesControlCodes(stream)?stream.columns:void 0,fallback=defaultCommand===void 0?void 0:commands[defaultCommand],options=fallback!==void 0&&"run"in fallback?await optionsOf(fallback.run):void 0,own=Object.entries(options??{}).filter(([name])=>!(name in TOP_OPTIONS));return[header(colors,summary),"",usageLine(`${prefix} ${defaultCommand===void 0?colors.cyan("<command>"):`[${colors.cyan("<command>")}]`} [options]`,colors),"",...await commandRows(commands,colors),...own.length===0?[]:["",`${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`,...optionRows(Object.fromEntries(own),colors,columns)],"",colors.bold("Options:"),...optionRows(path.length===1?TOP_OPTIONS:LEVEL_OPTIONS,colors,columns),...exampleRows(examples??[],colors),"",`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`].join(`
|
|
73
|
+
`)}function printError(prefix,message,hint,cause){let colors=paint(process14.stderr),styled=takesControlCodes(process14.stderr),head=styled?`${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}`:`error: ${prefix}:`,under=(label,text,tint)=>text===void 0?"":`
|
|
74
|
+
${styled?tint(label):`${label}:`} ${text}`;console.error(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause){console.error(JSON.stringify({error:message,...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}function wantsJson(argv){let end=argv.indexOf("--");return(end===-1?argv:argv.slice(0,end)).includes("--json")}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let help=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?printJsonError:(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??help:void 0,cause),error instanceof Exit?error.code:1}async function dispatch(level,typed,{version,redact}){let prefix=level.path.join(" "),argv;try{argv=takeOutputFlags(typed)}catch(error){return{code:reportThrown(prefix,error),meta:!1}}let[name,...args]=argv,fallback=level.defaultCommand===void 0?void 0:level.commands[level.defaultCommand];if(name===void 0&&level.runBare&&fallback!==void 0&&"run"in fallback)try{return{code:await fallback.run([]),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${level.defaultCommand}`,error,redact,!1),meta:error instanceof HelpShown}}if(name===void 0&&level.path.length>1)return console.error(await help2(await expand(level,[...level.path.slice(1),...argv]),process14.stderr)),{code:2,meta:!0};if(name==="help"&&args.length>0)return dispatch(level,[...args,"--help"],{version,redact});if(name===void 0||name==="help"||name==="--help"||name==="-h")return console.log(await help2(await expand(level,[...level.path.slice(1),...argv]),process14.stdout)),{code:0,meta:!0};if(level.path.length===1&&(name==="--version"||name==="-v"))return console.log(version()),{code:0,meta:!0};let command=lookup(level,name),rest=args,ran=name;if(command===void 0&&level.lazy.length>0)level=await expand(level,[...level.path.slice(1),...argv]),command=lookup(level,name);if(command===void 0&&level.defaultCommand!==void 0)command=level.commands[level.defaultCommand],rest=argv,ran=level.defaultCommand;if(command===void 0){let meant=closest(name,Object.keys(shown(level.commands)));return printError(prefix,`no command ${name}`,meant===void 0?`run ${prefix} --help for its commands`:`did you mean ${meant}?`),{code:2,meta:!1}}if("commands"in command){let{summary}=command;return dispatch({path:[...level.path,name],header:(colors,text)=>`${colors.bold(`${prefix} ${name}`)} ${text}`,summary,...scopeOf(command.commands,command.extraCommands,command.aliases),defaultCommand:void 0,runBare:!1,examples:command.examples,replaces:void 0},rest,{version,redact})}try{return{code:await command.run(rest),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${ran}`,error,redact,wantsJson(rest)),meta:error instanceof HelpShown}}}var COMPLETE="__complete",FILES="__files__";async function completingOf(run){completion.active=!0;try{await run([])}catch(error){if(error instanceof Completing)return error}finally{completion.active=!1}return new Completing({})}async function optionsOf(run){return(await completingOf(run)).options}function candidateLine(candidate){return typeof candidate==="string"?candidate:candidate.join("\t")}function positionalBeingTyped(before,{options,positionals}){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),typed=[],at=0;while(at<before.length){let word=before[at];if(word==="--"){typed.push(...before.slice(at+1));break}if(!word.startsWith("-"))typed.push(word);else if(takesValue(word))at++;at++}let last=positionals.at(-1);if(typed.length<positionals.length)return{name:positionals[typed.length],typed};return{name:last?.replace("]","").endsWith("...")===!0?last:void 0,typed}}async function leafCandidates(run,words){let completing=await completingOf(run);if((words.at(-1)??"").startsWith("-"))return Object.entries(completing.options).map(([name,option])=>option.description===void 0?`--${name}`:`--${name} ${option.description}`);let flag=words.at(-2),option=flag?.startsWith("-")===!0?Object.entries(completing.options).find(([name,{short}])=>flag===`--${name}`||flag===`-${short}`)?.[1]:void 0,{name,typed}=positionalBeingTyped(words.slice(0,-1),completing);if(option?.type==="string"){let values=option.choices===void 0?await option.candidates?.(typed):option.choices;return values===void 0?[FILES]:values.map(candidateLine)}let values=name===void 0?void 0:await completing.candidates[name]?.(typed);return values===void 0?[FILES]:values.map(candidateLine)}async function candidates(scope,defaultCommand,words,before=[]){let[word="",...rest]=words,listing=rest.length===0&&!word.startsWith("-"),{commands}=scope,command=lookup(scope,word);if(listing||command===void 0){let expanded=await expand(scope,[...before,...words]);commands=expanded.commands,command=lookup(expanded,word)}if(listing){let own=await Promise.all(Object.entries(shown(commands)).map(async([name,{summary}])=>`${name} ${await resolveSummary(summary)}`)),fallback=defaultCommand===void 0?void 0:commands[defaultCommand],values=fallback!==void 0&&"run"in fallback?await leafCandidates(fallback.run,[word]):[],valueOf=(line)=>line.slice(0,line.includes("\t")?line.indexOf("\t"):void 0);return[...own,...values.filter((line)=>line!==FILES&&!Object.hasOwn(commands,valueOf(line)))]}if(command===void 0){let fallback=defaultCommand===void 0?void 0:commands[defaultCommand];return fallback!==void 0&&"run"in fallback?leafCandidates(fallback.run,words):[]}return"commands"in command?candidates(scopeOf(command.commands,command.extraCommands,command.aliases),void 0,rest,[...before,word]):leafCandidates(command.run,rest)}var COMPLETIONS="--completions";function flagValue([flag="",...rest]){return flag.includes("=")?[flag.slice(flag.indexOf("=")+1),...rest]:rest}function printCompletionScript(name,args){let shell=COMPLETION_SHELLS.find((each)=>each===args[0]);if(shell===void 0||args.length!==1)return printError(name,`${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`,`${name} ${COMPLETIONS} fish`),2;return console.log(completionScript(shell,[name]).trimEnd()),0}async function printCandidates(found){for(let line of await found)console.log(line);return 0}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname3(resolved);;dir=dirname3(dir)){try{let{version}=JSON.parse(readFileSync5(join5(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname3(dir)===dir)return"0.0.0"}}async function runCli(cli,argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(candidates(scopeOf(cli.commands,cli.extraCommands,cli.aliases),cli.defaultCommand,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(cli.name,flagValue(argv));let version=()=>cli.version??packageVersion(),started=performance.now(),{code,meta}=await dispatch({path:[cli.name],header:(colors,about)=>`${colors.bold(cli.name)} ${colors.dim(version())} ${about}`,summary:cli.about,...scopeOf(cli.commands,cli.extraCommands,cli.aliases),defaultCommand:cli.defaultCommand,runBare:cli.runBare===!0,examples:cli.examples,replaces:cli.replaces},argv,{version,redact:cli.redact}),command=commandPath(scopeOf(cli.commands,cli.extraCommands,cli.aliases),argv);if(notifyEnd(command===void 0?cli.name:`${cli.name} ${command}`,code,performance.now()-started),cli.usage!==!1&&!meta)try{recordUsage(usageEntry(cli.name,command,argv,code,{ms:performance.now()-started}))}catch{}return code}function commandPath(scope,argv){let path=[],level=scope;for(let word of argv.filter((each)=>!each.startsWith("-"))){let command=lookup(level,word);if(command===void 0)break;if(path.push(word),!("commands"in command))break;level=scopeOf(command.commands,command.extraCommands,command.aliases)}return path.length===0?void 0:path.join(" ")}init_config();init_text2();init_folders();init_format();init_args();init_args();init_mode();init_style();init_text2();var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");init_style();init_text2();init_theme();init_user_config();init_args();init_input();init_style();init_user_config();init_prompt();init_chunk_yfkscv18();var W=1000,ht=60*W,Ue=60*ht,S=24*Ue,ei=7*S;var Y=[[n.y,"year"],[n.M,"month"],[n.w,"week"],[n.d,"day"],[n.h,"hour"],[n.m,"minute"],[n.s,"second"]];var T=15*W;function l(e,n){if(n===void 0)return e??void 0;let t=AbortSignal.timeout(n);return e?AbortSignal.any([e,t]):t}function w(e){if(typeof e!=="object"||e===null)return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function J(e,{signal:n}={}){return new Promise((t,o)=>{if(n?.aborted)return o(n.reason);let r=setTimeout(()=>{n?.removeEventListener("abort",s),t()},e);function s(){clearTimeout(r),o(n.reason)}n?.addEventListener("abort",s,{once:!0})})}init_chunk_rkhsft4a();async function ae(r,{attempts:t=3,delay:s=1000,backoff:m=2,maxDelay:o=1/0,jitter:i=!1,shouldRetry:a,onRetry:u,signal:l}={}){let c=i===!0?1:Number(i),e;for(let n=0;n<t+1;n++){l?.throwIfAborted();try{return await r(n)}catch(f){if(e=f,a&&!a(f,n))throw f;if(n<t){let p=Math.min(s*m**n,o)*(1-c*Math.random());u?.(f,n,p),await J(p,{signal:l})}}}throw Error(`Failed after ${t} ${G("retry",t)}`,{cause:e})}function s(...e){let r=new Headers;for(let n of e){if(!n)continue;let i;if(n instanceof Headers)i=[...n];else i=Array.isArray(n)?n:Object.entries(n);for(let[a,t]of i)if(t!==void 0)r.set(a,t)}return r}function T2(e){return w(e)||Array.isArray(e)}function J2(e){return typeof e==="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof FormData||e instanceof URLSearchParams||e instanceof ReadableStream||typeof Blob<"u"&&e instanceof Blob}var b2="http://relative.invalid";function I(e){try{return{parsed:new URL(e),relative:!1}}catch{return{parsed:new URL(e,b2),relative:!0}}}function B2(e,r){if(!r)return e;let{parsed:n,relative:i}=I(e);for(let[t,o]of Object.entries(r))for(let u of Array.isArray(o)?o:[o])if(u!==void 0)n.searchParams.append(t,String(u));if(!i)return n.href;let a=`${n.pathname}${n.search}${n.hash}`;return n.origin===b2?a:`//${n.host}${a}`}function E(e){if(!e)return;try{return JSON.parse(e)}catch{return}}function v(e){if(!w(e))return;for(let r of["error","message","detail"])if(typeof e[r]==="string"&&e[r])return e[r];return}class ie extends Error{status;statusText;url;body;data;said;constructor(e,r,n,i,a){let t=v(a),o=t??i;super(`HTTP ${e} ${r} - ${n}${o?` - ${o}`:""}`);this.status=e,this.statusText=r,this.url=n,this.body=i,this.data=a,this.name="FetchError",this.said=t}}async function x(e,r){let n;try{n=await e.text()}catch{n=""}return new ie(e.status,e.statusText,e.url||r,n||void 0,E(n))}class _e extends Error{url;body;constructor(e,r,n){super(`Invalid JSON response from ${e} - ${r.slice(0,200)}`,{cause:n});this.url=e,this.body=r,this.name="FetchParseError"}}function q(e){if(e instanceof ie)return e.status===408||e.status===429||e.status>=500;return e instanceof TypeError||e instanceof DOMException&&e.name==="TimeoutError"}async function c(e,r={}){let{retry:n,onError:i,...a}=r,{signal:t}=a;try{let o=H2(e,a);if(!n)return await m(o);let{attempts:u=3,shouldRetry:d=q,...f}=typeof n==="number"?{attempts:n}:n;return await ae(()=>m(o),{...f,attempts:u,signal:t??void 0,shouldRetry:(p,y)=>y<u&&!t?.aborted&&d(p,y)})}catch(o){throw i?.(o),o}}function A(e,r,n){if(e===void 0||e===null)return null;return r?n(e):e}function H2(e,r){let{baseUrl:n,token:i,query:a,body:t,headers:o,timeout:u,signal:d,onResponse:f,fetch:p=fetch,parse:y=JSON.parse,serialize:R=JSON.stringify,...k}=r,g=B2(n?new URL(e,n).href:e,a),h=T2(t);if(t!==void 0&&t!==null&&!h&&!J2(t))throw TypeError(`Unsupported body type for ${g}: ${Object.getPrototypeOf(t)?.constructor?.name??typeof t}`);let O=s({Accept:"application/json","Content-Type":h?"application/json":void 0,Authorization:i?`Bearer ${i}`:void 0},o);return{fullUrl:g,init:{...k,headers:O,body:A(t,h,R)},fetcher:p,parse:y,onResponse:f,timeout:u,signal:d}}async function m({fullUrl:e,init:r,fetcher:n,parse:i,onResponse:a,timeout:t,signal:o}){let u=l(o,t),d=await n(e,{...r,...u?{signal:u}:{}});if(a?.(d),!d.ok)throw await x(d,e);let f=await d.text();if(!f)return null;try{return i(f)}catch(p){throw new _e(d.url||e,f,p)}}async function cr(r,t,o=[],s={}){let n=new FormData;n.append("payload_json",JSON.stringify(t));for(let e=0;e<o.length;++e){let i=o[e],p=new Blob([new Uint8Array(i.buffer)],{type:i.contentType??"image/png"});n.append(`files[${e}]`,p,i.filename)}return await c(r,{...s,timeout:s.timeout??T,method:"POST",body:n})}var version="2.4.2";var shared={token:{type:"string",description:"The forge's token, defaults to GITHUB_TOKEN, then on GitHub to gh's login"},from:{type:"string",description:"From tag"},to:{type:"string",description:"To tag"},repo:{type:"string",short:"r",description:"Repository, e.g. kaynooo/cli, origin's by default (--gitea is kept as an alias)"},"release-repo":{type:"string",description:"Release repository, defaults to --repo (--release-gitea is kept as an alias)"},name:{type:"string",description:"Name of the release"},contributors:{type:"boolean",description:"Show contributors"},prerelease:{type:"boolean",description:"Mark release as prerelease"},draft:{type:"boolean",short:"d",description:"Mark release as draft"},output:{type:"string",description:"Output to file instead of sending to the forge"},capitalize:{type:"boolean",description:"Capitalize each commit message"},emoji:{type:"boolean",description:"Use emojis in section titles, --no-emoji to drop them"},group:{type:"boolean",description:"Nest commit messages under their scopes"},"first-parent":{type:"boolean",description:"Walk only the first parent of each merge"},"discord-webhook":{type:"string",description:"Discord webhook to post the release to, defaults to DISCORD_WEBHOOK"},"dry-run":{type:"boolean",description:"Dry run (--dry is kept as an alias)"},assets:{type:"string",multiple:!0,description:"Files to upload as assets to the release, repeatable or comma separated; quote globs, e.g. --assets 'dist/*.js'"},json:jsonOption("release: {command, status, from, to, commits, notes, url, output, assetsFailed, discord}; undo: {command, status, tag, releaseNote, remoteTag, localTag, commitReset}. Progress goes to stderr"),debug:{type:"boolean",description:"Print the stack of an unexpected error"}},undoFlags={...shared,note:{type:"boolean",description:"Also delete the release note on the forge (skips the question)"},yes:{type:"boolean",description:"Skip confirmation prompts"}},ALIASES={"--dry":"--dry-run","--gitea":"--repo","--release-gitea":"--release-repo"};function aliasFlags(argv){let end=argv.indexOf("--");return[...(end===-1?argv:argv.slice(0,end)).map((word)=>{let[name="",...value]=word.split("="),current=ALIASES[name];return current===void 0?word:[current,...value].join("=")}),...end===-1?[]:argv.slice(end)]}function defined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function toOptions(args){return defined({token:args.token,from:args.from,to:args.to,repo:args.repo,releaseRepo:args["release-repo"],name:args.name,contributors:args.contributors,prerelease:args.prerelease,draft:args.draft,output:args.output,capitalize:args.capitalize,emoji:args.emoji,group:args.group,firstParent:args["first-parent"],discordWebhook:args["discord-webhook"],dry:args["dry-run"],assets:args.assets})}function withToken(options){let token=[options.token,process.env.GITHUB_TOKEN].find((value)=>value!==void 0&&value!=="");return token===void 0?options:{...options,token}}function shouldAskNote({release,note,yes,dry}){return Boolean(release)&¬e!==!0&&yes!==!0&&dry!==!0}import path from"path";var out=()=>paint(process.stdout),err=()=>paint(process.stderr);async function stdoutToStderr(active,body){let log=console.log;if(active)console.log=(...args)=>console.error(...args.length===0?[""]:args);try{return await body()}finally{console.log=log}}var REQUEST_MS=60000;function onGithub(options){return options.provider==="github"}function tagPath(options,repo,tag,write=!1){return onGithub(options)?`repos/${repo}/git/${write?"refs":"ref"}/tags/${encodeURIComponent(tag)}`:`repos/${repo}/tags/${encodeURIComponent(tag)}`}async function request(url,init){let res=await fetch(url,{...init,signal:AbortSignal.timeout(REQUEST_MS)});if(!res.ok)throw Error(`${res.status} ${res.statusText}: ${await res.text()}`);return res}async function api(url,init){return await(await request(url,init)).json()}async function sendRelease(options,content){let headers=getHeaders(options),url=`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases`,method="POST";try{let exists=await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(options.to??"")}`,{headers});if(exists.url)url=exists.url,method="PATCH"}catch{}let body={body:content,draft:options.draft||!1,name:options.name??options.to,prerelease:options.prerelease,tag_name:options.to};console.log(out().cyan(method==="POST"?"Creating release notes...":"Updating release notes..."));let res=await api(url,{method,body:JSON.stringify(body),headers:{...headers,"content-type":"application/json"}});return console.log(out().green(`Released on ${res.html_url}`)),res.html_url}async function getRelease(options,tag){try{return await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(tag)}`,{headers:getHeaders(options)})}catch{return null}}async function deleteRelease(options,releaseId){await request(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/${releaseId}`,{method:"DELETE",headers:getHeaders(options)})}async function hasRemoteTag(options,tag){try{return await api(`https://${options.baseUrlApi}/${tagPath(options,options.releaseRepo,tag)}`,{headers:getHeaders(options)}),!0}catch{return!1}}async function deleteRemoteTag(options,tag){await request(`https://${options.baseUrlApi}/${tagPath(options,options.releaseRepo,tag,!0)}`,{method:"DELETE",headers:getHeaders(options)})}function getHeaders(options){if(onGithub(options))return{accept:"application/vnd.github+json",authorization:`Bearer ${options.token}`,"x-github-api-version":"2022-11-28"};return{accept:"application/vnd.gitea.v3+json",authorization:`token ${options.token}`}}var excludeAuthors=[/\[bot\]/i,/dependabot/i,/\(bot\)/i];async function resolveAuthorInfo(options,info){if((info.login??"")!=="")return info;if((options.token??"")==="")return info;if(info.commits.length)try{let data=await api(`https://${options.baseUrlApi}/repos/${options.repo}/${onGithub(options)?"commits":"git/commits"}/${info.commits[0]}`,{headers:getHeaders(options)});if(data.author!==null)info.login=data.author.login,info.avatar=data.author.avatar_url}catch{}if((info.login??"")!==""||onGithub(options))return info;try{let user=(await api(`https://${options.baseUrlApi}/users/search?q=${encodeURIComponent(info.email)}`,{headers:getHeaders(options)})).data.find((user)=>user.email.toLowerCase()===info.email.toLowerCase());if(user!==void 0){if(info.login=user.login,user.avatar_url!==void 0)info.avatar=user.avatar_url}}catch{}return info}async function resolveAuthors(commits,options){let map=new Map;for(let commit of commits)for(let[idx,author]of commit.authors.entries()){if(!author.email||!author.name||excludeAuthors.some((re)=>re.test(author.name)))continue;if(!map.has(author.email))map.set(author.email,{commits:[],name:author.name,email:author.email});if(idx===0)map.get(author.email).commits.push(commit.shortHash)}let authors=Array.from(map.values()),resolved=await Promise.all(authors.map(async(info)=>resolveAuthorInfo(options,info))),loginSet=new Set,nameSet=new Set;return resolved.sort((a,b)=>(a.login??a.name).localeCompare(b.login??b.name)).filter((i)=>{if(i.login!==void 0&&loginSet.has(i.login))return!1;if(i.login!==void 0)loginSet.add(i.login);else{if(nameSet.has(i.name))return!1;nameSet.add(i.name)}return!0})}async function hasTagOnGitea(tag,options){try{let url=`https://${options.baseUrlApi}/${tagPath(options,options.repo,tag)}`;return console.log(`checking if tag exists on ${url}`),await api(url,{headers:getHeaders(options)}),!0}catch{return!1}}async function uploadAssets(options,assets){let headers=getHeaders(options),assetList=[];if(typeof assets==="string")assetList=assets.split(",").map((s)=>s.trim()).filter(Boolean);else if(Array.isArray(assets))assetList=assets.flatMap((item)=>typeof item==="string"?item.split(",").map((s)=>s.trim()):[]).filter(Boolean);let expandedAssets=[];for(let pattern of assetList)try{let glob=new Bun.Glob(pattern),matches=Array.from(glob.scanSync());if(matches.length)expandedAssets.push(...matches);else expandedAssets.push(pattern)}catch(error){console.error(err().red(`Failed to process glob pattern "${pattern}": ${String(error)}`)),expandedAssets.push(pattern)}let release=await api(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(options.to??"")}`,{headers}),failed=0;for(let asset of expandedAssets){let filePath=path.resolve(asset),file=Bun.file(filePath);if(!await file.exists()){console.error(err().red(`Failed to read file ${filePath}: file does not exist`)),failed++;continue}let fileName=path.basename(filePath),assetsPath=`repos/${options.releaseRepo}/releases/${release.id}/assets?name=${encodeURIComponent(fileName)}`;console.log(out().cyan(`Uploading ${fileName}...`));try{if(onGithub(options))await request(`https://uploads.github.com/${assetsPath}`,{method:"POST",headers:{...headers,"content-type":"application/octet-stream"},body:file});else{let form=new FormData;form.append("attachment",file,fileName),await request(`https://${options.baseUrlApi}/${assetsPath}`,{method:"POST",headers,body:form})}console.log(out().green(`Uploaded ${fileName} successfully.`))}catch(error){console.error(err().red(`Failed to upload ${fileName}: ${String(error)}`)),failed++}}return failed}import{join as join6}from"path";var{$:$2}=globalThis.Bun;var o2=/^(\d+)\.(\d+)\.(\d+)$/;function wn(r){return o2.test(r)}function Z(r){let n=o2.exec(r);if(!n)throw Error(`Invalid semver: "${r}"`);return{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}}var{$}=globalThis.Bun;var gitSuffixRE=/\.git$/,sshRegex=/(?:ssh:\/\/[^/]+\/|^(?:[^@/\s]+@)?[^:/\s]+:)(\w[\w.-]*)\/(\w[\w.-]*)$/i,regexSpecialRE=/[.*+?^${}()|[\]\\]/g,httpsRegex=/https?:\/\/[^/]+\/(\w[\w.-]*)\/(\w[\w.-]*)$/i,releaseVersionRE=/^[^.]*(?:\.[\d.]*|\d)$/,TAG_DECORATION=/tag: ([^,\n]+)/g,ORIGIN_HOST=/^(?:[a-z][a-z\d+.-]*:\/\/)?(?:[^@/]+@)?([^:/]+)/i;async function getOriginHost(){let url=(await $`git config --get remote.origin.url`.quiet().nothrow().text()).trim();return ORIGIN_HOST.exec(url)?.[1]}async function getGiteaRepo(){let url=await execCommand("git",["config","--get","remote.origin.url"]),cleanUrl=url.replace(gitSuffixRE,""),match=sshRegex.exec(cleanUrl);if(match||=httpsRegex.exec(cleanUrl),!match)throw Error(`Can not parse Gitea repo from url ${url}`);return`${match[1]}/${match[2]}`}async function getCurrentGitBranch(){let[tag]=(await execCommand("git",["tag","--points-at","HEAD","--sort=-v:refname"])).split(`
|
|
75
|
+
`);return tag!==void 0&&tag!==""?tag:execCommand("git",["rev-parse","--abbrev-ref","HEAD"])}async function isRepoShallow(){return(await execCommand("git",["rev-parse","--is-shallow-repository"])).trim()==="true"}function getSafeTagTemplate(template){return template.includes("%s")?template:`${template}%s`}function getVersionString(template,tag){let pattern=template.split("%s").map((part)=>part.replace(regexSpecialRE,"\\$&")).join("(.+)");return new RegExp(`^${pattern}$`).exec(tag)?.[1]??tag}async function tipOf(to){return(await $`git rev-parse --verify -q ${`${to}^{commit}`}`.quiet().nothrow()).exitCode===0?to:"HEAD"}async function getGitTags(firstParent=!1,to="HEAD"){return[...(await execCommand("git",["log",...firstParent?["--first-parent"]:[],"--decorate-refs=refs/tags/","--format=%D",await tipOf(to),"--"])).matchAll(TAG_DECORATION)].map((match)=>match[1]?.trim()??"").filter((tag)=>tag!=="")}async function getLastMatchingTag(inputTag,tagFilter,tagTemplate,rollup={},firstParent=!1){let inputVersionString=getVersionString(tagTemplate,inputTag),isStableVersion=wn(inputVersionString),filteredTags=(await getGitTags(firstParent,inputTag)).filter(tagFilter),tag;if(isStableVersion){let input=Z(inputVersionString),isMajor=input.minor===0&&input.patch===0,isMinor=!isMajor&&input.patch===0,boundary;if(isMajor&&rollup.major)boundary=(v)=>v.minor===0&&v.patch===0;else if(isMinor&&rollup.minor)boundary=(v)=>v.patch===0;tag=filteredTags.find((tag)=>{let versionString=getVersionString(tagTemplate,tag);if(versionString===inputVersionString||!wn(versionString))return!1;return boundary?boundary(Z(versionString)):!0})}return tag||=filteredTags.find((tag)=>tag!==inputTag),tag}async function isRefGitTag(to){let ref=`refs/tags/${to}`;try{return await $`git show-ref --verify ${ref}`.quiet(),!0}catch{return!1}}async function getFirstGitCommit(firstParent=!1,to="HEAD"){return(await execCommand("git",["rev-list","--max-parents=0",...firstParent?["--first-parent"]:[],await tipOf(to),"--"])).split(`
|
|
76
|
+
`).at(-1)??""}async function deleteLocalTag(tag){await $`git tag -d ${tag}`.quiet()}async function hasRemoteGitTag(tag,remote="origin"){return(await execCommand("git",["ls-remote","--tags",remote,`refs/tags/${tag}`])).length>0}async function deleteRemoteGitTag(tag,remote="origin"){await $`git push ${remote} --delete ${tag}`.quiet()}async function getTagCommit(tag){return execCommand("git",["rev-list","-n","1",tag])}async function getHeadCommit(){return execCommand("git",["rev-parse","HEAD"])}async function getCommitSubject(ref){return execCommand("git",["log","-1","--format=%s",ref])}async function softResetLastCommit(){await $`git reset --soft HEAD~1`.quiet()}function isPrerelease(version){return!releaseVersionRE.test(version)}async function execCommand(cmd,args){return(await $`${cmd} ${args}`.quiet().text()).trim()}var GITHUB="github.com";function forgeName(config){return config.provider==="github"?"GitHub":"Forgejo"}var configFiles=["ts","mts","js","mjs","json"].map((ext)=>`changelog.config.${ext}`),defaultConfig={scopeMap:{},types:{feat:{title:"\u2728 New"},fix:{title:"\uD83D\uDD27 Fixed"},perf:{title:"\u26A1 Faster"},refactor:{title:"refactor",folded:!0},docs:{title:"docs",folded:!0},build:{title:"build",folded:!0},types:{title:"types",folded:!0},test:{title:"test",folded:!0},style:{title:"style",folded:!0},ci:{title:"ci",folded:!0}},titles:{breakingChanges:"\u26A0\uFE0F Breaking",highlights:"\uD83C\uDF1F Highlights",maintenance:"\uD83E\uDDF9 Maintenance"},contributors:!0,capitalize:!0,group:!0,emoji:!0,firstParent:!1,tag:"v%s"};function isPlainObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function mergeLayers(...layers){let merged={};for(let layer of layers)for(let[key,value]of Object.entries(layer)){if(value===void 0)continue;merged[key]=isPlainObject(value)&&isPlainObject(merged[key])?mergeLayers(merged[key],value):value}return merged}async function loadConfigFile(cwd){for(let name of configFiles){let path=join6(cwd,name);if(await Bun.file(path).exists())return(await import(path)).default??{}}return{}}async function ghToken(){if(Bun.which("gh")===null)return;let answer=await $2`gh auth token`.quiet().nothrow();return answer.exitCode===0&&answer.text().trim()!==""?answer.text().trim():void 0}async function loadPackageConfig(cwd){let file=Bun.file(join6(cwd,"package.json"));return!await file.exists()?{}:(await file.json()).changelog??{}}async function loadConfig(options,cwd=process.cwd()){let[packageConfig,fileConfig]=await Promise.all([loadPackageConfig(cwd),loadConfigFile(cwd)]);return mergeLayers(defaultConfig,packageConfig,fileConfig,options)}async function resolveConfig(options){let config=await loadConfig(options),origin=config.baseUrl===void 0?await getOriginHost():void 0,baseUrl=config.baseUrl??(origin===GITHUB?origin:configuredForge()?.host??origin);if(baseUrl===void 0||baseUrl==="")throw Error("no forge to link the notes to: set baseUrl in the changelog config, forge in ~/.config/kaynooo-cli/config.json, or an origin remote");config.baseUrl=baseUrl,config.provider??=baseUrl===GITHUB?"github":"gitea",config.baseUrlApi??=config.provider==="github"?"api.github.com":`${baseUrl}/api/v1`;let token=config.provider==="github"&&(config.token??"")===""?await ghToken():void 0;if(token!==void 0)config.token=token;if(config.to||=await getCurrentGitBranch(),config.tagFilter??=()=>!0,config.tag=getSafeTagTemplate(config.tag??defaultConfig.tag),config.rollup??={},config.fromRoot=!1,config.from===void 0||config.from===""){let tag=await getLastMatchingTag(config.to,config.tagFilter,config.tag,config.rollup,config.firstParent);config.fromRoot=tag===void 0,config.from=tag??await getFirstGitCommit(config.firstParent,config.to)}let legacy=config;if(config.repo||=legacy.gitea??await getGiteaRepo(),config.releaseRepo||=legacy.releaseGithub??config.repo,config.prerelease??=isPrerelease(config.to),config.discordWebhook??=process.env.DISCORD_WEBHOOK??"",typeof config.repo!=="string")throw TypeError(`Invalid repository, expected a string but got ${JSON.stringify(config.repo)}`);return config}function p(n){return n!==null&&n!==void 0}function m2(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,writable:!0,configurable:!0})}function Fr(n,e){let t={};for(let o of n){let u=e(o);if(Object.hasOwn(t,u))t[u].push(o);else m2(t,u,[o])}return t}init_text();var emojiRE=/\p{Extended_Pictographic}\uFE0F?/gu,fullHashRE=/^[\da-f]{40}$/,IDENTIFIER_START=/^(?:`|[a-z]+[A-Z]|\S*\d|\S*[._/]\w)/;function groupCommits(commits,options){let breaking=commits.filter((c)=>c.isBreaking),byType=Fr(commits.filter((c)=>!c.isBreaking),(c)=>c.type),sections=breaking.length?[{title:options.titles.breakingChanges,commits:breaking}]:[],folded=[];for(let[type,config]of Object.entries(options.types)){let typed=byType[type]??[];if(typeof config==="boolean"||typed.length===0)continue;(config.folded===!0?folded:sections).push({title:config.title,commits:typed})}return{sections,folded}}function formatTitle(title,options){return(options.emoji?title:title.replace(emojiRE,"")).trim()}function shortRef(ref){return fullHashRE.test(ref)?ref.slice(0,7):ref}function repoUrl(options){return`https://${options.baseUrl}/${options.repo}`}function compareUrl(options){return`${repoUrl(options)}/compare/${options.from}...${options.to}`}function releaseUrl(options){return`https://${options.baseUrl}/${options.releaseRepo}/releases/tag/${encodeURIComponent(options.to)}`}function userUrl(login,options){return`https://${options.baseUrl}/${login}`}function formatIssue(ref,options,withTitle){return`[${withTitle&&ref.title!==void 0?`${ref.value} ${ref.title}`:ref.value}](${repoUrl(options)}/issues/${ref.value.slice(1)})`}function capitalized(description){return IDENTIFIER_START.test(description)?description:d(description)}function formatLine(commit,options,prefix="",issueTitles=!1){let description=options.capitalize?capitalized(commit.description):commit.description,hash=`[\`${commit.shortHash.slice(0,7)}\`](${repoUrl(options)}/commit/${commit.shortHash})`,issues=commit.references.filter((ref)=>ref.type!=="hash").map((ref)=>formatIssue(ref,options,issueTitles));return[`${prefix}${description}`,hash,...issues].join(" \xB7 ")}function foldedPrefix(commit){return`**${commit.scope?`${commit.type}(${commit.scope})`:commit.type}**: `}function foldedCounts(folded,options){return folded.map((section)=>`${section.commits.length} ${formatTitle(section.title,options)}`).join(", ")}function formatAuthors(contributors,options){return join7(contributors.map((c)=>c.login!==void 0?`[@${c.login}](${userUrl(c.login,options)})`:`**${c.name}**`))}function summaryLabel(title){return title.replace(emojiRE,"").trim().toLowerCase()}function formatSummary({sections,folded},contributors,options){let counts=sections.map((section)=>`${section.commits.length} ${summaryLabel(section.title)}`);if(folded.length){let total=folded.reduce((sum,section)=>sum+section.commits.length,0);counts.push(`${total} ${summaryLabel(options.titles.maintenance)}`)}let authors=formatAuthors(contributors,options);return`> ${[counts.length?`**${counts.join(" \xB7 ")}**`:"",authors&&`by ${authors}`,`\`${shortRef(options.from)}\` \u2192 \`${shortRef(options.to)}\``].filter(Boolean).join(" \xB7 ")}`}function formatSection(section,options){let lines=["",`### ${formatTitle(section.title,options)}`,""],scopes=Fr(section.commits,(c)=>c.scope),nestable=Object.entries(scopes).some(([scope,commits])=>scope!==""&&commits.length>1);for(let[scope,commits]of Object.entries(scopes).sort(([a],[b])=>a.localeCompare(b))){let scopeText=`**${scope}**`,nested=nestable&&scope!==""&&(options.group===!0||options.group==="multiple"&&commits.length>1),prefix=scope!==""&&!nested?`${scopeText}: `:"",padding=nested?" ":"";if(nested)lines.push(`- ${scopeText}:`);for(let commit of commits.toReversed())if(lines.push(`${padding}- ${formatLine(commit,options,prefix)}`),commit.breakingNote!==void 0)lines.push(`${padding} - ${commit.breakingNote}`)}return lines}function formatAvatars(contributors,options){return contributors.filter((c)=>c.login!==void 0&&c.avatar!==void 0).map((c)=>`<a href="${userUrl(c.login,options)}"><img src="${c.avatar}" width="28" height="28" alt="@${c.login}"></a>`).join(" ")}function generateMarkdown(commits,options,contributors=[],highlights){let grouped=groupCommits(commits,options),{sections,folded}=grouped,lines=[formatSummary(grouped,contributors,options)];if(highlights)lines.push("",`### ${formatTitle(options.titles.highlights,options)}`,"",...highlights.lines,"",`[Read more](${highlights.link})`);for(let section of sections)lines.push(...formatSection(section,options));if(folded.length)lines.push("","<details>",`<summary><b>${formatTitle(options.titles.maintenance,options)}</b> \xB7 ${foldedCounts(folded,options)}</summary>`,"",...folded.flatMap((section)=>section.commits.toReversed().map((commit)=>`- ${formatLine(commit,options,foldedPrefix(commit))}`)),"","</details>");if(!sections.length&&!folded.length)lines.push("","*No significant changes*");lines.push("","---","");let avatars=formatAvatars(contributors,options);if(avatars)lines.push(avatars,"");return lines.push(`<sub>[Full diff \`${shortRef(options.from)}...${shortRef(options.to)}\`](${compareUrl(options)}) \xB7 generated by cli-changelog</sub>`),lines.join(`
|
|
77
|
+
`)}function join7(array,glue=", ",finalGlue=" and "){return array.length<=2?array.join(finalGlue):`${array.slice(0,-1).join(glue)}${finalGlue}${array.at(-1)}`}var descriptionLimit=4096,color=16486972,breakingColor=15548997,fenceRE=/^\s*(`{3,}|~{3,})/,headingRE=/^#{1,6}(?:\s(.*))?$/,strongRE=/\*\*|__/g,isCommitLine=(line)=>line.startsWith("- ");function fitCommits(head,lines,tail){let total=lines.filter(isCommitLine).length;for(let kept=lines.length;kept>=0;kept--){let shown=lines.slice(0,kept);while(shown.length&&kept<lines.length&&!isCommitLine(shown.at(-1)))shown.pop();let more=total-shown.filter(isCommitLine).length,text=[...head,...shown,...more?["",`*\u2026and ${more} more*`]:[],"",tail].join(`
|
|
78
|
+
`).trim();if(text.length<=descriptionLimit)return text}return}function fitDescription(head,lines,tail){let fitted=fitCommits(head,lines,tail);if(fitted!==void 0||!head.length)return fitted??tail.slice(0,descriptionLimit);for(let kept=head.length-2;kept>=1;kept--){let shown=head.slice(0,kept),open=openFence(shown);if(open!==void 0)shown.push(open);let text=fitCommits([...shown,"\u2026",head.at(-1)],lines,tail);if(text!==void 0)return text}return tail.slice(0,descriptionLimit)}function openFence(lines){let open;for(let line of lines){let marker=fenceRE.exec(line)?.[1];if(marker!==void 0)open=open!==void 0&&marker.startsWith(open)?void 0:open??marker}return open}var tableRowRE=/^\s*\|.*\|\s*$/,tableRuleRE=/^\s*\|(?:\s*:?-+:?\s*\|)+\s*$/,cellSplitRE=/(?<!\\)\|(?=(?:[^`]*`[^`]*`)*[^`]*$)/;function bulletedTables(lines){let fenced=!1,out=[];for(let[index,line]of lines.entries()){if(fenceRE.test(line))fenced=!fenced;if(fenced||!tableRowRE.test(line)){out.push(line);continue}if(tableRuleRE.test(line)||tableRuleRE.test(lines[index+1]??""))continue;let[first="",...rest]=line.trim().slice(1,-1).split(cellSplitRE).map((cell)=>cell.trim());out.push(`- **${first}**${rest.length?`: ${rest.join(" \xB7 ")}`:""}`)}return out}function highlightLines(highlights,options){let fenced=!1,lines=bulletedTables(highlights.lines).flatMap((line)=>{if(fenceRE.test(line))fenced=!fenced;let heading=fenced?null:headingRE.exec(line);if(!heading)return[line];let text=(heading[1]??"").replace(strongRE,"").trim();return text?[`**${text}**`]:[]});return[`**${formatTitle(options.titles.highlights,options)}**`,...lines,`[Read more](${highlights.link})`]}function generateDiscordPayload(commits,options,contributors=[],highlights){let{sections,folded}=groupCommits(commits,options),lines=[];for(let section of sections){lines.push("",`**${formatTitle(section.title,options)}**`);for(let commit of section.commits.toReversed())lines.push(`- ${formatLine(commit,options,commit.scope?`**${commit.scope}**: `:"",!0)}`)}if(!sections.length&&!folded.length)lines.push("*No significant changes*");let links=`[full notes](${releaseUrl(options)}) \xB7 [diff](${compareUrl(options)})`,tail=folded.length?`${formatTitle(options.titles.maintenance,options)} *${foldedCounts(folded,options)}* \xB7 ${links}`:links,authors=contributors.map((c)=>c.login??c.name).join(", "),range=`${shortRef(options.from)} \u2192 ${shortRef(options.to)}`,avatar=contributors.find((c)=>c.avatar!==void 0)?.avatar;return{embeds:[{title:`${String(options.releaseRepo).split("/").at(-1)} ${options.name||options.to}`.slice(0,256),url:releaseUrl(options),color:commits.some((c)=>c.isBreaking)?breakingColor:color,description:fitDescription(highlights?highlightLines(highlights,options):[],lines,tail),footer:{text:authors?`${authors} \xB7 ${range}`:range,...avatar===void 0?{}:{icon_url:avatar}},timestamp:new Date().toISOString()}]}}var{$:$3}=globalThis.Bun;var ConventionalCommitRegex=/^(?::.+:|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F\uDE80-\uDEFF]|[\u2600-\u2B55])? *(?<type>[a-z]+)(?:\((?<scope>[^()\n]+)\))?(?<breaking>!)?: (?<description>.+)/i,CoAuthoredByRegex=/co-authored-by:\s*(?<name>\S[^<]*)<(?<email>[^>]+)>/gi,PullRequestRE=/\([ a-z]*(#\d+)\s*\)/g,IssueRE=/(#\d+)/g,BreakingBodyRE=/^BREAKING[ -]CHANGE:[ \t]*(.*(?:\n(?![ \t]*$|[\w-]+(?:: | #)).+)*)/m,TicketLineRE=/^(#\d+) - (.+)$/gm;async function getGitDiff(from,to="HEAD",firstParent=!1){let range=`${from!==void 0&&from!==""?`${from}..`:""}${to}`,pretty="%x1e%s%x00%h%x00%an%x00%ae%x00%b";return(await $3`git --no-pager log ${range} ${firstParent?["--first-parent"]:[]} --pretty=${"%x1e%s%x00%h%x00%an%x00%ae%x00%b"}`.quiet().text()).split("\x1E").slice(1).map((record)=>{let[message="",shortHash="",authorName="",authorEmail="",body=""]=record.split("\x00");return{message,shortHash,author:{name:authorName,email:authorEmail},body:body.trim()}})}function parseGitCommit(commit,config){let match=commit.message.match(ConventionalCommitRegex);if(!match?.groups)return null;let type=(match.groups.type??"").toLowerCase(),breakingBody=BreakingBodyRE.exec(commit.body),breakingNote=breakingBody?.[1]?.replaceAll(/\s+/g," ").trim(),rawScope=match.groups.scope??"",scope=Object.hasOwn(config.scopeMap,rawScope)?config.scopeMap[rawScope]:rawScope,isBreaking=match.groups.breaking!==void 0||breakingBody!==null,description=match.groups.description??"",references=[];for(let m of description.matchAll(PullRequestRE))references.push({type:"pull-request",value:m[1]});for(let m of description.matchAll(IssueRE))if(!references.some((i)=>i.value===m[1]))references.push({type:"issue",value:m[1]});for(let m of commit.body.matchAll(TicketLineRE)){let known=references.find((i)=>i.value===m[1]);if(known)known.title=m[2].trim();else references.push({type:"issue",value:m[1],title:m[2].trim()})}references.push({value:commit.shortHash,type:"hash"}),description=description.replace(PullRequestRE,"").trim();let authors=[commit.author];for(let m of commit.body.matchAll(CoAuthoredByRegex))authors.push({name:(m.groups?.name??"").trim(),email:(m.groups?.email??"").trim()});return{...commit,authors,description,type,scope,references,isBreaking,...breakingNote===void 0||breakingNote===""?{}:{breakingNote}}}import{isAbsolute as isAbsolute2,join as join8}from"path";var fenceRE2=/^\s*(`{3,}|~{3,})/,headingRE2=/^(#{1,6})(\s.*)$/,schemeRE=/^[a-z][a-z\d+.-]*:/i,inlineLinkRE=/(\]\(\s*<?)((?:[^\s<>()]|\([^\s<>()]*\))+)/g,definitionRE=/^(\s{0,3}\[[^\]]+\]:\s*<?)([^\s<>]+)(>?(?:\s.*)?)$/,newlineRE=/\r?\n/,codeSpanRE=/(`+)[\s\S]*?\1/;function headingAnchor(text){return text.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu,"").replace(/\s/g,"-")}function resolveTarget(written,base,link){let target=link?.(written)??written;if(schemeRE.test(target)||target.startsWith("//"))return target;try{return new URL(target,base).href}catch{return target}}function resolveLinks(line,base,link){let definition=definitionRE.exec(line);if(definition)return`${definition[1]}${resolveTarget(definition[2],base,link)}${definition[3]}`;let rest=line,out="";while(rest){let code=codeSpanRE.exec(rest),text=code?rest.slice(0,code.index):rest;if(out+=text.replace(inlineLinkRE,(_,open,target)=>`${open}${resolveTarget(target,base,link)}`),!code)break;out+=code[0],rest=rest.slice(code.index+code[0].length)}return out}function withoutAnchor(url){let hash=url.indexOf("#");return hash===-1?url:url.slice(0,hash)}function withoutFrontmatter(lines){if(lines[0]?.trim()!=="---")return lines;let end=lines.findIndex((line,index)=>index>0&&line.trim()==="---");return end===-1?lines:lines.slice(end+1)}function parseHighlights(source,version,url,link){let lines=withoutFrontmatter(source.split(newlineRE)),section=[],fence,inside=!1;for(let line of lines){let marker=fenceRE2.exec(line)?.[1];if(fence===void 0&&marker===void 0){let heading=headingRE2.exec(line);if(heading?.[1]==="##"){if(inside)break;inside=heading[2].trim()===version;continue}if(inside&&heading){section.push(`${"#".repeat(Math.min(heading[1].length+1,6))}${heading[2]}`);continue}}if(marker!==void 0)fence=fence!==void 0&&marker.startsWith(fence)?void 0:fence??marker;if(inside)section.push(fence!==void 0||marker!==void 0?line:resolveLinks(line,url,link))}while(section.length&&!section[0].trim())section.shift();while(section.length&&!section.at(-1).trim())section.pop();return!section.length?void 0:{lines:section,link:`${withoutAnchor(url)}#${headingAnchor(version)}`}}async function readHighlights(options,cwd=process.cwd()){let highlights=options.highlights;if(highlights===void 0)return;let{file,url,link}=highlights,source=Bun.file(isAbsolute2(file)?file:join8(cwd,file));if(!await source.exists())return;return parseHighlights(await source.text(),getVersionString(options.tag,options.to),url,link)}function parseCommits(commits,config){return commits.map((commit)=>parseGitCommit(commit,config)).filter(p)}async function generate(options){let resolved=await resolveConfig(options),rawCommits=await getGitDiff(resolved.fromRoot===!0?void 0:resolved.from,resolved.to,resolved.firstParent),commits=parseCommits(rawCommits,resolved),contributors=resolved.contributors?await resolveAuthors(commits,resolved):[],highlights=await readHighlights(resolved),md=generateMarkdown(commits,resolved,contributors,highlights),discord=generateDiscordPayload(commits,resolved,contributors,highlights);return{config:resolved,md,discord,commits,contributors}}async function reporting(argv,run){let end=argv.indexOf("--"),json=(end===-1?argv:argv.slice(0,end)).includes("--json"),reports=[],code=await stdoutToStderr(json,async()=>run(argv,(value)=>reports.push(value)));if(json&&reports[0]!==void 0)printJson(reports[0]);return code}function failed(e,debug){if(e instanceof Exit)throw e;if(debug===!0&&e instanceof Error&&e.stack!==void 0)console.error(err().dim(e.stack.split(`
|
|
79
|
+
`).slice(1).join(`
|
|
80
|
+
`)));return fail(e instanceof Error?e.message:String(e),1)}async function ask2(question){return await confirm(question,{default:!1,hint:"pass --yes to skip the questions"})===!0}async function printManualRelease(config,md,heading){let file=join9(tmpdir(),`changelog-${config.to.replaceAll("/","-")}.md`);await Bun.write(file,md),console.log(),console.error(err().yellow(heading)),console.error(err().yellow(` https://${config.baseUrl}/${config.releaseRepo}/releases/new?tag=${encodeURIComponent(config.to)}`)),console.error(err().yellow(` pasting the notes saved to ${file}`)),console.log()}var RELEASE_EXITS=[[0,"it released, wrote --output or showed --dry-run"],[1,"the release could not be made (no token, the tag not on the forge, a shallow clone, an API error), an asset upload or the Discord post failed"],[2,"a usage error"]];async function release(argv,report){let parsed=parse(argv,`usage: changelog release [options]
|
|
81
|
+
|
|
82
|
+
--json prints {command, status (released, dry-run or saved), from, to, commits, notes, url, output, assetsFailed, discord (posted, failed or null)} on stdout and the progress on stderr; a failure is {error} on stderr.`,shared,{allowNegative:!0,positionals:[],exits:RELEASE_EXITS}),options=withToken(toOptions(parsed.values)),generated,code=0;try{console.log(),console.log(out().dim(`changelog v${version}`));let{config,md,discord,commits}=await generate(options),result={command:"release",status:"released",from:config.from,to:config.to,commits:commits.length,notes:md,url:null,output:null,assetsFailed:0,discord:null};if(generated={config,md},console.log(role("accent",process.stdout)(config.from)+out().dim(" -> ")+role("path",process.stdout)(config.to)+out().dim(` (${commits.length} commits)`)),console.log(out().dim("--------------")),console.log(),console.log(md.replace(/ /g,"")),console.log(),console.log(out().dim("--------------")),config.dry)return console.log(out().yellow(config.discordWebhook?"Dry run. Release and Discord post skipped.":"Dry run. Release skipped.")),await printManualRelease(config,md,"Create it manually at"),report({...result,status:"dry-run"}),0;if(typeof config.output==="string")return await Bun.write(config.output,md),console.log(out().yellow(`Saved to ${config.output}`)),report({...result,status:"saved",output:config.output}),0;if(!config.token)await printManualRelease(config,md,"Create it manually at"),fail(`no ${forgeName(config)} token found, pass --token or set GITHUB_TOKEN${config.provider==="github"?", or log in with gh auth login":""}, release skipped`,1);if(!await hasTagOnGitea(config.to,config))await printManualRelease(config,md,"Create it manually at"),fail(`the ref "${config.to}" is not available as a tag on ${forgeName(config)}, release skipped`,1);if(!commits.length&&await isRepoShallow())await printManualRelease(config,md,"Create it manually at"),fail("the repo seems to be cloned shallowly, which makes changelog fail to generate, specify `fetch-depth: 0` in your CI config",1);if(result.url=await sendRelease(config,md),config.assets?.length){if(result.assetsFailed=await uploadAssets(config,config.assets),result.assetsFailed>0)code=1}if(config.discordWebhook)try{await cr(config.discordWebhook,discord),console.log(out().green("Posted to Discord")),result.discord="posted"}catch(e){console.error(err().red(`Released, but the Discord post failed: ${String(e)}`)),result.discord="failed",code=1}return report(result),code}catch(e){if(generated&&!(e instanceof Exit))await printManualRelease(generated.config,generated.md,"Failed to create the release. Create it manually at");return failed(e,parsed.values.debug)}}var UNDO_EXITS=[[0,"it undid it, had nothing to undo, ran --dry-run or the question was declined"],[1,"a step fails"],[2,"a usage error"]];async function undo(argv,report){let{values:args,positionals}=parse(argv,`usage: changelog undo [tag] [options]
|
|
83
|
+
|
|
84
|
+
--json prints {command, status (undone, nothing, dry-run or declined), tag, releaseNote, remoteTag, localTag, commitReset: {hash, subject} or null} on stdout and the progress on stderr, each flag true when that step is (or, on a dry run, would be) taken. It asks no question: the release note is deleted with --note only, and anything to remove needs --yes or --dry-run (exit 2 otherwise).`,undoFlags,{positionals:["[tag]"],exits:UNDO_EXITS}),json=args.json===!0,tag=positionals[0],options=withToken(toOptions(args));try{if(console.log(),console.log(out().dim(`changelog v${version}`)),tag===void 0||tag===""){if(tag=(await getGitTags())[0],tag===void 0)return console.log(out().yellow("No tags found, nothing to undo.")),report({command:"undo",status:"nothing",tag:null,releaseNote:!1,remoteTag:!1,localTag:!1,commitReset:null}),0;console.log(out().yellow(`No tag specified, using the latest tag "${out().bold(tag)}".`))}let config=await resolveConfig({...options,to:tag}),originRepo;try{originRepo=await getGiteaRepo()}catch{}let remoteViaGit=Boolean(originRepo)&&String(config.releaseRepo)===originRepo,release=config.token?await getRelease(config,tag):null,remoteTag=remoteViaGit?await hasRemoteGitTag(tag):Boolean(config.token)&&await hasRemoteTag(config,tag),localTag=await isRefGitTag(tag),commitToReset;if(localTag&&await getTagCommit(tag)===await getHeadCommit())commitToReset={hash:await getHeadCommit(),subject:await getCommitSubject("HEAD")};let deleteNote=release!==null&&(args.note===!0||!json&&shouldAskNote({release,note:args.note,yes:args.yes,dry:args["dry-run"]})&&await ask2(`Also delete the ${forgeName(config)} release note "${release.name||tag}"?`)),actions=[];if(deleteNote)actions.push(`${out().red("release note")} ${tag}`);if(remoteTag)actions.push(`${out().red("remote tag")} ${tag}`);if(localTag)actions.push(`${out().red("local tag")} ${tag}`);if(commitToReset)actions.push(`${out().red("commit")} reset --soft (${commitToReset.hash.slice(0,7)} "${commitToReset.subject}")`);else if(localTag)actions.push(out().dim(`commit skipped (${tag} is not HEAD)`));let result={command:"undo",status:"undone",tag,releaseNote:deleteNote,remoteTag,localTag,commitReset:commitToReset===void 0?null:{hash:commitToReset.hash,subject:commitToReset.subject}};if(!actions.length)return console.log(out().yellow(`Nothing to undo for "${tag}".`)),report({...result,status:"nothing"}),0;if(json&&args.yes!==!0&&args["dry-run"]!==!0)fail("--json asks no question, so removing needs --yes (or --dry-run to preview)");console.log(),console.log(`About to remove on ${out().bold(String(config.releaseRepo))}:`);for(let action of actions)console.log(` - ${action}`);if(console.log(),args["dry-run"])return console.log(out().yellow("Dry run. Nothing removed.")),report({...result,status:"dry-run"}),0;if(!args.yes&&!await ask2("Proceed?"))return console.log(out().yellow("Aborted.")),report({...result,status:"declined",releaseNote:!1,remoteTag:!1,localTag:!1,commitReset:null}),0;if(deleteNote)await deleteRelease(config,release.id),console.log(out().green(`Deleted release note ${tag}`));if(remoteTag){if(remoteViaGit)await deleteRemoteGitTag(tag);else await deleteRemoteTag(config,tag);console.log(out().green(`Deleted remote tag ${tag}`))}if(localTag)await deleteLocalTag(tag),console.log(out().green(`Deleted local tag ${tag}`));if(commitToReset)await softResetLastCommit(),console.log(out().green(`Reset commit ${commitToReset.hash.slice(0,7)} (changes kept in working tree)`));return report(result),0}catch(e){return failed(e,args.debug)}}process.exitCode=await runCli({name:"changelog",about:"generate the release notes and publish them",replaces:"writing the release notes by hand and posting them through the Forgejo or GitHub UI",examples:[["changelog --dry-run","the notes since the last tag, nothing published"],["changelog undo v1.2.0 --dry-run","what undoing that release would remove"]],commands:{release:{summary:"generate the release notes and publish them (the default)",run:async(argv)=>reporting(aliasFlags(argv),release)},undo:{summary:"undo a release: delete the remote/local tag and reset the bump commit",run:async(argv)=>reporting(aliasFlags(argv),undo)}},defaultCommand:"release"});
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-changelog",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "2.4.2",
|
|
5
|
+
"description": "Generates a release's changelog from its conventional commits and publishes it as a Forgejo release.",
|
|
6
|
+
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"homepage": "https://github.com/Kayno0o/cli/tree/main/packages/changelog#readme",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/Kayno0o/cli.git",
|
|
12
|
+
"directory": "packages/changelog"
|
|
13
|
+
},
|
|
14
|
+
"bugs": "https://github.com/Kayno0o/cli/issues",
|
|
15
|
+
"keywords": [
|
|
16
|
+
"forgejo",
|
|
17
|
+
"gitea",
|
|
18
|
+
"release",
|
|
19
|
+
"changelog",
|
|
20
|
+
"conventional-commits"
|
|
21
|
+
],
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"exports": {
|
|
24
|
+
".": "./src/index.ts"
|
|
25
|
+
},
|
|
26
|
+
"bin": {
|
|
27
|
+
"changelog": "./dist/cli.js"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist",
|
|
31
|
+
"src"
|
|
32
|
+
],
|
|
33
|
+
"engines": {
|
|
34
|
+
"bun": ">=1.4.3"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "$npm_execpath ../../scripts/build.ts src/cli.ts",
|
|
38
|
+
"changelog": "$npm_execpath src/cli.ts"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@kaynooo/cli-kit": "0.48.0",
|
|
42
|
+
"@kaynooo/utils": "3.1.0"
|
|
43
|
+
}
|
|
44
|
+
}
|