@kaisers-io/refs 0.5.1 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +80 -1
- package/README.md +18 -17
- package/dist/refs.mjs +11 -11
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,81 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.6.1] - 2026-08-03
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- `refs doctor`'s `skill` check no longer reports a skill that is installed and working as
|
|
15
|
+
missing. It only ever looked in `~/.claude/skills/refs` and `~/.codex/skills/refs`, but
|
|
16
|
+
`npx skills add kaisers-io/refs` — the documented installer — writes neither: it keeps one
|
|
17
|
+
real copy in a shared `.agents/skills/refs` directory and symlinks each agent's own
|
|
18
|
+
directory at it. A Claude Code user was rescued by that symlink; anyone without one — a
|
|
19
|
+
Codex-only user, or anyone whose install went to the current project rather than `$HOME` —
|
|
20
|
+
was told to install a skill they already had, and never saw the version comparison that
|
|
21
|
+
`0.6.0` made the point of this check. Five locations are now checked, in this order:
|
|
22
|
+
`~/.agents/skills/refs/SKILL.md` (`shared ~/.agents`), `$CLAUDE_CONFIG_DIR` or `~/.claude`
|
|
23
|
+
(`Claude Code`), `$CODEX_HOME` or `~/.codex` (`Codex`), `<cwd>/.agents/skills/refs`
|
|
24
|
+
(`project ./.agents`), and `<cwd>/.claude/skills/refs` (`project ./.claude`). The last two
|
|
25
|
+
are there because `skills add` installs into the current project unless `-g` is passed, and
|
|
26
|
+
implies `-y` when it runs inside an agent, so an agent-driven install never touches `$HOME`
|
|
27
|
+
at all — and because naming a single agent (`skills add … -a claude-code`) switches the
|
|
28
|
+
installer to copy mode, which skips the shared `.agents` directory entirely and writes only
|
|
29
|
+
that agent's own. Unlike its global counterpart, the project path takes no env override:
|
|
30
|
+
the installer hardcodes a relative `.claude/skills` there. Codex needs no counterpart at
|
|
31
|
+
all, being a universal agent whose project install lands in `./.agents` in every mode. The
|
|
32
|
+
locations are deduplicated by resolved real path, so the usual symlinked install is
|
|
33
|
+
reported once rather than once per agent, while two genuinely independent copies are both
|
|
34
|
+
compared and a problem in either wins.
|
|
35
|
+
- `refs doctor`'s "skill not found" message no longer claims the skill is not installed, and
|
|
36
|
+
no longer names directories it did not search. That list of locations is best-effort and
|
|
37
|
+
cannot be otherwise: the paths are the `skills` installer's implementation detail rather
|
|
38
|
+
than a documented contract, the canonical directory has moved before, and 74 agents carry a
|
|
39
|
+
global skills directory of their own. A skill installed for some other agent still works
|
|
40
|
+
and is simply invisible here, so the `detail` now names the locations it searched and keeps
|
|
41
|
+
the install hint for the case where the skill really is missing. Those names are derived
|
|
42
|
+
from the paths actually resolved, so with `$CLAUDE_CONFIG_DIR` or `$CODEX_HOME` set the
|
|
43
|
+
message names the override rather than the `~/.claude`/`~/.codex` it replaced — an override
|
|
44
|
+
moves the search, it does not widen it, and pointing anyone at the directory the check just
|
|
45
|
+
skipped would be worse than saying nothing. It stays a `warn`, never a `fail` — the skill's
|
|
46
|
+
own capability gate compares `refs --version` against the pin in the file the agent already
|
|
47
|
+
loaded and depends on none of this.
|
|
48
|
+
|
|
49
|
+
## [0.6.0] - 2026-08-03
|
|
50
|
+
|
|
51
|
+
### Changed
|
|
52
|
+
|
|
53
|
+
- **Breaking (`--json` only):** `refs list --json` and `refs show --json` no longer include
|
|
54
|
+
the ref's package data by default. Both now report a `packages_count` number instead; pass
|
|
55
|
+
`--packages` to get the names back (a sorted `string[]` on `list`, the full package map on
|
|
56
|
+
`show`). `refs show <a-140-package-monorepo> --json` drops from roughly 4,400 tokens to
|
|
57
|
+
about 100. Human output is unchanged — it never showed package data.
|
|
58
|
+
- **Breaking (`--json` only):** `refs show --json` no longer includes `sample_tags` unless
|
|
59
|
+
`--tags` is passed, and skips the `git tag` subprocess entirely when it isn't. Human
|
|
60
|
+
output is unchanged: it always probes for tags, and still prints the `tags:` line
|
|
61
|
+
whenever the probe found any.
|
|
62
|
+
- The agent skill is now **explicitly invoked only** — it no longer activates on its own.
|
|
63
|
+
Invoke it with `/refs` (Claude Code) or `$refs` (Codex). This is `disable-model-invocation`
|
|
64
|
+
in the frontmatter plus `policy.allow_implicit_invocation: false` in the new
|
|
65
|
+
`skills/refs/agents/openai.yaml`.
|
|
66
|
+
- The skill's reference files moved out of `references/` and now sit beside `SKILL.md` as
|
|
67
|
+
`INVESTIGATE.md`, `ADD.md`, `MAINTAIN.md`, and `ONBOARDING.md`, joined by a new
|
|
68
|
+
`COMMANDS.md` CLI reference. `npx skills add` and `skills update` replace the skill
|
|
69
|
+
directory wholesale, so nothing is left behind. **If you installed the skill by copying
|
|
70
|
+
files manually, delete the old `skills/refs/references/` directory** — it would otherwise
|
|
71
|
+
sit alongside the new files with stale instructions.
|
|
72
|
+
- The skill now pins the CLI version it was written against
|
|
73
|
+
(`metadata.cli_version` in its frontmatter), and the release workflow fails if that pin
|
|
74
|
+
drifts from the published CLI version.
|
|
75
|
+
- `refs doctor`'s `skill` check now compares that pinned `cli_version` against the running
|
|
76
|
+
CLI and names which side is behind, instead of only checking that `SKILL.md` exists. Both
|
|
77
|
+
`~/.claude/skills/refs` and `~/.codex/skills/refs` are checked, and a problem in either
|
|
78
|
+
wins over an `ok` in the other.
|
|
79
|
+
|
|
80
|
+
### Fixed
|
|
81
|
+
|
|
82
|
+
- The skill's frontmatter claimed macOS/Linux only. Windows has been fully supported since
|
|
83
|
+
0.5.0; the field is gone.
|
|
84
|
+
|
|
10
85
|
## [0.5.1] - 2026-07-30
|
|
11
86
|
|
|
12
87
|
### Added
|
|
@@ -218,7 +293,11 @@ trusted-publishing pipeline end to end.
|
|
|
218
293
|
installed git hooks.
|
|
219
294
|
- Agent skill (`skills/refs/`) documenting the investigate/add/maintain workflows.
|
|
220
295
|
|
|
221
|
-
[Unreleased]: https://github.com/kaisers-io/refs/compare/v0.
|
|
296
|
+
[Unreleased]: https://github.com/kaisers-io/refs/compare/v0.6.1...HEAD
|
|
297
|
+
[0.6.1]: https://github.com/kaisers-io/refs/compare/v0.6.0...v0.6.1
|
|
298
|
+
[0.6.0]: https://github.com/kaisers-io/refs/compare/v0.5.1...v0.6.0
|
|
299
|
+
[0.5.1]: https://github.com/kaisers-io/refs/compare/v0.5.0...v0.5.1
|
|
300
|
+
[0.5.0]: https://github.com/kaisers-io/refs/compare/v0.4.0...v0.5.0
|
|
222
301
|
[0.4.0]: https://github.com/kaisers-io/refs/compare/v0.3.0...v0.4.0
|
|
223
302
|
[0.3.0]: https://github.com/kaisers-io/refs/compare/v0.2.0...v0.3.0
|
|
224
303
|
[0.2.0]: https://github.com/kaisers-io/refs/compare/v0.1.3...v0.2.0
|
package/README.md
CHANGED
|
@@ -58,28 +58,29 @@ help is the authoritative, always-current reference.
|
|
|
58
58
|
|
|
59
59
|
## Commands
|
|
60
60
|
|
|
61
|
-
| Command | What it does
|
|
62
|
-
| -------------- |
|
|
63
|
-
| `refs init` | Seed or migrate the refs home directory, its config, and the git hooks guard.
|
|
64
|
-
| `refs add` | Add a git reference in two phases: propose (`--dry-run`), then finalize (`--proposal`).
|
|
65
|
-
| `refs list` | List configured refs with their staleness/missing checkout status.
|
|
66
|
-
| `refs show` | Show a configured ref:
|
|
67
|
-
| `refs sync` | Fetch (or re-clone, if the checkout is missing) configured refs — all by default.
|
|
68
|
-
| `refs resolve` | Resolve a git url, npm package name, import path, or ref-key suffix to its ref/package.
|
|
69
|
-
| `refs tag` | Resolve a version to its git tag, via the ref's (or a package's) `tag_format`.
|
|
70
|
-
| `refs edit` | Edit one field of a global setting, a ref, or a package.
|
|
71
|
-
| `refs remove` | Remove a configured ref: its config/state entry AND its checkout directory.
|
|
72
|
-
| `refs doctor` | Run environment/integrity checks (git, node, config, hooks, checkouts, ssh).
|
|
73
|
-
| `refs migrate` | Migrate the refs config to the current schema, seeding it if absent.
|
|
61
|
+
| Command | What it does |
|
|
62
|
+
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
|
63
|
+
| `refs init` | Seed or migrate the refs home directory, its config, and the git hooks guard. |
|
|
64
|
+
| `refs add` | Add a git reference in two phases: propose (`--dry-run`), then finalize (`--proposal`). |
|
|
65
|
+
| `refs list` | List configured refs with their staleness/missing checkout status. |
|
|
66
|
+
| `refs show` | Show a configured ref: entry, state, local path, package count (`--packages`/`--tags` add the package map and sample tags to `--json`). |
|
|
67
|
+
| `refs sync` | Fetch (or re-clone, if the checkout is missing) configured refs — all by default. |
|
|
68
|
+
| `refs resolve` | Resolve a git url, npm package name, import path, or ref-key suffix to its ref/package. |
|
|
69
|
+
| `refs tag` | Resolve a version to its git tag, via the ref's (or a package's) `tag_format`. |
|
|
70
|
+
| `refs edit` | Edit one field of a global setting, a ref, or a package. |
|
|
71
|
+
| `refs remove` | Remove a configured ref: its config/state entry AND its checkout directory. |
|
|
72
|
+
| `refs doctor` | Run environment/integrity checks (git, node, config, hooks, checkouts, ssh). |
|
|
73
|
+
| `refs migrate` | Migrate the refs config to the current schema, seeding it if absent. |
|
|
74
74
|
|
|
75
75
|
## Agent skill
|
|
76
76
|
|
|
77
77
|
The CLI pairs with one thin, cross-agent skill (Claude Code and Codex) that routes agent
|
|
78
78
|
questions ("how does zod implement codecs") to the right checkout via `refs resolve
|
|
79
|
-
--json` and keeps things fresh with `refs sync`/`refs doctor`.
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
79
|
+
--json` and keeps things fresh with `refs sync`/`refs doctor`. It is user-invoked — it
|
|
80
|
+
does not activate on its own; invoke it with `/refs` in Claude Code or `$refs` in Codex.
|
|
81
|
+
`refs init` prints the exact install command for your setup. The skill is distributed
|
|
82
|
+
from the GitHub repository, which is private during the current development phase — it
|
|
83
|
+
opens up when `refs` goes public.
|
|
83
84
|
|
|
84
85
|
## Changelog
|
|
85
86
|
|
package/dist/refs.mjs
CHANGED
|
@@ -347,24 +347,24 @@ sync_ttl = "1h"
|
|
|
347
347
|
`).map(e=>e.trim()).filter(e=>e!==``).slice(0,n),Ac=async(e,t,n)=>(await e.run(`git`,[`show-ref`,`--verify`,`--`,`refs/tags/${n}`],{cwd:t})).exitCode===0,jc=[`#!/bin/sh`,`echo "refs: this checkout is a managed read-only reference — commits are blocked" >&2`,`exit 1`,``].join(`
|
|
348
348
|
`),Mc=async e=>{await Promise.all([`pre-commit`,`pre-push`].map(async n=>{let r=m(e.hooksDir,n);await Bs(r,jc),await t(r,493)}))},Nc=/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/u,Pc=/\d+\.\d+\.\d+/gu,Fc=e=>ts.safeParse(e).success,Ic=e=>{let t=e.match(Pc);return t!==null&&t.length>1},Lc=e=>{let t=Nc.exec(e);if(!t||Ic(e))return;let[n]=t,r=e.replace(n,`{version}`);if(Fc(r))return r},Rc=(e,t,n)=>{let r=e.get(t);r===void 0?e.set(t,{count:1,index:n}):r.count+=1},zc=e=>{let t=new Map;for(let[n,r]of e.entries()){let e=Lc(r);e&&Rc(t,e,n)}return t},Bc=(e,t)=>e.count>t.count||e.count===t.count&&e.index<t.index,Vc=e=>{let t=[...e.entries()],[n]=t;if(n===void 0)return null;let[r,i]=n;return t.slice(1).reduce(({format:e,data:t},[n,r])=>Bc(r,t)?{data:r,format:n}:{data:t,format:e},{data:i,format:r}).format},Hc=e=>{let t=zc(e);return Vc(t)},Uc=(e,t)=>e.replaceAll(`{version}`,()=>t),Wc=async(e,t,n,r)=>{let i=Uc(n,r);if(!await Ac(e,t,i))throw v(`tag '${i}' not found in ${t} — check the version or tag_format`);return i},Gc=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)?[\s\S]*@/iu,q=e=>{let t=e.replace(Gc,`$<scheme><redacted>@`);return t.length<=200?t:`${t.slice(0,200)}…`},Kc=/^git@(?<host>[^:/\s]+):(?<path>[^\s]+)$/u,qc=/^git\+/u,Jc={"https:":`443`,"ssh:":`22`},Yc=e=>e.replace(/\.git$/u,``),Xc=e=>e.split(`/`).some(e=>e===`.`||e===`..`),Zc=e=>e.includes(`\\`),Qc=e=>e.includes(`%`),$c=e=>{let t=z.safeParse(e);if(!t.success)throw b(`not a supported git url: derived key '${q(e)}' is invalid`);return t.data},el=({host:e,port:t,protocol:n})=>{let r=Jc[n];return t===``||t===r?e.toLowerCase():`${e.toLowerCase()}_${t}`},tl=e=>{let t=Yc(e.path.replace(/^\/+/u,``).replace(/\/+$/u,``));return $c(`${el(e)}/${t}`)},nl=e=>{let t=decodeURIComponent(e).split(`/`).filter(e=>e!==``);if(t.length<2)throw b(`not a supported git url: file url path must have at least 2 segments`);let n=t.at(-2)??``,r=t.at(-1)??``;return $c(`local/${n}/${r}`)},rl=(e,t)=>{try{return new URL(e)}catch{throw b(`not a supported git url: ${q(t)}`)}},il=e=>{if(e.password!==``)throw b(`not a supported git url: credentials embedded in url`);if(e.protocol===`https:`&&e.username!==``)throw b(`not a supported git url: credentials embedded in https url`)},al=(e,t)=>{if(e.protocol===`file:`){if(!t)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return nl(e.pathname)}if(e.protocol!==`https:`&&e.protocol!==`ssh:`)throw b(`not a supported git url: unsupported protocol ${e.protocol}`);return il(e),tl({host:e.hostname,path:e.pathname,port:e.port,protocol:e.protocol})},ol=(e,t)=>{if(Qc(e))throw b(`not a supported git url: percent-encoding not supported in ${q(t)}`);if(e.includes(`:`))throw b(`not a supported git url: ambiguous ':' in scp-style path ${q(t)}; use the ssh:// url form instead`);if(e.startsWith(`/`)||e.startsWith(`~`))throw b(`not a supported git url: ambiguous absolute/home-relative scp path in ${q(t)}; use the ssh:// url form instead`)},sl=(e,t)=>{let n=e.groups?.path??``;return ol(n,t),tl({host:e.groups?.host??``,path:n,port:``,protocol:`ssh:`})},cl=(e,t)=>{if(Zc(e))throw b(`not a supported git url: backslash not allowed in ${q(t)}`)},ll=(e,t)=>{if(Xc(e))throw b(`not a supported git url: path traversal segment in ${q(t)}`)},ul=(e,t,n)=>{if(e.protocol!==`file:`&&Qc(t))throw b(`not a supported git url: percent-encoding not supported in ${q(n)}`)},dl=(e,t)=>{let n=t?.allowFileUrls??!1,r=e.replace(qc,``);cl(r,e),ll(r,e);let i=Kc.exec(r);if(i?.groups!==void 0)return{cloneUrl:r,key:sl(i,e)};let a=rl(r,e);return ul(a,r,e),{cloneUrl:r,key:al(a,n)}},fl=`.git`,pl=e=>e.replace(/^\/+/u,``).replace(/\/+$/u,``),ml=e=>e.endsWith(fl)?e:`${e}${fl}`,hl=(e,t)=>`https://${e.toLowerCase()}/${pl(t)}`,gl=(e,t)=>`git@${e.toLowerCase()}:${ml(pl(t))}`,_l=e=>{if(e===`https:`)return`https`;if(e===`ssh:`)return`ssh`;throw b(`not a supported git url: unsupported protocol ${e}`)},vl=(e,t,n)=>{let r=Jc[e.protocol];if(e.port!==``&&e.port!==r)throw b(`cannot apply git_transport=${t} to ${q(n)}: its non-default port ${e.port} cannot be expressed in the ${t} url form — add the repo with an explicit url instead`)},yl=(e,t)=>t===`https`?hl(e.hostname,e.pathname):gl(e.hostname,e.pathname),bl=(e,t,n)=>{let r=dl(t).key;if(r!==n)throw b(`git_transport transform changed repo identity: '${q(e)}' → '${t}' (key '${n}' → '${r}')`);return t},xl=(e,t)=>{if(t.transport===`ssh`)return t.cloneUrl;let n=e.groups?.host??``,r=e.groups?.path??``;return bl(t.cloneUrl,hl(n,r),t.originalKey)},Sl=e=>{let t=rl(e.cloneUrl,e.cloneUrl);return _l(t.protocol)===e.transport?e.cloneUrl:(vl(t,e.transport,e.cloneUrl),bl(e.cloneUrl,yl(t,e.transport),e.originalKey))},Cl=(e,t)=>{if(e.startsWith(`file:`))return e;let n={cloneUrl:e,originalKey:dl(e).key,transport:t},r=Kc.exec(e);return r?.groups===void 0?Sl(n):xl(r,n)},wl=`meta.json`,Tl=e=>{if(typeof e==`object`&&e&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}},El=e=>{try{return process.kill(e,0),!0}catch(e){return Tl(e)!==`ESRCH`}},Dl=e=>{try{return JSON.parse(e)}catch{return}},Ol=async e=>{try{return await o(e,`utf8`)}catch{return}},kl=e=>{if(typeof e!=`string`)return;let t=Date.parse(e);if(!Number.isNaN(t))return t},Al=e=>{if(typeof e!=`object`||!e)return;let t=e,{pid:n}=t,r=kl(t.acquired_at);if(typeof n==`number`&&r!==void 0)return{acquiredAtMs:r,pid:n}},jl=async e=>{let t=await Ol(m(e,wl));if(t!==void 0)return Al(Dl(t))},Ml=e=>{if(typeof e!=`object`||!e)return;let{token:t}=e;if(typeof t==`string`)return t},Nl=async e=>{let t=await Ol(m(e,wl));if(t!==void 0)return Ml(Dl(t))},Pl=async e=>{try{return(await f(e)).mtimeMs}catch{return}},Fl=async(e,t)=>{let n=m(e,wl),r=`${n}.tmp-${ce()}`;await ee(r,t,`utf8`),await l(r,n)},Il=async(e,t)=>{await Fl(e,JSON.stringify({acquired_at:new Date().toISOString(),pid:process.pid,token:t}))},Ll=new Set([`EEXIST`,`EPERM`,`EACCES`,`EBUSY`]),Rl=new Set([`ENOENT`,`EPERM`,`EACCES`,`EBUSY`]),zl=async e=>{try{return await a(e,{recursive:!1}),!0}catch(e){let t=Tl(e);if(t!==void 0&&Ll.has(t))return!1;throw e}},Bl=async(e,t)=>{try{return await l(e,t),!0}catch(e){let t=Tl(e);if(t!==void 0&&Rl.has(t))return!1;throw e}},Vl=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/u,Hl=async e=>{let t=await jl(e);if(t===void 0){let t=await Pl(e);return t!==void 0&&Date.now()-t>5e3}return Date.now()-t.acquiredAtMs>6e5||!El(t.pid)},Ul=async(e,t)=>{try{await Il(e,t)}catch(e){if(Tl(e)===`ENOENT`)return`retry`;throw e}return t},Wl=async e=>{if(!await zl(e))return;let t=await Ul(e,ce());return t===`retry`?Wl(e):t},Gl=e=>m(e.locksDir,`${e.name}.steal-claim`),Kl=e=>m(e.locksDir,`${e.name}.steal.${ce()}`),ql=async e=>{let t=await Pl(e);return t!==void 0&&Date.now()-t>2e3},Jl=async e=>await zl(e)?!0:await ql(e)?(await u(e,{force:!0,recursive:!0}),zl(e)):!1,Yl=async e=>{let t=Kl(e);return await Bl(e.lockPath,t)?t:void 0},Xl=async e=>{if(!await Hl(e.lockPath))return;let t=await Yl(e);t!==void 0&&await u(t,{force:!0,recursive:!0})},Zl=async e=>{let t=Gl(e);if(await Jl(t))try{await Xl(e)}finally{await u(t,{force:!0,recursive:!0})}},Ql=async(e,t)=>{if(await Hl(e.lockPath)){await Zl(e);return}if(Date.now()>=t)throw ye(`lock ${e.name} is held — another refs process is running`);await pe(100)},$l=async(e,t)=>{let n=await Wl(e.lockPath);return n===void 0?(await Ql(e,t),$l(e,t)):n},eu=async(e,t)=>{await Nl(e)===t&&await u(e,{force:!0,recursive:!0})},tu=e=>{if(e===`.`||e===`..`||!Vl.test(e))throw b(`lock name must not contain "/" or other unsafe characters — only letters, digits, and "_.-" are allowed, and it may not be "." or "..": ${e}`)},J=async(e,t,n,r)=>{tu(t);let i={lockPath:m(e.locksDir,t),locksDir:e.locksDir,name:t};await a(e.locksDir,{recursive:!0});let o=Date.now()+(r?.timeoutMs??1e4),s=await $l(i,o);try{return await n()}finally{await eu(i.lockPath,s)}},nu=ro({directory:I().optional(),url:I().optional()}),ru=ro({repository:ao([I(),nu]).optional()}),iu=/^(?:@[a-z0-9-~][a-z0-9._~-]*\/)?[a-z0-9-~][a-z0-9._~-]*$/u,au=new Set([`node_modules`,`favicon.ico`]),ou=e=>v(`package '${e}' has no usable repository field — find the repository and run: refs add <git-url>`),su=e=>{let[t,n]=e.split(`/`);return n??t??e},cu=e=>{if(e.length>214)throw y(`invalid package name: '${e}' exceeds maximum length of 214 characters`);if(!iu.test(e))throw y(`invalid package name: '${e}' does not match npm naming rules`);let t=su(e);if(au.has(t))throw y(`invalid package name: '${e}' uses a reserved name`)},lu=e=>e.replace(`/`,`%2F`),uu=e=>typeof e==`string`?e:e?.url,du=e=>{if(typeof e==`object`&&e?.directory){let t=ns.safeParse(e.directory);if(t.success)return t.data}},fu=async(e,t)=>{try{return await e.json()}catch{throw b(`invalid npm registry response for '${t}': not parseable JSON`)}},pu=async(e,t)=>{let n=await e(`https://registry.npmjs.org/${lu(t)}`);if(n.status===404)throw v(`npm package '${t}' not found`);if(n.status!==200)throw b(`failed to fetch npm package '${t}': status ${n.status}`);let r=await fu(n,t),i=ru.safeParse(r);if(!i.success)throw b(`invalid npm package response for '${t}'`);return i.data},mu=(e,t)=>{try{return dl(e)}catch{throw ou(t)}},hu=async(e,t)=>{cu(t);let n=await pu(e,t),r=uu(n.repository);if(r===void 0||r===``)throw ou(t);let{cloneUrl:i,key:a}=mu(r,t),o=du(n.repository);return o===void 0?{cloneUrl:i,key:a}:{cloneUrl:i,directory:o,key:a}},gu=new Set;let _u=!1;const vu=()=>{for(let e of gu)try{e.kill(`SIGKILL`)}catch{}},yu=[`SIGINT`,`SIGTERM`,`SIGHUP`,`SIGBREAK`],bu=e=>{let t=()=>{vu(),process.removeListener(e,t),process.kill(process.pid,e)};process.on(e,t)},xu=()=>{_u||(_u=!0,yu.forEach(e=>{bu(e)}),process.on(`exit`,vu))},Su=()=>{let e=[],t=0,n=!1;return{finish:()=>({text:Buffer.concat(e).toString(`utf8`),truncated:n}),push:r=>{if(n)return;let i=67108864-t;if(r.length<=i){e.push(r),t+=r.length;return}i>0&&e.push(r.subarray(0,i)),n=!0}}},Cu=(e,t)=>[e.replace(/\r?\n$/u,``),t].filter(e=>e!==``).join(`
|
|
349
349
|
`),wu=(e,t,n)=>{let r=e;return t.truncated&&(r=Cu(r,`refs: stdout exceeded 67108864 bytes, truncated`)),n.truncated&&(r=Cu(r,`refs: stderr exceeded 67108864 bytes, truncated`)),r},Tu={clear:()=>{},markedTimedOut:()=>!1},Eu=(e,t)=>{if(t===void 0)return Tu;let n=!1,r,i=setTimeout(()=>{n=!0,e.kill(`SIGTERM`),r=setTimeout(()=>{e.kill(`SIGKILL`)},2e3)},t);return{clear:()=>{clearTimeout(i),r!==void 0&&clearTimeout(r)},markedTimedOut:()=>n}},Du=e=>e===void 0?{}:{cwd:e},Ou=(e,t)=>Cu(e,`refs: command timed out after ${String(t)}ms`),ku=(e,t)=>({exitCode:124,stderr:Ou(e,t),stdout:``,timedOut:!0}),Au=(e,t,n)=>{let r=_e(e,t,{...Du(n?.cwd),stdio:[`ignore`,`pipe`,`pipe`]});gu.add(r);let i=Su(),a=Su();return r.stdout.on(`data`,e=>{i.push(e)}),r.stderr.on(`data`,e=>{a.push(e)}),{child:r,stderrCollector:a,stdoutCollector:i,timeout:Eu(r,n?.timeoutMs)}},ju=(e,t,n)=>{try{return Au(e,t,n)}catch(e){return{exitCode:127,stderr:Nu(e),stdout:``}}},Mu=e=>!(`child`in e),Nu=e=>e instanceof Error?e.message:String(e),Pu=async e=>{try{let[t]=await he(e,`close`);return{code:t}}catch(e){return{code:null,errorMessage:Nu(e)}}},Fu=e=>e===null?1:e,Iu=(e,t)=>t.truncated?{...e,stdoutTruncated:!0}:e,Lu=e=>e.timedOut?ku(e.stderr.text,e.timeoutMs):e.errorMessage===void 0?Iu({exitCode:Fu(e.code),stderr:wu(e.stderr.text,e.stdout,e.stderr),stdout:e.stdout.text},e.stdout):Iu({exitCode:127,stderr:Cu(e.stderr.text,e.errorMessage),stdout:e.stdout.text},e.stdout);var Ru=class{async run(e,t,n){xu();let r=ju(e,t,n);if(Mu(r))return r;let i=await Pu(r.child);return gu.delete(r.child),r.timeout.clear(),Lu({code:i.code,errorMessage:i.errorMessage,stderr:r.stderrCollector.finish(),stdout:r.stdoutCollector.finish(),timedOut:r.timeout.markedTimedOut(),timeoutMs:n?.timeoutMs})}};const zu=os.partial({description:!0}),Bu=R({default_branch:I().min(1),key:z,tag_format_candidate:ts.nullable(),url:I().min(1)});Bu.extend({description:I().default(``),packages:Vo(zu)});const Vu=Bu.extend({description:I().min(1),packages:Vo(os)}),Hu=R({effective_clone_mode:$o.optional(),head_sha:I().regex(/^[0-9a-f]{40}$/u,`head_sha must be a 40-character lowercase hex string`).optional(),last_error:I().optional(),last_fetched_at:ia().optional(),pending_proposal_at:ia().optional()}),Uu=R({refs:zo(e=>e.length>0&&!Ro.has(e),()=>`state ref key must be non-empty and not "__proto__", "constructor", or "prototype"`,lo(I(),Hu)).default({})}),Y=(e,t,n)=>t?.[e]??n[e],Wu=async e=>{try{return await o(e.statePath,`utf8`)}catch(e){if(V(e))return;throw e}},Gu=e=>{try{return JSON.parse(e)}catch{return}},X=async e=>{let t=await Wu(e);if(t===void 0)return Uu.parse({});let n=Gu(t);if(n===void 0)return Uu.parse({});let r=Uu.safeParse(n);return r.success?r.data:Uu.parse({})},Ku=async(e,t)=>{let n=Uu.safeParse(t);if(!n.success)throw b(O(n.error));await Bs(e.statePath,`${JSON.stringify(n.data,void 0,2)}\n`)},qu=/[/\\]/u,Ju={kind:`ignore`},Yu=e=>!re(e)&&e.split(qu).every(e=>e!==`.`&&e!==`..`),Xu=e=>Yu(e)&&!e.startsWith(`!`)&&!e.includes(`**`)&&(e.match(/\*/gu)??[]).length<=1,Zu=e=>Xu(e)?e.endsWith(`/*`)?{baseDir:e.slice(0,-2),kind:`expand-children`}:e===`*`?{baseDir:`.`,kind:`expand-children`}:e.includes(`*`)?Ju:{dir:e,kind:`probe-dir`}:Ju,Qu=(e,t)=>{if(t&&e===``)return!0;let n=e===`..`||e.startsWith(`..`+se);return e!==``&&!n&&!re(e)},$u=(e,t,n)=>t.filter((e,t)=>n[t]===!0).map(t=>ie.join(e,t)),ed=(e,t)=>t?.name?{description:t.description,name:t.name,path:e}:void 0,td=e=>{let t=e.map(e=>[e.path,e]),n=[...new Map(t).values()];return n.sort((e,t)=>e.path.localeCompare(t.path)),n},nd=/^\s*-\s+["']?(?<pattern>[^"'#]+)["']?/u,rd=/^packages:\s*(?:#.*)?$/u,id=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ad=e=>{if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(!id(e))return[];let{packages:t}=e;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]},od=Symbol(`end-of-section`),sd=e=>{let t=e.trim();if(t&&!t.startsWith(`-`)&&t.includes(`:`)&&!rd.test(e))return od;if(!t.startsWith(`-`))return;let n=nd.exec(e)?.groups?.pattern?.trim();if(n)return n},cd=e=>{let t=[];for(let n of e){let e=sd(n);if(e===od)break;e!==void 0&&t.push(e)}return t},ld=e=>{let t=e.findIndex(e=>rd.test(e));return t===-1?[]:cd(e.slice(t+1))},ud=e=>{let{name:t}=e;if(typeof t==`string`)return t},dd=e=>{let{description:t}=e;if(typeof t==`string`)return t},fd=async(e,t,n=!1)=>{try{return Qu(ae(await c(e),await c(t)),n)}catch{return!1}},pd=async(e,t)=>{try{let n=m(t,`package.json`);return await fd(e,n)?(await o(n,`utf8`),!0):!1}catch{return!1}},md=async(e,t)=>{try{let n=m(e,t);if(!await fd(e,n,t===`.`))return[];let r=(await s(n,{withFileTypes:!0})).filter(e=>e.isDirectory()),i=await Promise.all(r.map(t=>pd(e,m(n,t.name))));return $u(t,r.map(e=>e.name),i)}catch{return[]}},hd=async(e,t)=>{let n=Zu(t);if(n.kind===`expand-children`)return md(e,n.baseDir);if(n.kind===`probe-dir`){let t=m(e,n.dir);if(await fd(e,t)&&await pd(e,t))return[n.dir]}return[]},gd=async(e,t)=>{try{let n=m(t,`package.json`);if(!await fd(e,n))return;let r=await o(n,`utf8`),i=JSON.parse(r);return{description:dd(i),name:ud(i)}}catch{return}},_d=async(e,t)=>{let n=new Set;try{if(!await fd(e,t))return n;let r=await o(t,`utf8`);ad(JSON.parse(r).workspaces).forEach(e=>n.add(e))}catch{}return n},vd=async(e,t)=>{let n=new Set;try{if(!await fd(e,t))return n;ld((await o(t,`utf8`)).split(`
|
|
350
|
-
`)).forEach(e=>n.add(e))}catch{}return n},yd=async(e,t)=>{let n=new Set,r=[...t].map(t=>hd(e,t));return(await Promise.all(r)).forEach(e=>{e.forEach(e=>n.add(e))}),n},bd=async(e,t)=>{let n=m(e,t);if(await fd(e,n))return ed(t,await gd(e,n))},xd=async(e,t)=>{let n=[...t].map(t=>bd(e,t));return(await Promise.all(n)).filter(e=>e!==void 0)},Sd=async e=>{let t=m(e,`package.json`),n=m(e,`pnpm-workspace.yaml`),r=await _d(e,t),i=await vd(e,n),a=new Set([...r,...i]);if(a.size===0)return[];let o=await yd(e,a);return td(await xd(e,o))}
|
|
350
|
+
`)).forEach(e=>n.add(e))}catch{}return n},yd=async(e,t)=>{let n=new Set,r=[...t].map(t=>hd(e,t));return(await Promise.all(r)).forEach(e=>{e.forEach(e=>n.add(e))}),n},bd=async(e,t)=>{let n=m(e,t);if(await fd(e,n))return ed(t,await gd(e,n))},xd=async(e,t)=>{let n=[...t].map(t=>bd(e,t));return(await Promise.all(n)).filter(e=>e!==void 0)},Sd=async e=>{let t=m(e,`package.json`),n=m(e,`pnpm-workspace.yaml`),r=await _d(e,t),i=await vd(e,n),a=new Set([...r,...i]);if(a.size===0)return[];let o=await yd(e,a);return td(await xd(e,o))};var Cd=`0.6.1`;const wd=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString(`utf8`)},Td=()=>({cliVersion:Cd,cwd:process.cwd(),env:process.env,errLine:e=>{process.stderr.write(`${e}\n`)},fetcher:e=>fetch(e),nodeVersion:process.version,out:e=>{process.stdout.write(`${e}\n`)},readStdin:wd,runner:new Ru});var Ed=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},Dd=class extends Ed{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},Od=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new Dd(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function kd(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var Ad=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(e=>kd(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(t?` `+t:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
|
|
351
351
|
`)}displayWidth(e){return ve(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
|
|
352
352
|
`+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
|
|
353
|
-
`)}},
|
|
353
|
+
`)}},jd=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Pd(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new Dd(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?Nd(this.name().replace(/^no-/,``)):Nd(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Md=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function Nd(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Pd(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
|
|
354
354
|
- a short flag is a single dash and a single character
|
|
355
355
|
- either use a single dash and a single character (for a short flag)
|
|
356
356
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
|
|
357
357
|
- too many short flags`):i.test(t)?Error(`${n}
|
|
358
358
|
- too many long flags`):Error(`${n}
|
|
359
|
-
- unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function
|
|
360
|
-
- specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
361
|
-
Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new
|
|
362
|
-
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof
|
|
359
|
+
- unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function Fd(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function Id(e,t){if(!t||t.length===0)return``;t=Array.from(new Set(t));let n=e.startsWith(`--`);n&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let r=[],i=3;return t.forEach(t=>{if(t.length<=1)return;let n=Fd(e,t),a=Math.max(e.length,t.length);(a-n)/a>.4&&(n<i?(i=n,r=[t]):n===i&&r.push(t))}),r.sort((e,t)=>e.localeCompare(t)),n&&(r=r.map(e=>`--${e}`)),r.length>1?`\n(Did you mean one of ${r.join(`, `)}?)`:r.length===1?`\n(Did you mean ${r[0]}?)`:``}var Ld=class e extends me{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>h.stdout.write(e),writeErr:e=>h.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>h.stdout.isTTY?h.stdout.columns:void 0,getErrHelpWidth:()=>h.stderr.isTTY?h.stderr.columns:void 0,getOutHasColors:()=>zd()??(h.stdout.isTTY&&h.stdout.hasColors?.()),getErrHasColors:()=>zd()??(h.stderr.isTTY&&h.stderr.hasColors?.()),stripColor:e=>ve(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new Ad,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
|
|
360
|
+
- specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Od(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
|
|
361
|
+
Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new Ed(e,t,n)),h.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new jd(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
362
|
+
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof jd)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){h.versions?.electron&&(t.from=`electron`);let e=h.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=h.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:h.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,`default`)}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
363
363
|
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(le.existsSync(e))return;let r=`'${e}' does not exist
|
|
364
364
|
- if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
365
365
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
366
|
-
- ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function r(e,t){let r=p.resolve(e,t);if(le.existsSync(r))return r;if(n.includes(p.extname(t)))return;let i=n.find(e=>le.existsSync(`${r}${e}`));if(i)return`${r}${i}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||``;if(this._scriptPath){let e;try{e=le.realpathSync(this._scriptPath)}catch{e=this._scriptPath}a=p.resolve(p.dirname(e),a)}if(a){let t=r(a,i);if(!t&&!e._executableFile&&this._scriptPath){let n=p.basename(this._scriptPath,p.extname(this._scriptPath));n!==this._name&&(t=r(a,`${n}-${e._name}`))}i=t||i}let o=n.includes(p.extname(i)),s;h.platform===`win32`?(this._checkForMissingExecutable(i,a,e._name),t.unshift(i),t=
|
|
367
|
-
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in h.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,h.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
368
|
-
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function Ld(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function Rd(){if(h.env.NO_COLOR||h.env.FORCE_COLOR===`0`||h.env.FORCE_COLOR===`false`)return!1;if(h.env.FORCE_COLOR||h.env.CLICOLOR_FORCE!==void 0)return!0}new Id;const zd=[],Bd=e=>Array.isArray(e)?e:[e],Vd=e=>e===void 0?zd:[e],Hd=e=>e instanceof Error?e.message:String(e),Z=e=>{let t=e.optsWithGlobals();return{json:t.json===!0,verbose:t.verbose===!0}},Q=(e,t,n,r,i)=>{if(t.json){let t={data:r,ok:!0,warnings:i??zd};e.out(JSON.stringify(t));return}for(let t of Bd(n))e.out(t);for(let t of i??zd)e.errLine(`refs: warning: ${t}`)},Ud=(e,t,n)=>{if(t.json){let t={error:{code:n.code,message:n.message},ok:!1};e.out(JSON.stringify(t));return}e.errLine(`refs: ${n.message}`)},Wd=(e,t)=>{e.errLine(`refs: ${t}`)},$=(e,t,n)=>async()=>{try{await n()}catch(n){let r=xe(n,{verbose:t.verbose});Ud(e,t,r),process.exitCode=r.exitCode}};var Gd=`0.5.1`;const Kd=async e=>{let t=await e.runner.run(`git`,[`--version`]);return t.exitCode===0?{detail:t.stdout.trim(),name:`git`,status:`ok`}:{detail:t.stderr.trim()||`git --version exited with code ${t.exitCode}`,name:`git`,status:`fail`}},qd=/^v(?<major>\d+)\.(?<minor>\d+)/u,Jd=e=>{let t=qd.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},Yd=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=12,Xd=e=>{let{nodeVersion:t}=e;return Yd(Jd(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.12`,name:`node`,status:`fail`}},Zd=()=>cs.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),Qd=async e=>{try{return{config:await W(e)}}catch(e){return{config:Zd(),errorMessage:Hd(e)}}},$d=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},ef=[`.claude`,`skills`,`refs`,`SKILL.md`],tf=[`.codex`,`skills`,`refs`,`SKILL.md`],nf=e=>e===void 0?[]:[m(e,...ef),m(e,...tf)],rf=async t=>{try{return await e(t),!0}catch{return!1}},af=async e=>{let t=nf(e.env.HOME);return(await Promise.all(t.map(e=>rf(e)))).some(Boolean)?{detail:`the refs skill is installed`,name:`skill`,status:`ok`}:{detail:`refs skill not found — install it: npx skills add kaisers-io/refs`,name:`skill`,status:`warn`}},of=(e,t)=>Object.keys(t.refs).map(t=>({dest:U(e,z.parse(t)),key:t})).filter(e=>G(e.dest)),sf=[`pre-commit`,`pre-push`],cf=async(t,r)=>{try{return await e(m(t.hooksDir,r),n.X_OK),!0}catch{return!1}},lf=async e=>{let t=await Promise.all(sf.map(t=>cf(e,t)));return sf.filter((e,n)=>!t[n])},uf=async(e,t,n)=>{let r=await e.runner.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:n});return r.exitCode===0&&r.stdout.trim()===t.hooksDir},df=e=>e.missingHooks.length>0?{detail:`${e.missingHooks.map(e=>`hooks/${e}`).join(`, `)} missing or not executable — run: refs init`,name:`hooks-guard`,status:`fail`}:e.badKeys.length>0?{detail:`core.hooksPath not set for: ${e.badKeys.join(`, `)} — run: refs init`,name:`hooks-guard`,status:`fail`}:{detail:`${sf.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},ff=async(e,t,n)=>{let r=of(t,n),[i,a]=await Promise.all([lf(t),Promise.all(r.map(n=>uf(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return df({badKeys:o,checkoutCount:r.length,missingHooks:i})},pf=async(e,t)=>{let n=await e.runner.run(`git`,[`status`,`--porcelain`],{cwd:t.dest});return n.exitCode===0?{broken:!1,detail:``,dirty:n.stdout.trim()!==``,key:t.key}:{broken:!0,detail:n.stderr.trim(),dirty:!1,key:t.key}},mf=e=>{let t=e.filter(e=>e.broken);if(t.length>0)return{detail:t.map(e=>`${e.key}: git status failed — ${e.detail}`).join(`; `),name:`dirty-checkouts`,status:`fail`};let n=e.filter(e=>e.dirty).map(e=>e.key);return n.length===0?{detail:`no local changes in any checkout`,name:`dirty-checkouts`,status:`ok`}:{detail:`local changes will be discarded on next sync: ${n.join(`, `)}`,name:`dirty-checkouts`,status:`warn`}},hf=async(e,t,n)=>{let r=of(t,n),i=await Promise.all(r.map(t=>pf(e,t)));return mf(i)},gf=async e=>{try{return await X(e)}catch{return Uu.parse({})}},_f=async e=>{try{return(await s(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(V(e))return[];throw e}},vf=async(e,t)=>{if(G(e))return[[...t]];let n=await _f(e);return(await Promise.all(n.map(n=>vf(m(e,n),[...t,n])))).flat()},yf=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},bf=(e,t,n)=>yf(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: rm -rf ${e.dest}`,xf=(e,t)=>({dest:m(e.sourcesDir,...t),key:t.join(`/`)}),Sf=async(e,t,n)=>{let r=(await vf(e.sourcesDir,[])).map(t=>xf(e,t)).filter(e=>!Object.hasOwn(t.refs,e.key));if(r.length===0)return{detail:`no orphaned checkouts under sources/`,name:`orphans`,status:`ok`};let i=Date.now();return{detail:r.map(e=>bf(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},Cf=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,wf=e=>e===``?{}:{user:e},Tf=e=>e===``?{}:{port:e},Ef=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...wf(t.username),...Tf(t.port)}:void 0}catch{return}},Df=e=>{let t=Cf.exec(e),n=t?.groups?.host;return n===void 0?Ef(e):{host:n,user:t?.groups?.user??`git`}},Of=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,kf=e=>e.user===void 0?Of(e):`${e.user}@${Of(e)}`,Af=e=>{let t=Object.values(e.refs).map(e=>Df(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(kf(e),e);return[...n.values()].toSorted((e,t)=>kf(e).localeCompare(kf(t)))},jf=/Permission denied/u,Mf=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],Nf=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,Pf=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=Nf(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},Ff=async(e,t,n)=>{let r=kf(t),i=await e.runner.run(`ssh`,Pf(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:jf.test(i.stderr)?{host:r,outcome:`denied`}:Mf.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},If=(e,t)=>{let n=e.filter(e=>e.outcome===`timeout`).map(e=>e.host);if(n.length!==0)return{detail:`ssh probe timed out after ${t/1e3}s: ${n.join(`, `)}`,name:`ssh-auth`,status:`fail`}},Lf=e=>{let t=e.filter(e=>e.outcome===`denied`).map(e=>e.host);if(t.length!==0)return{detail:`ssh permission denied for: ${t.join(`, `)}`,name:`ssh-auth`,status:`fail`}},Rf=e=>{let t=e.filter(e=>e.outcome===`connection-warn`);if(t.length!==0)return{detail:`ssh connection issue, treated as warn: ${t.map(e=>`${e.host} (${e.detail??``})`).join(`; `)}`,name:`ssh-auth`,status:`warn`}},zf=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),Bf=(e,t)=>If(e,t)??Lf(e)??Rf(e)??zf(e),Vf=async(e,t,n)=>{let r=Af(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>Ff(e,t,i)));return Bf(a,i)},Hf=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${Hd(t)}`,name:e.name,status:`fail`}}},Uf=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await Hf(t),i=await Uf(n);return r===void 0?i:[r,...i]},Wf=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>Kd(n)},{name:`node`,run:()=>Promise.resolve(Xd(n))},{name:`config`,run:()=>Promise.resolve($d(t.errorMessage))},{name:`hooks-guard`,run:()=>ff(n,r,t.config)},{name:`dirty-checkouts`,run:()=>hf(n,r,t.config)},{name:`orphans`,run:()=>Sf(r,t.config,i)},{name:`skill`,run:()=>af(n)},{name:`ssh-auth`,run:()=>Vf(n,t.config)}]},Gf=async e=>{let t=H(e.env),n=await Qd(t),r=await gf(t);return Uf(Wf({configLoad:n,ctx:e,home:t,state:r}))},Kf={fail:`FAIL`,ok:`OK`,warn:`WARN`},qf=e=>e.map(e=>`[${Kf[e.status]}] ${e.name}: ${e.detail}`),Jf=e=>e.some(e=>e.status===`fail`),Yf=(e,t)=>{e.command(`doctor`).description(`Run environment/integrity checks (git, node, config, hooks, checkouts, ssh).`).action((e,n)=>{let r=Z(n);return $(t,r,async()=>{let e=await Gf(t);Q(t,r,qf(e),{checks:e}),Jf(e)&&(process.exitCode=g.UNEXPECTED)})()})},Xf=async e=>{let t=H(e.env),n=await J(t,`home`,()=>lc(t,Gd));return n===`migrated`?{backup:Vs(t),result:n}:{backup:null,result:n}},Zf=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${te(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,Qf=(e,t)=>{e.command(`migrate`).description(`Migrate the refs config to the current schema, seeding it if absent.`).action((e,n)=>{let r=Z(n);return $(t,r,async()=>{let e=await Xf(t);Q(t,r,Zf(e),e)})()})},$f=(e,t,n)=>e===void 0||n-Date.parse(e)>t,ep=(e,t,n)=>{let r=e.state.refs[t],i=Qo(Y(`sync_ttl`,n,e.settings));return{clone_mode:Y(`clone_mode`,n,e.settings),description:n.description,key:t,missing:!G(U(e.home,z.parse(t))),packages:Object.keys(n.packages??{}).toSorted(),stale:$f(r?.last_fetched_at,i,e.now)}},tp=e=>{let t={home:e.home,now:e.now,settings:e.config.settings,state:e.state};return Object.entries(e.config.refs).map(([e,n])=>ep(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},np=async e=>{let t=H(e.env),n=await W(t),r=await X(t);return tp({config:n,home:t,now:Date.now(),state:r})},rp=e=>{let t=[];return e.stale&&t.push(`[stale]`),e.missing&&t.push(`[missing]`),t.length===0?``:` ${t.join(` `)}`},ip=e=>e.length===0?[`no refs configured — run: refs add <source>`]:e.map(e=>`${e.key} ${e.description}${rp(e)}`),ap=e=>e.split(`/`),op=(e,t)=>{let n=ap(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},sp=(e,t)=>{if(Object.hasOwn(e.refs,t))return z.parse(t);let n=ap(t),r=Object.keys(e.refs).filter(e=>op(e,n)).toSorted(),[i]=r;if(i===void 0)throw v(`no ref matches '${t}'`);if(r.length>1)throw y(`'${t}' matches more than one ref: ${r.join(`, `)}`);return z.parse(i)},cp=(e,t)=>{e.command(`list`).description(`List configured refs with their staleness/missing checkout status.`).action((e,n)=>{let r=Z(n);return $(t,r,async()=>{let e=await np(t);Q(t,r,ip(e),e)})()})},lp=e=>`ref.${e.replaceAll(`/`,`_`)}`,up=e=>e.REFS_ALLOW_FILE_URLS===`1`,dp=(e,t)=>{let n=dl(t,{allowFileUrls:up(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},fp=async(e,t)=>{if(t===``)throw y(`refs add npm: requires a package name, e.g. npm:left-pad`);Wd(e,`resolving npm package '${t}'…`);let n=await hu(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},pp=(e,t)=>t.startsWith(`npm:`)?fp(e,t.slice(4)):Promise.resolve(dp(e,t)),mp=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=Y(`git_transport`,void 0,t);return{...e,cloneUrl:Cl(e.cloneUrl,n)}},hp=e=>`ref '${e}' already exists — use refs edit or refs remove`,gp=(e,t)=>{if(e.refs[t]!==void 0)throw ye(hp(t))},_p=async e=>{try{return await s(e,{withFileTypes:!0})}catch(e){if(V(e))return;throw e}},vp=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),yp=async(e,t)=>{let n=await _p(e);if(n===void 0)return{kind:`stop`};let r=vp(n);if(r.includes(t))return{kind:`continue`,nextDir:m(e,t)};let i=r.find(e=>e.toLowerCase()===t.toLowerCase());return i===void 0?{kind:`stop`}:{kind:`collision`,name:i}},bp=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await yp(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):bp(a.nextDir,i,[...n,r])},xp=[],Sp=async(e,t)=>{let n=await bp(e.sourcesDir,t.split(`/`),xp);if(n!==void 0)throw ye(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},Cp=async e=>{try{return await i(e),!0}catch(e){if(V(e))return!1;throw e}},wp=async e=>{try{return await s(e)}catch(e){if(V(e))return;throw e}},Tp=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(V(e))return;throw e}},Ep=async e=>{let t=await wp(e);if(t===void 0)return!0;if(t.length>0)return!1;try{await d(e)}catch(e){if(!V(e))throw e}return!0},Dp=async e=>{let t=await Tp(e);return t===void 0?!0:t?Ep(e):!1},Op=async(e,t)=>{t!==e.sourcesDir&&await Dp(t)&&await Op(e,ne(t))},kp=async(e,t)=>await Cp(t)?(Gs(e,t),await u(t,{force:!0,recursive:!0}),await Op(e,ne(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},Ap=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),jp=async(e,t)=>{let n=await W(e);await $s(e,{...n,refs:Ap(n.refs,t)});let r=await X(e);await Ku(e,{...r,refs:Ap(r.refs,t)})},Mp=async(e,t)=>{let n=H(e.env),r=sp(await W(n),t),i=U(n,r),{removedCheckout:a,warning:o}=await J(n,lp(r),()=>kp(n,i));return await J(n,`home`,()=>jp(n,r)),{data:{key:r,removed_checkout:a},warnings:Vd(o)}},Np=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],Pp=(e,t)=>{e.command(`remove`).description(`Remove a configured ref: its config/state entry AND its checkout directory.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).action((e,n,r)=>{let i=Z(r);return $(t,i,async()=>{let{data:n,warnings:r}=await Mp(t,e);Q(t,i,Np(n),n,r)})()})},Fp=(e,t)=>{let n=e.refs[t];if(n===void 0)throw Error(`internal: matched ref key '${t}' is missing from config.refs`);return n},Ip=(e,t)=>{if(!G(e))throw v(`checkout for '${t}' is missing — run: refs sync ${t}`)},Lp=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r},Rp=e=>`no ref matches '${e}' — run refs list, or add it: refs add <url>`,zp=/^[a-z][a-z0-9+.-]*:\/\//iu,Bp=/^git@[^:/\s]+:[^\s]+$/u,Vp=e=>zp.test(e)||Bp.test(e),Hp=(e,t)=>{try{return dl(e,t)}catch{if(Vp(e))throw b(`query looks like a git url but is not a supported form — check the url (credentials are never accepted) or run: refs resolve <package|ref-suffix>`);return}},Up=(e,t,n)=>{let r=Hp(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw v(Rp(t))}},Wp=(e,t)=>{let n=[];for(let r of Object.keys(e.refs).toSorted()){let i=e.refs[r]?.packages?.[t];i!==void 0&&n.push({entry:i,key:z.parse(r)})}return n},Gp=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — use the full ref key`,Kp=(e,t)=>{let n=Wp(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw y(Gp(t,n.map(e=>e.key)));return r}},qp=(e,t)=>{let n=t.split(`/`);for(let t=n.length-1;t>=1;--t){let r=n.slice(0,t).join(`/`),i=Kp(e,r);if(i!==void 0)return{...i,name:r}}},Jp=(e,t)=>{try{return sp(e,t)}catch(e){throw e instanceof _&&e.code===`not_found`?v(Rp(t)):e}},Yp=(e,t,n)=>{let r=Up(e,t,n);if(r!==void 0)return r;let i=Kp(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=qp(e,t);return a===void 0?{key:Jp(e,t)}:{key:a.key,packageMatch:a}},Xp=(e,t)=>{if(e.packageMatch===void 0)return null;let{entry:n,name:r}=e.packageMatch;return{local_path:m(t,n.path),name:r,path:n.path}},Zp=async(e,t)=>{let n=H(e.env),r=await W(n),i=Yp(r,t,{allowFileUrls:up(e.env)}),a=Fp(r,i.key),o=await X(n),s=U(n,i.key),c=Qo(Y(`sync_ttl`,a,r.settings));return{key:i.key,local_path:s,missing:!G(s),package:Xp(i,s),stale:$f(o.refs[i.key]?.last_fetched_at,c,Date.now())}},Qp=e=>{let t=[e.key,`local_path: ${e.local_path}`];return e.package!==null&&t.push(`package: ${e.package.name}`,`local_path: ${e.package.local_path}`),t},$p=(e,t)=>{e.command(`resolve`).description(`Resolve a git url, npm package name, import path, or ref-key suffix to its ref/package.`).argument(`<query>`,`git url, npm package name, import path, or unique ref-key suffix`).action((e,n,r)=>{let i=Z(r);return $(t,i,async()=>{let n=await Zp(t,e);Q(t,i,Qp(n),n)})()})},em={},tm=async(e,t)=>{if(!G(t))return{tags:[]};try{return{tags:await kc(e.runner,t,5)}}catch(e){return{tags:[],warning:`could not list tags: ${Hd(e)}`}}},nm=async(e,t)=>{let n=H(e.env),r=await W(n),i=sp(r,t),a=Fp(r,i),o=await X(n),s=U(n,i),{tags:c,warning:l}=await tm(e,s);return{data:{...a,key:i,local_path:s,sample_tags:c,state:o.refs[i]??em},warnings:Vd(l)}},rm=e=>{let t=[`${e.key} ${e.description}`,`url: ${e.url}`,`local_path: ${e.local_path}`];return e.sample_tags.length>0&&t.push(`tags: ${e.sample_tags.join(`, `)}`),t},im=(e,t)=>{e.command(`show`).description(`Show a configured ref: full entry, state, local path, and sample tags.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).action((e,n,r)=>{let i=Z(r);return $(t,i,async()=>{let{data:n,warnings:r}=await nm(t,e);Q(t,i,rm(n),n,r)})()})},am=(e,t)=>{let n={head_sha:t.headSha,last_fetched_at:new Date().toISOString()},r=t.effectiveCloneMode??e?.effective_clone_mode;return r!==void 0&&(n.effective_clone_mode=r),n},om=async(e,t,n)=>{let r=await W(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await $s(e,r))},sm=(e,t,n)=>J(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await om(e,t,n.branchRenamedTo);let r=await X(e);r.refs[t]=am(r.refs[t],n),await Ku(e,r)}),cm=async(e,t,n)=>{try{await J(e,`home`,async()=>{let r=await X(e);r.refs[t]={...r.refs[t],last_error:n},await Ku(e,r)})}catch{}},lm=e=>{let t=0,n=[];return{acquire:()=>{if(t<e)return t+=1,Promise.resolve();let{promise:r,resolve:i}=Promise.withResolvers();return n.push(()=>{t+=1,i()}),r},release:()=>{--t;let e=n.shift();e!==void 0&&e()}}},um=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},dm=(e,t,n)=>`checkout at ${e} points at '${q(t)}' — expected '${q(n)}'; remove the checkout directory or run refs remove before retrying`,fm=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,pm=(e,t)=>{try{return dl(e,{allowFileUrls:t}).key}catch{return}},mm=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=fm(n),i=pm(t.expectedUrl,t.allowFileUrls),a=pm(r,t.allowFileUrls);if(i===void 0||a!==i)throw ye(dm(t.dest,r,t.expectedUrl))},hm=e=>`checkout at ${e} exists but is not refs-managed — remove it (rm -rf ${e}) and retry`,gm=async(e,t)=>{let n=await e.run(`git`,[`config`,`--local`,`core.hooksPath`],{cwd:t.dest});if(n.exitCode!==0||n.stdout.trim()!==t.hooksDir)throw ye(hm(t.dest))},_m=async(e,t)=>{await a(ne(t.dest),{recursive:!0}),Wd(e,`cloning ${q(t.cloneUrl)} into ${t.dest}…`);let n=await bc(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},vm=async(e,t)=>(Gs(t.home,t.dest),G(t.dest)?(await mm(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await gm(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):_m(e,t)),ym=(e,t)=>`checkout for '${e}' at ${t} is missing or corrupt (git rev-parse HEAD failed) — run: refs remove ${e}, then refs add <source> --dry-run again`,bm=(e,t,n)=>`checkout for '${e}' at ${t} has a HEAD sha refs cannot store yet (${n.length} hex chars, expected 40) — only SHA-1 repositories are supported for now; \`--object-format=sha256\` repositories are not yet supported`,xm=async(e,t)=>{await mm(e,t),await gm(e,{dest:t.dest,hooksDir:t.hooksDir});let n=await e.run(`git`,[`rev-parse`,`HEAD`],{cwd:t.dest});if(n.exitCode!==0)throw b(ym(t.key,t.dest));let r=n.stdout.trim();if(!Hu.shape.head_sha.safeParse(r).success)throw b(bm(t.key,t.dest,r));return r},Sm=(e,t,n)=>`sync produced a HEAD sha for '${e}' at ${t} that refs cannot store yet (${n.length} hex chars) — only SHA-1 repositories are supported for now`,Cm=(e,t,n)=>{if(!Hu.shape.head_sha.safeParse(n).success)throw b(Sm(e,t,n));return n},wm=(e,t,n)=>{let r={effectiveCloneMode:t.effectiveMode,headSha:n.headSha,status:`cloned`};return n.actualBranch!==e.ref.default_branch&&(r.branchRenamedTo=n.actualBranch),t.warning!==void 0&&(r.warning=t.warning),r},Tm=async(e,t,n)=>{await a(ne(n),{recursive:!0});let r=Y(`clone_mode`,t.ref,t.settings),i=await bc(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await Sc(e.runner,n),s=await xm(e.runner,{allowFileUrls:up(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return wm(t,i,{actualBranch:o,headSha:s})},Em=async(e,t,n)=>{await gm(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await mm(e.runner,{allowFileUrls:up(e.env),dest:n,expectedUrl:t.ref.url});let r=await Oc(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:Cm(t.key,n,r.newSha),status:r.status};return r.branchRenamedTo!==void 0&&(i.branchRenamedTo=r.branchRenamedTo),r.warning!==void 0&&(i.warning=r.warning),i},Dm=(e,t)=>J(t.home,lp(t.key),()=>{let n=U(t.home,t.key);return Gs(t.home,n),G(n)?Em(e,t,n):Tm(e,t,n)}),Om=e=>{let t=[];e.branchRenamedTo!==void 0&&t.push(`default branch renamed to ${e.branchRenamedTo}`),e.warning!==void 0&&t.push(e.warning);let[n]=t;if(n!==void 0)return t.join(` | `)},km=(e,t)=>{let n={key:e,status:t.status},r=Om(t);return r!==void 0&&(n.warning=r),n},Am=async(e,t)=>{try{let n=await Dm(e,t);return await sm(t.home,t.key,n),km(t.key,n)}catch(e){let n=Hd(e);return await cm(t.home,t.key,n),{error:n,key:t.key,status:`failed`}}},jm=(e,t)=>e.status===`rejected`?{error:Hd(e.reason),key:t,status:`failed`}:e.value,Mm=async(e,t)=>{let n=lm(4);return(await Promise.allSettled(t.map(t=>um(n,()=>Am(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return jm(e,r.key)})},Nm=(e,t,n)=>({home:e,key:n,ref:Fp(t,n),settings:t.settings}),Pm=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>Nm(e,t,z.parse(n))):n.map(n=>Nm(e,t,sp(t,n))),Fm=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=Qo(Y(`sync_ttl`,t.ref,t.settings)),a=$f(n.refs[t.key]?.last_fetched_at,i,r),o=!G(U(e,t.key));return a||o})},Im=async(e,t,n)=>{if(!n)return t;let r=await X(e);return Fm(e,t,r)},Lm=async(e,t)=>{let n=H(e.env),r=await W(n),i=Pm(n,r,t.refs),a=await Mm(e,await Im(n,i,t.staleOnly));return{failedCount:a.filter(e=>e.status===`failed`).length,results:a}},Rm=[`updated`,`fresh`,`cloned`,`restored`,`failed`],zm={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},Bm=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},Vm=e=>e.status===`failed`?` ${e.key}: ${e.error??`unknown error`}`:e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`,Hm=e=>{let t=Bm(e),n=[Rm.map(e=>`${zm[e]} (${t[e].length})`).join(` / `)];for(let e of Rm)for(let r of t[e])n.push(Vm(r));return n},Um=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),Wm=(e,t)=>{e.command(`sync`).description(`Fetch (or re-clone, if the checkout is missing) configured refs — all by default.`).argument(`[refs...]`,`ref keys or unique suffixes to sync (default: every configured ref)`).option(`--stale-only`,`skip refs whose last sync is still within their ref's sync_ttl`).action((e,n,r)=>{let i=Z(r);return $(t,i,async()=>{let r=await Lm(t,Um(e,n));Q(t,i,Hm(r.results),{results:r.results}),r.failedCount>0&&(process.exitCode=g.UNEXPECTED)})()})},Gm=(e,t,n)=>n===void 0?e.tag_format:Lp(e,t,n).tag_format??e.tag_format,Km=async(e,t)=>{let n=H(e.env),r=await W(n),i=sp(r,t.query),a=Fp(r,i),o=Gm(a,i,t.opts.packageName),s=U(n,i);Ip(s,i);let c=await Wc(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},qm=e=>[`${e.key}@${e.version} -> ${e.tag}`],Jm=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},Ym=[Yf,Qf,Pp,$p,im,Wm,(e,t)=>{e.command(`tag`).description(`Resolve a version to its git tag, via the ref's (or a package's) tag_format.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).argument(`<version>`,`version to resolve, e.g. 4.1.0`).option(`--package <name>`,`resolve against this package's tag_format instead of the ref's`).action((e,n,r,i)=>{let a=Z(i);return $(t,a,async()=>{let i=await Km(t,{opts:Jm(r),query:e,version:n});Q(t,a,qm(i),i)})()})}],Xm=e=>e.description===void 0?{path:e.path}:{description:e.description,path:e.path},Zm=(e,t,n)=>e.length>0?Object.fromEntries(e.map(e=>[e.name,Xm(e)])):n===void 0?{}:{[n]:{path:t??`.`}},Qm=e=>{let t=e.description??``;return e.tag_format===void 0?{description:t,path:e.path}:{description:t,path:e.path,tag_format:e.tag_format}},$m=e=>{let t=Object.entries(e);if(t.length!==0)return Object.fromEntries(t.map(([e,t])=>[e,Qm(t)]))},eh=e=>e.description===void 0||e.description===``,th=e=>Object.entries(e).filter(([,e])=>eh(e)).map(([e])=>e).toSorted(),nh=e=>{let t=th(e);if(t.length!==0)throw b(`packages without a detected description: ${t.join(`, `)} — run the two-phase flow instead: refs add <source> --dry-run --json > proposal.json, fill in the package descriptions, then refs add --proposal proposal.json`)},rh=e=>{if(Object.keys(e).length!==0)return e},ih=e=>{if(e===null)throw b(`tag_format_candidate must be set to a valid tag format (containing '{version}') before finalizing — edit the proposal and provide one, or add the ref manually`);return e},ah=e=>e.packages===void 0?{default_branch:e.default_branch,description:e.description,tag_format:e.tag_format,url:e.url}:{default_branch:e.default_branch,description:e.description,packages:e.packages,tag_format:e.tag_format,url:e.url},oh=async(e,t,n)=>{let r=await Sc(e.runner,t),i=Hc(await kc(e.runner,t));return Wd(e,`detecting workspace packages…`),{defaultBranch:r,packages:Zm(await Sd(t),n.npmDirectory,n.npmPkgName),tagFormatCandidate:i}},sh=(e,t)=>J(t.home,lp(t.resolved.key),async()=>{let n=await vm(e,{allowFileUrls:up(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await oh(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),ch=e=>{let t={default_branch:e.cloneResult.fields.defaultBranch,description:``,key:e.resolved.key,packages:e.cloneResult.fields.packages,tag_format_candidate:e.cloneResult.fields.tagFormatCandidate,url:e.resolved.cloneUrl},n={dest:e.dest,proposal:t};return e.cloneResult.effectiveMode!==void 0&&(n.effectiveCloneMode=e.cloneResult.effectiveMode),e.cloneResult.warning!==void 0&&(n.warning=e.cloneResult.warning),n},lh=async(e,t)=>{let n=H(e.env),r=await W(n),i=mp(await pp(e,t),r.settings);gp(r,i.key),await Sp(n,i.key);let a=U(n,i.key),o=Y(`clone_mode`,void 0,r.settings),s=await sh(e,{cloneMode:o,dest:a,home:n,resolved:i});return ch({cloneResult:s,dest:a,resolved:i})},uh=(e,t,n)=>J(e,`home`,async()=>{gp(await W(e),t);let r=await X(e),i=r.refs[t],a=n??i?.effective_clone_mode,o={...i,pending_proposal_at:new Date().toISOString()};a!==void 0&&(o.effective_clone_mode=a),r.refs[t]=o,await Ku(e,r)}),dh=(e,t)=>{let n=cs.safeParse(e);if(!n.success)throw b(O(n.error));let r=Uu.safeParse(t);if(!r.success)throw b(O(r.error));return{config:n.data,state:r.data}},fh=async(e,t)=>{let n=await W(e.home);gp(n,e.ref.key);let r=ah(e.ref);n.refs[e.ref.key]=r;let i=await X(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??Y(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...dh(n,i),entry:r}},ph=async(e,t)=>{let n=up(e.env),r=await J(t.home,lp(t.ref.key),()=>(Gs(t.home,t.dest),xm(e.runner,{allowFileUrls:n,dest:t.dest,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.ref.key})));return J(t.home,`home`,async()=>{let{config:e,entry:n,state:i}=await fh(t,r);return await Ku(t.home,i),await $s(t.home,e),{entry:n,key:t.ref.key}})},mh=(e,t)=>t===`-`?e.readStdin():o(t,`utf8`),hh=e=>{try{return JSON.parse(e)}catch(e){throw b(`invalid JSON in proposal: ${Hd(e)}`)}},gh=e=>typeof e==`object`&&!!e&&!Array.isArray(e),_h=e=>gh(e)&&`ok`in e&&!(`key`in e),vh=e=>{if(!_h(e))return e;if(e.ok===!1)throw b(`proposal file contains a failed refs envelope (ok is false) — re-run the dry-run`);if(gh(e.data))return e.data;throw b(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},yh=e=>e.code===`unrecognized_keys`,bh=e=>e.path.length===0,xh=(e,t)=>{let n=t.toSorted().map(e=>`"${e}"`).join(`, `);return e===``?`✖ unrecognized key(s) in proposal: ${n}`:`✖ unrecognized key(s) in proposal at ${e}: ${n}`},Sh=e=>{let t=new Map;for(let n of e){let e=lt(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>xh(e,t))},Ch=e=>`✖ invalid proposal: ${e.message}`,wh=e=>{let t=e.issues.filter(e=>yh(e)),n=e.issues.filter(e=>!yh(e)),r=n.filter(e=>bh(e));if(t.length===0&&r.length===0)return O(e);let i=n.filter(e=>!bh(e)),a=[...Sh(t),...r.map(e=>Ch(e))];return i.length>0&&a.push(O({issues:i})),a.join(`
|
|
369
|
-
`)},
|
|
370
|
-
`),
|
|
366
|
+
- ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function r(e,t){let r=p.resolve(e,t);if(le.existsSync(r))return r;if(n.includes(p.extname(t)))return;let i=n.find(e=>le.existsSync(`${r}${e}`));if(i)return`${r}${i}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||``;if(this._scriptPath){let e;try{e=le.realpathSync(this._scriptPath)}catch{e=this._scriptPath}a=p.resolve(p.dirname(e),a)}if(a){let t=r(a,i);if(!t&&!e._executableFile&&this._scriptPath){let n=p.basename(this._scriptPath,p.extname(this._scriptPath));n!==this._name&&(t=r(a,`${n}-${e._name}`))}i=t||i}let o=n.includes(p.extname(i)),s;h.platform===`win32`?(this._checkForMissingExecutable(i,a,e._name),t.unshift(i),t=Rd(h.execArgv).concat(t),s=ge.spawn(h.execPath,t,{stdio:`inherit`})):o?(t.unshift(i),t=Rd(h.execArgv).concat(t),s=ge.spawn(h.argv[0],t,{stdio:`inherit`})):s=ge.spawn(i,t,{stdio:`inherit`}),s.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{h.on(e,()=>{s.killed===!1&&s.exitCode===null&&s.kill(e)})});let c=this._exitCallback;s.on(`close`,e=>{e??=1,c?c(new Ed(e,`commander.executeSubCommandAsync`,`(close)`)):h.exit(e)}),s.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(i,a,e._name);else if(t.code===`EACCES`)throw Error(`'${i}' not executable`);if(!c)h.exit(1);else{let e=new Ed(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,c(e)}}),this.runningCommand=s}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)!==void 0&&this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
367
|
+
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in h.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,h.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Md(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=Id(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=e.length,i=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${r}: ${e.join(`, `)}.`;this.error(i,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=Id(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>kd(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=p.basename(e,p.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(h.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
368
|
+
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function Rd(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function zd(){if(h.env.NO_COLOR||h.env.FORCE_COLOR===`0`||h.env.FORCE_COLOR===`false`)return!1;if(h.env.FORCE_COLOR||h.env.CLICOLOR_FORCE!==void 0)return!0}new Ld;const Bd=[],Vd=e=>Array.isArray(e)?e:[e],Hd=e=>e===void 0?Bd:[e],Ud=e=>e instanceof Error?e.message:String(e),Z=e=>{let t=e.optsWithGlobals();return{json:t.json===!0,verbose:t.verbose===!0}},Q=(e,t,n,r,i)=>{if(t.json){let t={data:r,ok:!0,warnings:i??Bd};e.out(JSON.stringify(t));return}for(let t of Vd(n))e.out(t);for(let t of i??Bd)e.errLine(`refs: warning: ${t}`)},Wd=(e,t,n)=>{if(t.json){let t={error:{code:n.code,message:n.message},ok:!1};e.out(JSON.stringify(t));return}e.errLine(`refs: ${n.message}`)},Gd=(e,t)=>{e.errLine(`refs: ${t}`)},$=(e,t,n)=>async()=>{try{await n()}catch(n){let r=xe(n,{verbose:t.verbose});Wd(e,t,r),process.exitCode=r.exitCode}},Kd=async e=>{let t=await e.runner.run(`git`,[`--version`]);return t.exitCode===0?{detail:t.stdout.trim(),name:`git`,status:`ok`}:{detail:t.stderr.trim()||`git --version exited with code ${t.exitCode}`,name:`git`,status:`fail`}},qd=/^v(?<major>\d+)\.(?<minor>\d+)/u,Jd=e=>{let t=qd.exec(e),n=t?.groups?.major,r=t?.groups?.minor;if(n!==void 0&&r!==void 0)return{major:Number(n),minor:Number(r)}},Yd=e=>e===void 0?!1:e.major>24||e.major===24&&e.minor>=12,Xd=e=>{let{nodeVersion:t}=e;return Yd(Jd(t))?{detail:t,name:`node`,status:`ok`}:{detail:`${t} does not satisfy the required range >=24.12`,name:`node`,status:`fail`}},Zd=()=>cs.parse({meta:{cli_version:`0.0.0`,schema_version:1},refs:{},settings:{}}),Qd=async e=>{try{return{config:await W(e)}}catch(e){return{config:Zd(),errorMessage:Ud(e)}}},$d=e=>e===void 0?{detail:`config is present and matches the current schema`,name:`config`,status:`ok`}:{detail:e,name:`config`,status:`fail`},ef=(e,t)=>Object.keys(t.refs).map(t=>({dest:U(e,z.parse(t)),key:t})).filter(e=>G(e.dest)),tf=[`pre-commit`,`pre-push`],nf=async(t,r)=>{try{return await e(m(t.hooksDir,r),n.X_OK),!0}catch{return!1}},rf=async e=>{let t=await Promise.all(tf.map(t=>nf(e,t)));return tf.filter((e,n)=>!t[n])},af=async(e,t,n)=>{let r=await e.runner.run(`git`,[`config`,`--local`,`--get`,`core.hooksPath`],{cwd:n});return r.exitCode===0&&r.stdout.trim()===t.hooksDir},of=e=>e.missingHooks.length>0?{detail:`${e.missingHooks.map(e=>`hooks/${e}`).join(`, `)} missing or not executable — run: refs init`,name:`hooks-guard`,status:`fail`}:e.badKeys.length>0?{detail:`core.hooksPath not set for: ${e.badKeys.join(`, `)} — run: refs init`,name:`hooks-guard`,status:`fail`}:{detail:`${tf.map(e=>`hooks/${e}`).join(`, `)} present; ${e.checkoutCount} checkout(s) guarded`,name:`hooks-guard`,status:`ok`},sf=async(e,t,n)=>{let r=ef(t,n),[i,a]=await Promise.all([rf(t),Promise.all(r.map(n=>af(e,t,n.dest)))]),o=r.filter((e,t)=>!a[t]).map(e=>e.key);return of({badKeys:o,checkoutCount:r.length,missingHooks:i})},cf=async(e,t)=>{let n=await e.runner.run(`git`,[`status`,`--porcelain`],{cwd:t.dest});return n.exitCode===0?{broken:!1,detail:``,dirty:n.stdout.trim()!==``,key:t.key}:{broken:!0,detail:n.stderr.trim(),dirty:!1,key:t.key}},lf=e=>{let t=e.filter(e=>e.broken);if(t.length>0)return{detail:t.map(e=>`${e.key}: git status failed — ${e.detail}`).join(`; `),name:`dirty-checkouts`,status:`fail`};let n=e.filter(e=>e.dirty).map(e=>e.key);return n.length===0?{detail:`no local changes in any checkout`,name:`dirty-checkouts`,status:`ok`}:{detail:`local changes will be discarded on next sync: ${n.join(`, `)}`,name:`dirty-checkouts`,status:`warn`}},uf=async(e,t,n)=>{let r=ef(t,n),i=await Promise.all(r.map(t=>cf(e,t)));return lf(i)},df=async e=>{try{return await X(e)}catch{return Uu.parse({})}},ff=async e=>{try{return(await s(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(V(e))return[];throw e}},pf=async(e,t)=>{if(G(e))return[[...t]];let n=await ff(e);return(await Promise.all(n.map(n=>pf(m(e,n),[...t,n])))).flat()},mf=(e,t,n)=>{let r=e.refs[t]?.pending_proposal_at;return r!==void 0&&n-Date.parse(r)<864e5},hf=(e,t,n)=>mf(t,e.key,n)?`${e.key}: pending add`:`${e.key}: orphan — remove with: rm -rf ${e.dest}`,gf=(e,t)=>({dest:m(e.sourcesDir,...t),key:t.join(`/`)}),_f=async(e,t,n)=>{let r=(await pf(e.sourcesDir,[])).map(t=>gf(e,t)).filter(e=>!Object.hasOwn(t.refs,e.key));if(r.length===0)return{detail:`no orphaned checkouts under sources/`,name:`orphans`,status:`ok`};let i=Date.now();return{detail:r.map(e=>hf(e,n,i)).join(`; `),name:`orphans`,status:`warn`}},vf=[`.agents`,`skills`,`refs`,`SKILL.md`],yf=[`skills`,`refs`,`SKILL.md`],bf=[`.claude`,`skills`,`refs`,`SKILL.md`],xf=`npx skills add kaisers-io/refs`,Sf=`npm i -g @kaisers-io/refs@latest`,Cf=(e,t)=>e===void 0?void 0:{display:t,path:e},wf=e=>{let{dirName:t,env:n,home:r,overrideName:i}=e,a=n[i]?.trim();return a!==void 0&&a.length>0?{display:a,path:a}:Cf(r===void 0?void 0:m(r,t),`~/${t}`)},Tf=e=>{let t=e.env.HOME;return[{label:`shared ~/.agents`,root:Cf(t,`~/.agents`),segments:vf},{label:`Claude Code`,root:wf({dirName:`.claude`,env:e.env,home:t,overrideName:`CLAUDE_CONFIG_DIR`}),segments:yf},{label:`Codex`,root:wf({dirName:`.codex`,env:e.env,home:t,overrideName:`CODEX_HOME`}),segments:yf},{label:`project ./.agents`,root:Cf(e.cwd,`./.agents`),segments:vf},{label:`project ./.claude`,root:Cf(e.cwd,`./.claude`),segments:bf}].flatMap(({label:e,root:t,segments:n})=>t===void 0?[]:[{display:t.display,label:e,path:m(t.path,...n)}])},Ef=async(e,t)=>{try{let n=await c(e);return{label:t,realPath:n,source:await o(n,`utf8`)}}catch{return}},Df=e=>{let t=new Map;for(let n of e)t.has(n.realPath)||t.set(n.realPath,n);return[...t.values()]},Of=/^---\r?\n(?<body>[\s\S]*?)\r?\n---/u,kf=/^\s*cli_version:\s*["']?(?<version>[^"'\s]+)["']?\s*$/mu,Af=e=>{let t=Of.exec(e)?.groups?.body;if(t!==void 0)return kf.exec(t)?.groups?.version},jf=/^\d+\.\d+\.\d+$/u,Mf=e=>{if(jf.test(e))return e.split(`.`).map(Number)},Nf=(e,t)=>{if(e===t)return`match`;let n=Mf(e),r=Mf(t);if(n===void 0||r===void 0)return`unknown`;let i=n.findIndex((e,t)=>e!==r[t]);return i===-1?`match`:(n[i]??0)>(r[i]??0)?`cli-older`:`skill-older`},Pf={"cli-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the CLI: ${Sf}`,match:(e,t)=>`the refs skill is installed and matches this CLI (${t})`,"skill-older":(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — update the skill: ${xf}`,unknown:(e,t)=>`the refs skill targets CLI ${e} but this CLI is ${t} — reinstall both: ${Sf} and ${xf}`},Ff=e=>{let{cliVersion:t,label:n,skillVersion:r}=e;if(r===void 0)return{detail:`the refs skill (${n}) predates the version gate — update it: ${xf}`,name:`skill`,status:`warn`};let i=Nf(r,t);return{detail:`${n}: ${Pf[i](r,t)}`,name:`skill`,status:i===`match`?`ok`:`warn`}},If=e=>({detail:`refs skill not found in the locations this check knows about (${e.map(e=>e.display).join(`, `)}) — an install anywhere else is invisible here and still works; if it really is missing: ${xf}`,name:`skill`,status:`warn`}),Lf=async e=>{let t=Tf(e),n=await Promise.all(t.map(e=>Ef(e.path,e.label))),r=Df(n.filter(e=>e!==void 0)).map(t=>Ff({cliVersion:e.cliVersion,label:t.label,skillVersion:Af(t.source)}));return r.find(e=>e.status!==`ok`)??r[0]??If(t)},Rf=/^(?<user>[^/\s@]+)@(?<host>[^:/\s]+):/u,zf=e=>e===``?{}:{user:e},Bf=e=>e===``?{}:{port:e},Vf=e=>{try{let t=new URL(e);return t.protocol===`ssh:`?{host:t.hostname,...zf(t.username),...Bf(t.port)}:void 0}catch{return}},Hf=e=>{let t=Rf.exec(e),n=t?.groups?.host;return n===void 0?Vf(e):{host:n,user:t?.groups?.user??`git`}},Uf=e=>e.port===void 0?e.host:`${e.host}:${e.port}`,Wf=e=>e.user===void 0?Uf(e):`${e.user}@${Uf(e)}`,Gf=e=>{let t=Object.values(e.refs).map(e=>Hf(e.url)).filter(e=>e!==void 0),n=new Map;for(let e of t)n.set(Wf(e),e);return[...n.values()].toSorted((e,t)=>Wf(e).localeCompare(Wf(t)))},Kf=/Permission denied/u,qf=[/Could not resolve hostname/u,/Connection refused/u,/Host key verification failed/u,/timed out/u],Jf=e=>e.user===void 0?e.host:`${e.user}@${e.host}`,Yf=e=>{let t=[`-o`,`ConnectTimeout=5`,`-o`,`BatchMode=yes`],n=Jf(e);return e.port===void 0?[...t,`-T`,n]:[...t,`-p`,e.port,`-T`,n]},Xf=async(e,t,n)=>{let r=Wf(t),i=await e.runner.run(`ssh`,Yf(t),{timeoutMs:n});return i.timedOut===!0?{host:r,outcome:`timeout`}:Kf.test(i.stderr)?{host:r,outcome:`denied`}:qf.some(e=>e.test(i.stderr))?{detail:i.stderr.trim(),host:r,outcome:`connection-warn`}:{host:r,outcome:`ok`}},Zf=(e,t)=>{let n=e.filter(e=>e.outcome===`timeout`).map(e=>e.host);if(n.length!==0)return{detail:`ssh probe timed out after ${t/1e3}s: ${n.join(`, `)}`,name:`ssh-auth`,status:`fail`}},Qf=e=>{let t=e.filter(e=>e.outcome===`denied`).map(e=>e.host);if(t.length!==0)return{detail:`ssh permission denied for: ${t.join(`, `)}`,name:`ssh-auth`,status:`fail`}},$f=e=>{let t=e.filter(e=>e.outcome===`connection-warn`);if(t.length!==0)return{detail:`ssh connection issue, treated as warn: ${t.map(e=>`${e.host} (${e.detail??``})`).join(`; `)}`,name:`ssh-auth`,status:`warn`}},ep=e=>({detail:`ssh auth ok for: ${e.map(e=>e.host).join(`, `)}`,name:`ssh-auth`,status:`ok`}),tp=(e,t)=>Zf(e,t)??Qf(e)??$f(e)??ep(e),np=async(e,t,n)=>{let r=Gf(t);if(r.length===0)return;let i=n?.timeoutMs??1e4,a=await Promise.all(r.map(t=>Xf(e,t,i)));return tp(a,i)},rp=async e=>{try{return await e.run()}catch(t){return{detail:`check crashed: ${Ud(t)}`,name:e.name,status:`fail`}}},ip=async e=>{let[t,...n]=e;if(t===void 0)return[];let r=await rp(t),i=await ip(n);return r===void 0?i:[r,...i]},ap=e=>{let{configLoad:t,ctx:n,home:r,state:i}=e;return[{name:`git`,run:()=>Kd(n)},{name:`node`,run:()=>Promise.resolve(Xd(n))},{name:`config`,run:()=>Promise.resolve($d(t.errorMessage))},{name:`hooks-guard`,run:()=>sf(n,r,t.config)},{name:`dirty-checkouts`,run:()=>uf(n,r,t.config)},{name:`orphans`,run:()=>_f(r,t.config,i)},{name:`skill`,run:()=>Lf(n)},{name:`ssh-auth`,run:()=>np(n,t.config)}]},op=async e=>{let t=H(e.env),n=await Qd(t),r=await df(t);return ip(ap({configLoad:n,ctx:e,home:t,state:r}))},sp={fail:`FAIL`,ok:`OK`,warn:`WARN`},cp=e=>e.map(e=>`[${sp[e.status]}] ${e.name}: ${e.detail}`),lp=e=>e.some(e=>e.status===`fail`),up=(e,t)=>{e.command(`doctor`).description(`Run environment/integrity checks (git, node, config, hooks, checkouts, ssh).`).action((e,n)=>{let r=Z(n);return $(t,r,async()=>{let e=await op(t);Q(t,r,cp(e),{checks:e}),lp(e)&&(process.exitCode=g.UNEXPECTED)})()})},dp=async e=>{let t=H(e.env),n=await J(t,`home`,()=>lc(t,Cd));return n===`migrated`?{backup:Vs(t),result:n}:{backup:null,result:n}},fp=e=>e.result===`migrated`&&e.backup!==null?`config migrated (backup: ${te(e.backup)})`:e.result===`seeded`?`config seeded`:`config up to date`,pp=(e,t)=>{e.command(`migrate`).description(`Migrate the refs config to the current schema, seeding it if absent.`).action((e,n)=>{let r=Z(n);return $(t,r,async()=>{let e=await dp(t);Q(t,r,fp(e),e)})()})},mp=(e,t,n)=>e===void 0||n-Date.parse(e)>t,hp=(e,t,n)=>{let r=e.state.refs[t],i=Qo(Y(`sync_ttl`,n,e.settings)),a=Object.keys(n.packages??{}).toSorted();return{clone_mode:Y(`clone_mode`,n,e.settings),description:n.description,key:t,missing:!G(U(e.home,z.parse(t))),...e.includePackages?{packages:a}:{},packages_count:a.length,stale:mp(r?.last_fetched_at,i,e.now)}},gp=e=>{let t={home:e.home,includePackages:e.includePackages,now:e.now,settings:e.config.settings,state:e.state};return Object.entries(e.config.refs).map(([e,n])=>hp(t,e,n)).toSorted((e,t)=>e.key.localeCompare(t.key))},_p=async(e,t)=>{let n=H(e.env),r=await W(n),i=await X(n);return gp({config:r,home:n,includePackages:t,now:Date.now(),state:i})},vp=e=>{let t=[];return e.stale&&t.push(`[stale]`),e.missing&&t.push(`[missing]`),t.length===0?``:` ${t.join(` `)}`},yp=e=>e.length===0?[`no refs configured — run: refs add <source>`]:e.map(e=>`${e.key} ${e.description}${vp(e)}`),bp=e=>e.split(`/`),xp=(e,t)=>{let n=bp(e);if(t.length>n.length)return!1;let r=n.length-t.length;return t.every((e,t)=>e===n[r+t])},Sp=(e,t)=>{if(Object.hasOwn(e.refs,t))return z.parse(t);let n=bp(t),r=Object.keys(e.refs).filter(e=>xp(e,n)).toSorted(),[i]=r;if(i===void 0)throw v(`no ref matches '${t}'`);if(r.length>1)throw y(`'${t}' matches more than one ref: ${r.join(`, `)}`);return z.parse(i)},Cp=(e,t)=>{e.command(`list`).description(`List configured refs with their staleness/missing checkout status.`).option(`--packages`,`include each ref's package names in --json output (off by default)`).action((e,n)=>{let r=Z(n);return $(t,r,async()=>{let n=await _p(t,e.packages===!0);Q(t,r,yp(n),n)})()})},wp=e=>`ref.${e.replaceAll(`/`,`_`)}`,Tp=e=>e.REFS_ALLOW_FILE_URLS===`1`,Ep=(e,t)=>{let n=dl(t,{allowFileUrls:Tp(e.env)});return{cloneUrl:n.cloneUrl,key:n.key}},Dp=async(e,t)=>{if(t===``)throw y(`refs add npm: requires a package name, e.g. npm:left-pad`);Gd(e,`resolving npm package '${t}'…`);let n=await hu(e.fetcher,t),r={cloneUrl:n.cloneUrl,key:n.key,npmPkgName:t};return n.directory!==void 0&&(r.npmDirectory=n.directory),r},Op=(e,t)=>t.startsWith(`npm:`)?Dp(e,t.slice(4)):Promise.resolve(Ep(e,t)),kp=(e,t)=>{if(e.npmPkgName===void 0)return e;let n=Y(`git_transport`,void 0,t);return{...e,cloneUrl:Cl(e.cloneUrl,n)}},Ap=e=>`ref '${e}' already exists — use refs edit or refs remove`,jp=(e,t)=>{if(e.refs[t]!==void 0)throw ye(Ap(t))},Mp=async e=>{try{return await s(e,{withFileTypes:!0})}catch(e){if(V(e))return;throw e}},Np=e=>e.filter(e=>e.isDirectory()).map(e=>e.name),Pp=async(e,t)=>{let n=await Mp(e);if(n===void 0)return{kind:`stop`};let r=Np(n);if(r.includes(t))return{kind:`continue`,nextDir:m(e,t)};let i=r.find(e=>e.toLowerCase()===t.toLowerCase());return i===void 0?{kind:`stop`}:{kind:`collision`,name:i}},Fp=async(e,t,n)=>{let[r,...i]=t;if(r===void 0)return;let a=await Pp(e,r);if(a.kind!==`stop`)return a.kind===`collision`?[...n,a.name].join(`/`):Fp(a.nextDir,i,[...n,r])},Ip=[],Lp=async(e,t)=>{let n=await Fp(e.sourcesDir,t.split(`/`),Ip);if(n!==void 0)throw ye(`checkout path for '${t}' collides case-insensitively with existing '${n}'`)},Rp=async e=>{try{return await i(e),!0}catch(e){if(V(e))return!1;throw e}},zp=async e=>{try{return await s(e)}catch(e){if(V(e))return;throw e}},Bp=async e=>{try{return(await i(e)).isDirectory()}catch(e){if(V(e))return;throw e}},Vp=async e=>{let t=await zp(e);if(t===void 0)return!0;if(t.length>0)return!1;try{await d(e)}catch(e){if(!V(e))throw e}return!0},Hp=async e=>{let t=await Bp(e);return t===void 0?!0:t?Vp(e):!1},Up=async(e,t)=>{t!==e.sourcesDir&&await Hp(t)&&await Up(e,ne(t))},Wp=async(e,t)=>await Rp(t)?(Gs(e,t),await u(t,{force:!0,recursive:!0}),await Up(e,ne(t)),{removedCheckout:!0}):{removedCheckout:!1,warning:`checkout was already missing`},Gp=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),Kp=async(e,t)=>{let n=await W(e);await $s(e,{...n,refs:Gp(n.refs,t)});let r=await X(e);await Ku(e,{...r,refs:Gp(r.refs,t)})},qp=async(e,t)=>{let n=H(e.env),r=Sp(await W(n),t),i=U(n,r),{removedCheckout:a,warning:o}=await J(n,wp(r),()=>Wp(n,i));return await J(n,`home`,()=>Kp(n,r)),{data:{key:r,removed_checkout:a},warnings:Hd(o)}},Jp=e=>e.removed_checkout?[`removed ${e.key} (checkout deleted)`]:[`removed ${e.key} (checkout was already missing)`],Yp=(e,t)=>{e.command(`remove`).description(`Remove a configured ref: its config/state entry AND its checkout directory.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).action((e,n,r)=>{let i=Z(r);return $(t,i,async()=>{let{data:n,warnings:r}=await qp(t,e);Q(t,i,Jp(n),n,r)})()})},Xp=(e,t)=>{let n=e.refs[t];if(n===void 0)throw Error(`internal: matched ref key '${t}' is missing from config.refs`);return n},Zp=(e,t)=>{if(!G(e))throw v(`checkout for '${t}' is missing — run: refs sync ${t}`)},Qp=(e,t,n)=>{let r=e.packages?.[n];if(r===void 0)throw v(`no package '${n}' registered on ref '${t}'`);return r},$p=e=>`no ref matches '${e}' — run refs list, or add it: refs add <url>`,em=/^[a-z][a-z0-9+.-]*:\/\//iu,tm=/^git@[^:/\s]+:[^\s]+$/u,nm=e=>em.test(e)||tm.test(e),rm=(e,t)=>{try{return dl(e,t)}catch{if(nm(e))throw b(`query looks like a git url but is not a supported form — check the url (credentials are never accepted) or run: refs resolve <package|ref-suffix>`);return}},im=(e,t,n)=>{let r=rm(t,n);if(r!==void 0){if(Object.hasOwn(e.refs,r.key))return{key:r.key};throw v($p(t))}},am=(e,t)=>{let n=[];for(let r of Object.keys(e.refs).toSorted()){let i=e.refs[r]?.packages?.[t];i!==void 0&&n.push({entry:i,key:z.parse(r)})}return n},om=(e,t)=>`package '${e}' is registered by more than one ref: ${t.join(`, `)} — use the full ref key`,sm=(e,t)=>{let n=am(e,t),[r]=n;if(r!==void 0){if(n.length>1)throw y(om(t,n.map(e=>e.key)));return r}},cm=(e,t)=>{let n=t.split(`/`);for(let t=n.length-1;t>=1;--t){let r=n.slice(0,t).join(`/`),i=sm(e,r);if(i!==void 0)return{...i,name:r}}},lm=(e,t)=>{try{return Sp(e,t)}catch(e){throw e instanceof _&&e.code===`not_found`?v($p(t)):e}},um=(e,t,n)=>{let r=im(e,t,n);if(r!==void 0)return r;let i=sm(e,t);if(i!==void 0)return{key:i.key,packageMatch:{...i,name:t}};let a=cm(e,t);return a===void 0?{key:lm(e,t)}:{key:a.key,packageMatch:a}},dm=(e,t)=>{if(e.packageMatch===void 0)return null;let{entry:n,name:r}=e.packageMatch;return{local_path:m(t,n.path),name:r,path:n.path}},fm=async(e,t)=>{let n=H(e.env),r=await W(n),i=um(r,t,{allowFileUrls:Tp(e.env)}),a=Xp(r,i.key),o=await X(n),s=U(n,i.key),c=Qo(Y(`sync_ttl`,a,r.settings));return{key:i.key,local_path:s,missing:!G(s),package:dm(i,s),stale:mp(o.refs[i.key]?.last_fetched_at,c,Date.now())}},pm=e=>{let t=[e.key,`local_path: ${e.local_path}`];return e.package!==null&&t.push(`package: ${e.package.name}`,`local_path: ${e.package.local_path}`),t},mm=(e,t)=>{e.command(`resolve`).description(`Resolve a git url, npm package name, import path, or ref-key suffix to its ref/package.`).argument(`<query>`,`git url, npm package name, import path, or unique ref-key suffix`).action((e,n,r)=>{let i=Z(r);return $(t,i,async()=>{let n=await fm(t,e);Q(t,i,pm(n),n)})()})},hm={},gm=async(e,t)=>{if(!G(t))return{tags:[]};try{return{tags:await kc(e.runner,t,5)}}catch(e){return{tags:[],warning:`could not list tags: ${Ud(e)}`}}},_m=async(e,t,n)=>{let r=H(e.env),i=await W(r),a=Sp(i,t),o=Xp(i,a),s=await X(r),c=U(r,a),{packages:l,...u}=o,d=n.tags?await gm(e,c):void 0;return{data:{...u,key:a,local_path:c,...n.packages?{packages:l??{}}:{},packages_count:Object.keys(l??{}).length,...d===void 0?{}:{sample_tags:d.tags},state:s.refs[a]??hm},warnings:Hd(d?.warning)}},vm=e=>{let t=[`${e.key} ${e.description}`,`url: ${e.url}`,`local_path: ${e.local_path}`];return e.sample_tags!==void 0&&e.sample_tags.length>0&&t.push(`tags: ${e.sample_tags.join(`, `)}`),t},ym=(e,t)=>{e.command(`show`).description(`Show a configured ref: entry, state, local path, package count; --packages/--tags add the package map and sample tags to --json.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).option(`--packages`,`include the ref's full package map in --json output (off by default)`).option(`--tags`,`include sample tags in --json output (human output always probes for them)`).action((e,n,r)=>{let i=Z(r);return $(t,i,async()=>{let r={packages:n.packages===!0,tags:!i.json||n.tags===!0},{data:a,warnings:o}=await _m(t,e,r);Q(t,i,vm(a),a,o)})()})},bm=(e,t)=>{let n={head_sha:t.headSha,last_fetched_at:new Date().toISOString()},r=t.effectiveCloneMode??e?.effective_clone_mode;return r!==void 0&&(n.effective_clone_mode=r),n},xm=async(e,t,n)=>{let r=await W(e),i=r.refs[t];i!==void 0&&(r.refs[t]={...i,default_branch:n},await $s(e,r))},Sm=(e,t,n)=>J(e,`home`,async()=>{n.branchRenamedTo!==void 0&&await xm(e,t,n.branchRenamedTo);let r=await X(e);r.refs[t]=bm(r.refs[t],n),await Ku(e,r)}),Cm=async(e,t,n)=>{try{await J(e,`home`,async()=>{let r=await X(e);r.refs[t]={...r.refs[t],last_error:n},await Ku(e,r)})}catch{}},wm=e=>{let t=0,n=[];return{acquire:()=>{if(t<e)return t+=1,Promise.resolve();let{promise:r,resolve:i}=Promise.withResolvers();return n.push(()=>{t+=1,i()}),r},release:()=>{--t;let e=n.shift();e!==void 0&&e()}}},Tm=async(e,t)=>{await e.acquire();try{return await t()}finally{e.release()}},Em=(e,t,n)=>`checkout at ${e} points at '${q(t)}' — expected '${q(n)}'; remove the checkout directory or run refs remove before retrying`,Dm=e=>e.exitCode===0?e.stdout.trim():`(no origin remote)`,Om=(e,t)=>{try{return dl(e,{allowFileUrls:t}).key}catch{return}},km=async(e,t)=>{let n=await e.run(`git`,[`remote`,`get-url`,`origin`],{cwd:t.dest}),r=Dm(n),i=Om(t.expectedUrl,t.allowFileUrls),a=Om(r,t.allowFileUrls);if(i===void 0||a!==i)throw ye(Em(t.dest,r,t.expectedUrl))},Am=e=>`checkout at ${e} exists but is not refs-managed — remove it (rm -rf ${e}) and retry`,jm=async(e,t)=>{let n=await e.run(`git`,[`config`,`--local`,`core.hooksPath`],{cwd:t.dest});if(n.exitCode!==0||n.stdout.trim()!==t.hooksDir)throw ye(Am(t.dest))},Mm=async(e,t)=>{await a(ne(t.dest),{recursive:!0}),Gd(e,`cloning ${q(t.cloneUrl)} into ${t.dest}…`);let n=await bc(e.runner,t);return n.warning===void 0?{effectiveMode:n.effectiveMode}:{effectiveMode:n.effectiveMode,warning:n.warning}},Nm=async(e,t)=>(Gs(t.home,t.dest),G(t.dest)?(await km(e.runner,{allowFileUrls:t.allowFileUrls,dest:t.dest,expectedUrl:t.cloneUrl}),await jm(e.runner,{dest:t.dest,hooksDir:t.hooksDir}),{}):Mm(e,t)),Pm=(e,t)=>`checkout for '${e}' at ${t} is missing or corrupt (git rev-parse HEAD failed) — run: refs remove ${e}, then refs add <source> --dry-run again`,Fm=(e,t,n)=>`checkout for '${e}' at ${t} has a HEAD sha refs cannot store yet (${n.length} hex chars, expected 40) — only SHA-1 repositories are supported for now; \`--object-format=sha256\` repositories are not yet supported`,Im=async(e,t)=>{await km(e,t),await jm(e,{dest:t.dest,hooksDir:t.hooksDir});let n=await e.run(`git`,[`rev-parse`,`HEAD`],{cwd:t.dest});if(n.exitCode!==0)throw b(Pm(t.key,t.dest));let r=n.stdout.trim();if(!Hu.shape.head_sha.safeParse(r).success)throw b(Fm(t.key,t.dest,r));return r},Lm=(e,t,n)=>`sync produced a HEAD sha for '${e}' at ${t} that refs cannot store yet (${n.length} hex chars) — only SHA-1 repositories are supported for now`,Rm=(e,t,n)=>{if(!Hu.shape.head_sha.safeParse(n).success)throw b(Lm(e,t,n));return n},zm=(e,t,n)=>{let r={effectiveCloneMode:t.effectiveMode,headSha:n.headSha,status:`cloned`};return n.actualBranch!==e.ref.default_branch&&(r.branchRenamedTo=n.actualBranch),t.warning!==void 0&&(r.warning=t.warning),r},Bm=async(e,t,n)=>{await a(ne(n),{recursive:!0});let r=Y(`clone_mode`,t.ref,t.settings),i=await bc(e.runner,{cloneUrl:t.ref.url,dest:n,hooksDir:t.home.hooksDir,mode:r}),o=await Sc(e.runner,n),s=await Im(e.runner,{allowFileUrls:Tp(e.env),dest:n,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.key});return zm(t,i,{actualBranch:o,headSha:s})},Vm=async(e,t,n)=>{await jm(e.runner,{dest:n,hooksDir:t.home.hooksDir}),await km(e.runner,{allowFileUrls:Tp(e.env),dest:n,expectedUrl:t.ref.url});let r=await Oc(e.runner,{defaultBranch:t.ref.default_branch,dir:n}),i={headSha:Rm(t.key,n,r.newSha),status:r.status};return r.branchRenamedTo!==void 0&&(i.branchRenamedTo=r.branchRenamedTo),r.warning!==void 0&&(i.warning=r.warning),i},Hm=(e,t)=>J(t.home,wp(t.key),()=>{let n=U(t.home,t.key);return Gs(t.home,n),G(n)?Vm(e,t,n):Bm(e,t,n)}),Um=e=>{let t=[];e.branchRenamedTo!==void 0&&t.push(`default branch renamed to ${e.branchRenamedTo}`),e.warning!==void 0&&t.push(e.warning);let[n]=t;if(n!==void 0)return t.join(` | `)},Wm=(e,t)=>{let n={key:e,status:t.status},r=Um(t);return r!==void 0&&(n.warning=r),n},Gm=async(e,t)=>{try{let n=await Hm(e,t);return await Sm(t.home,t.key,n),Wm(t.key,n)}catch(e){let n=Ud(e);return await Cm(t.home,t.key,n),{error:n,key:t.key,status:`failed`}}},Km=(e,t)=>e.status===`rejected`?{error:Ud(e.reason),key:t,status:`failed`}:e.value,qm=async(e,t)=>{let n=wm(4);return(await Promise.allSettled(t.map(t=>Tm(n,()=>Gm(e,t))))).map((e,n)=>{let r=t[n];if(r===void 0)throw Error(`internal: sync target at index ${n} is missing`);return Km(e,r.key)})},Jm=(e,t,n)=>({home:e,key:n,ref:Xp(t,n),settings:t.settings}),Ym=(e,t,n)=>n.length===0?Object.keys(t.refs).toSorted().map(n=>Jm(e,t,z.parse(n))):n.map(n=>Jm(e,t,Sp(t,n))),Xm=(e,t,n)=>{let r=Date.now();return t.filter(t=>{let i=Qo(Y(`sync_ttl`,t.ref,t.settings)),a=mp(n.refs[t.key]?.last_fetched_at,i,r),o=!G(U(e,t.key));return a||o})},Zm=async(e,t,n)=>{if(!n)return t;let r=await X(e);return Xm(e,t,r)},Qm=async(e,t)=>{let n=H(e.env),r=await W(n),i=Ym(n,r,t.refs),a=await qm(e,await Zm(n,i,t.staleOnly));return{failedCount:a.filter(e=>e.status===`failed`).length,results:a}},$m=[`updated`,`fresh`,`cloned`,`restored`,`failed`],eh={cloned:`Cloned`,failed:`Failed`,fresh:`Fresh`,restored:`Restored`,updated:`Updated`},th=e=>{let t={cloned:[],failed:[],fresh:[],restored:[],updated:[]};for(let n of e)t[n.status].push(n);return t},nh=e=>e.status===`failed`?` ${e.key}: ${e.error??`unknown error`}`:e.warning===void 0?` ${e.key}`:` ${e.key} (${e.warning})`,rh=e=>{let t=th(e),n=[$m.map(e=>`${eh[e]} (${t[e].length})`).join(` / `)];for(let e of $m)for(let r of t[e])n.push(nh(r));return n},ih=(e,t)=>({refs:e,staleOnly:t.staleOnly===!0}),ah=(e,t)=>{e.command(`sync`).description(`Fetch (or re-clone, if the checkout is missing) configured refs — all by default.`).argument(`[refs...]`,`ref keys or unique suffixes to sync (default: every configured ref)`).option(`--stale-only`,`skip refs whose last sync is still within their ref's sync_ttl`).action((e,n,r)=>{let i=Z(r);return $(t,i,async()=>{let r=await Qm(t,ih(e,n));Q(t,i,rh(r.results),{results:r.results}),r.failedCount>0&&(process.exitCode=g.UNEXPECTED)})()})},oh=(e,t,n)=>n===void 0?e.tag_format:Qp(e,t,n).tag_format??e.tag_format,sh=async(e,t)=>{let n=H(e.env),r=await W(n),i=Sp(r,t.query),a=Xp(r,i),o=oh(a,i,t.opts.packageName),s=U(n,i);Zp(s,i);let c=await Wc(e.runner,s,o,t.version);return{key:i,ref_path:`refs/tags/${c}`,tag:c,version:t.version}},ch=e=>[`${e.key}@${e.version} -> ${e.tag}`],lh=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},uh=[up,pp,Yp,mm,ym,ah,(e,t)=>{e.command(`tag`).description(`Resolve a version to its git tag, via the ref's (or a package's) tag_format.`).argument(`<ref>`,`full ref key or a unique suffix, e.g. zod`).argument(`<version>`,`version to resolve, e.g. 4.1.0`).option(`--package <name>`,`resolve against this package's tag_format instead of the ref's`).action((e,n,r,i)=>{let a=Z(i);return $(t,a,async()=>{let i=await sh(t,{opts:lh(r),query:e,version:n});Q(t,a,ch(i),i)})()})}],dh=e=>e.description===void 0?{path:e.path}:{description:e.description,path:e.path},fh=(e,t,n)=>e.length>0?Object.fromEntries(e.map(e=>[e.name,dh(e)])):n===void 0?{}:{[n]:{path:t??`.`}},ph=e=>{let t=e.description??``;return e.tag_format===void 0?{description:t,path:e.path}:{description:t,path:e.path,tag_format:e.tag_format}},mh=e=>{let t=Object.entries(e);if(t.length!==0)return Object.fromEntries(t.map(([e,t])=>[e,ph(t)]))},hh=e=>e.description===void 0||e.description===``,gh=e=>Object.entries(e).filter(([,e])=>hh(e)).map(([e])=>e).toSorted(),_h=e=>{let t=gh(e);if(t.length!==0)throw b(`packages without a detected description: ${t.join(`, `)} — run the two-phase flow instead: refs add <source> --dry-run --json > proposal.json, fill in the package descriptions, then refs add --proposal proposal.json`)},vh=e=>{if(Object.keys(e).length!==0)return e},yh=e=>{if(e===null)throw b(`tag_format_candidate must be set to a valid tag format (containing '{version}') before finalizing — edit the proposal and provide one, or add the ref manually`);return e},bh=e=>e.packages===void 0?{default_branch:e.default_branch,description:e.description,tag_format:e.tag_format,url:e.url}:{default_branch:e.default_branch,description:e.description,packages:e.packages,tag_format:e.tag_format,url:e.url},xh=async(e,t,n)=>{let r=await Sc(e.runner,t),i=Hc(await kc(e.runner,t));return Gd(e,`detecting workspace packages…`),{defaultBranch:r,packages:fh(await Sd(t),n.npmDirectory,n.npmPkgName),tagFormatCandidate:i}},Sh=(e,t)=>J(t.home,wp(t.resolved.key),async()=>{let n=await Nm(e,{allowFileUrls:Tp(e.env),cloneUrl:t.resolved.cloneUrl,dest:t.dest,home:t.home,hooksDir:t.home.hooksDir,mode:t.cloneMode}),r={fields:await xh(e,t.dest,t.resolved)};return n.effectiveMode!==void 0&&(r.effectiveMode=n.effectiveMode),n.warning!==void 0&&(r.warning=n.warning),r}),Ch=e=>{let t={default_branch:e.cloneResult.fields.defaultBranch,description:``,key:e.resolved.key,packages:e.cloneResult.fields.packages,tag_format_candidate:e.cloneResult.fields.tagFormatCandidate,url:e.resolved.cloneUrl},n={dest:e.dest,proposal:t};return e.cloneResult.effectiveMode!==void 0&&(n.effectiveCloneMode=e.cloneResult.effectiveMode),e.cloneResult.warning!==void 0&&(n.warning=e.cloneResult.warning),n},wh=async(e,t)=>{let n=H(e.env),r=await W(n),i=kp(await Op(e,t),r.settings);jp(r,i.key),await Lp(n,i.key);let a=U(n,i.key),o=Y(`clone_mode`,void 0,r.settings),s=await Sh(e,{cloneMode:o,dest:a,home:n,resolved:i});return Ch({cloneResult:s,dest:a,resolved:i})},Th=(e,t,n)=>J(e,`home`,async()=>{jp(await W(e),t);let r=await X(e),i=r.refs[t],a=n??i?.effective_clone_mode,o={...i,pending_proposal_at:new Date().toISOString()};a!==void 0&&(o.effective_clone_mode=a),r.refs[t]=o,await Ku(e,r)}),Eh=(e,t)=>{let n=cs.safeParse(e);if(!n.success)throw b(O(n.error));let r=Uu.safeParse(t);if(!r.success)throw b(O(r.error));return{config:n.data,state:r.data}},Dh=async(e,t)=>{let n=await W(e.home);jp(n,e.ref.key);let r=bh(e.ref);n.refs[e.ref.key]=r;let i=await X(e.home);return i.refs[e.ref.key]={effective_clone_mode:e.effectiveCloneMode??i.refs[e.ref.key]?.effective_clone_mode??Y(`clone_mode`,void 0,n.settings),head_sha:t,last_fetched_at:new Date().toISOString()},{...Eh(n,i),entry:r}},Oh=async(e,t)=>{let n=Tp(e.env),r=await J(t.home,wp(t.ref.key),()=>(Gs(t.home,t.dest),Im(e.runner,{allowFileUrls:n,dest:t.dest,expectedUrl:t.ref.url,hooksDir:t.home.hooksDir,key:t.ref.key})));return J(t.home,`home`,async()=>{let{config:e,entry:n,state:i}=await Dh(t,r);return await Ku(t.home,i),await $s(t.home,e),{entry:n,key:t.ref.key}})},kh=(e,t)=>t===`-`?e.readStdin():o(t,`utf8`),Ah=e=>{try{return JSON.parse(e)}catch(e){throw b(`invalid JSON in proposal: ${Ud(e)}`)}},jh=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Mh=e=>jh(e)&&`ok`in e&&!(`key`in e),Nh=e=>{if(!Mh(e))return e;if(e.ok===!1)throw b(`proposal file contains a failed refs envelope (ok is false) — re-run the dry-run`);if(jh(e.data))return e.data;throw b(`proposal file is a refs envelope without a usable data object — re-run the dry-run`)},Ph=e=>e.code===`unrecognized_keys`,Fh=e=>e.path.length===0,Ih=(e,t)=>{let n=t.toSorted().map(e=>`"${e}"`).join(`, `);return e===``?`✖ unrecognized key(s) in proposal: ${n}`:`✖ unrecognized key(s) in proposal at ${e}: ${n}`},Lh=e=>{let t=new Map;for(let n of e){let e=lt(n.path);t.set(e,[...t.get(e)??[],...n.keys])}return[...t.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Ih(e,t))},Rh=e=>`✖ invalid proposal: ${e.message}`,zh=e=>{let t=e.issues.filter(e=>Ph(e)),n=e.issues.filter(e=>!Ph(e)),r=n.filter(e=>Fh(e));if(t.length===0&&r.length===0)return O(e);let i=n.filter(e=>!Fh(e)),a=[...Lh(t),...r.map(e=>Rh(e))];return i.length>0&&a.push(O({issues:i})),a.join(`
|
|
369
|
+
`)},Bh=e=>{let t=Vu.safeParse(e);if(!t.success)throw b(zh(t.error));return t.data},Vh=async(e,t)=>{let n=await kh(e,t);return Bh(Nh(Ah(n)))},Hh=(e,t)=>[`refs add: dry-run proposal ready for '${e}' (checkout: ${t})`,`next: review the proposal, then run refs add --proposal <file> to finalize`],Uh=async(e,t)=>{let n=await wh(e,t);await Th(H(e.env),n.proposal.key,n.effectiveCloneMode);let r=Hd(n.warning);return{data:n.proposal,human:Hh(n.proposal.key,n.dest),warnings:r}},Wh=e=>[`refs add: '${e}' added to config`],Gh=e=>{let t={default_branch:e.default_branch,description:e.description,key:e.key,tag_format:yh(e.tag_format_candidate),url:e.url},n=vh(e.packages);return n!==void 0&&(t.packages=n),t},Kh=async(e,t)=>{let n=await Vh(e,t),r=H(e.env),i=U(r,n.key);if(!G(i))throw v(`no checkout found at ${i} — run: refs add <source> --dry-run first`);let{entry:a,key:o}=await Oh(e,{dest:i,home:r,ref:Gh(n)});return{data:{entry:a,key:o},human:Wh(o),warnings:[]}},qh=(e,t)=>{_h(e.proposal.packages);let n={default_branch:e.proposal.default_branch,description:t,key:e.proposal.key,tag_format:yh(e.proposal.tag_format_candidate),url:e.proposal.url},r=mh(e.proposal.packages);return r!==void 0&&(n.packages=r),n},Jh=async(e,t,n)=>{let r=await wh(e,t),i=H(e.env),a=qh(r,n),o={dest:r.dest,home:i,ref:a};r.effectiveCloneMode!==void 0&&(o.effectiveCloneMode=r.effectiveCloneMode);let{entry:s,key:c}=await Oh(e,o),l=Hd(r.warning);return{data:{entry:s,key:c},human:Wh(c),warnings:l}},Yh=e=>{let t=[e.dryRun,e.proposal!==void 0,e.description!==void 0].filter(Boolean).length;if(t>1)throw y(`refs add: use only one of --dry-run, --proposal, or --description`);if(t===0)throw y(`refs add needs --dry-run, --proposal, or --description`)},Xh=e=>{if(e===void 0||e===``)throw y(`refs add requires <source> (a git url or npm:<package>)`);return e},Zh=(e,t)=>(Yh(t),t.proposal===void 0?t.description===void 0?Uh(e,Xh(t.source)):Jh(e,Xh(t.source),t.description):Kh(e,t.proposal)),Qh=(e,t)=>{let n={dryRun:t.dryRun===!0};return e!==void 0&&(n.source=e),t.proposal!==void 0&&(n.proposal=t.proposal),t.description!==void 0&&(n.description=t.description),n},$h=(e,t)=>{e.command(`add`).description(`Add a git reference in two phases: propose (--dry-run), then finalize (--proposal).`).argument(`[source]`,`git url or npm:<package> (omit when finalizing with --proposal)`).option(`--dry-run`,`resolve and clone the source, writing a reviewable proposal`).option(`--proposal <file>`,`finalize from a completed proposal JSON file (- for stdin)`).option(`--description <text>`,`one-shot: dry-run then finalize immediately with this description`).action((e,n,r)=>{let i=Z(r);return $(t,i,async()=>{let r=await Zh(t,Qh(e,n));Q(t,i,r.human,r.data,r.warnings)})()})},eg=e=>e===void 0?null:e,tg=()=>Object.keys(os.shape).toSorted().join(`, `),ng=e=>`unknown package field '${e}' — valid fields: ${tg()}`,rg=e=>Object.hasOwn(os.shape,e),ig=(e,t,n)=>{if(!rg(t))throw y(ng(t));let r=e[t],i=os.safeParse({...e,[t]:n});if(!i.success)throw b(O(i.error));return{field:t,newValue:i.data[t],oldValue:r,updated:i.data}},ag=async e=>{let t=Qp(e.entry,e.key,e.packageName),n=ig(t,e.field,e.value),r={...e.entry,packages:{...e.entry.packages,[e.packageName]:n.updated}};return await $s(e.home,{...e.config,refs:{...e.config.refs,[e.key]:r}}),{field:n.field,key:e.key,new:eg(n.newValue),old:eg(n.oldValue)}},og=`packages`,sg=()=>Object.keys(ss.shape).filter(e=>e!==og).toSorted().join(`, `),cg=e=>`unknown ref field '${e}' — valid fields: ${sg()}`,lg=e=>Object.hasOwn(ss.shape,e),ug=(e,t,n)=>`failed to rewrite git remote at ${e} to '${q(t)}': ${n.trim()}`,dg=async(e,t)=>{if(Gs(t.home,t.dest),!G(t.dest))return;let n=await e.runner.run(`git`,[`remote`,`set-url`,`origin`,t.cloneUrl],{cwd:t.dest});if(n.exitCode!==0)throw b(ug(t.dest,t.cloneUrl,n.stderr))},fg=async(e,t)=>{let n=dl(t.value,{allowFileUrls:Tp(e.env)});if(n.key!==t.key)throw b(`new url derives a different key — remove and re-add instead`);let r=U(t.home,t.key);return await dg(e,{cloneUrl:n.cloneUrl,dest:r,home:t.home}),{...t.entry,url:n.cloneUrl}},pg=(e,t,n)=>{let r={...e,[t]:n},i=ss.safeParse(r);if(!i.success)throw b(O(i.error));return i.data},mg=(e,t)=>t.field===`url`?fg(e,{entry:t.entry,home:t.home,key:t.key,value:t.value}):Promise.resolve(pg(t.entry,t.field,t.value)),hg=async(e,t)=>{let{field:n}=t;if(n===og)throw y(`use --package <name> <field> <value>`);if(!lg(n))throw y(cg(n));let r=t.entry[n],i=await mg(e,{entry:t.entry,field:n,home:t.home,key:t.key,value:t.value});return{new:i[n],old:r,updated:i}},gg=(e,t)=>{let n=H(e.env),{field:r,opts:i,query:a,value:o}=t;return J(n,`home`,async()=>{let t=await W(n),s=Sp(t,a),c=Xp(t,s);if(i.packageName!==void 0)return ag({config:t,entry:c,field:r,home:n,key:s,packageName:i.packageName,value:o});let l=await hg(e,{entry:c,field:r,home:n,key:s,value:o});return await $s(n,{...t,refs:{...t.refs,[s]:l.updated}}),{field:r,key:s,new:eg(l.new),old:eg(l.old)}})},_g=`settings`,vg=[],yg=()=>Object.keys(is.shape).toSorted().join(`, `),bg=e=>`unknown setting '${e}' — valid settings: ${yg()}`,xg=e=>Object.hasOwn(is.shape,e),Sg=e=>`note: 'settings' addressed the global settings, not ${e} — use the full ref key to edit that ref`,Cg=e=>{try{let t=Sp(e,_g);return[Sg(`ref '${t}'`)]}catch(e){if(e instanceof _&&e.code===`usage`)return[Sg("one of several matching refs — see `refs list`")];if(e instanceof _&&e.code===`not_found`)return vg;throw e}},wg=e=>({data:{field:e.key,key:_g,new:eg(e.parsed[e.key]),old:eg(e.old)},warnings:Cg(e.config)}),Tg=(e,t)=>{let n=H(e.env);return J(n,`home`,async()=>{let e=await W(n);if(!xg(t.key))throw y(bg(t.key));let r=e.settings[t.key],i={...e.settings,[t.key]:t.value},a=is.safeParse(i);if(!a.success)throw b(O(a.error));return await $s(n,{...e,settings:a.data}),wg({config:e,key:t.key,old:r,parsed:a.data})})},Eg=[],Dg=e=>{let t={};return e.package!==void 0&&(t.packageName=e.package),t},Og=async(e,t)=>{if(t.first===`settings`){if(t.opts.packageName!==void 0)throw y(`--package is not valid with 'refs edit settings ...' — it only applies to ref/package edits`);return Tg(e,{key:t.second,value:t.value})}return{data:await gg(e,{field:t.second,opts:t.opts,query:t.first,value:t.value}),warnings:Eg}},kg=e=>e==null?`(unset)`:String(e),Ag=e=>[`${e.key}: ${e.field} '${kg(e.old)}' -> '${kg(e.new)}'`],jg=(e,t)=>{e.command(`edit`).description(`Edit one field: 'refs edit settings <key> <value>' for a global setting, or 'refs edit <ref> <field> <value> [--package <name>]' for a ref or package field.`).argument(`<ref-or-settings>`,`a ref key/unique suffix, or the literal 'settings'`).argument(`<field-or-key>`,`field to edit (or, in settings mode, the setting key)`).argument(`<value>`,`the new value`).option(`--package <name>`,`edit this package's field instead of a top-level ref field`).action((e,n,r,i,a)=>{let o=Z(a);return $(t,o,async()=>{let{data:a,warnings:s}=await Og(t,{first:e,opts:Dg(i),second:n,value:r});Q(t,o,Ag(a),a,s)})()})},Mg=`Install the agent skill: npx skills add kaisers-io/refs (private phase: npx skills add <path-to-this-repo> --skill refs)`,Ng=async e=>{await a(e.root,{recursive:!0}),await a(e.sourcesDir,{recursive:!0}),await a(e.locksDir,{recursive:!0}),await a(e.hooksDir,{recursive:!0})},Pg=async e=>{let t=H(e.env);return await Ng(t),{config:await J(t,`home`,async()=>{let e=await lc(t,Cd);return await Mc(t),e}),home:t.root,skill_hint:Mg}},Fg=[(e,t)=>{e.command(`init`).description(`Seed or migrate the refs home directory, its config, and the git hooks guard.`).action((e,n)=>{let r=Z(n);return $(t,r,async()=>{let e=await Pg(t);Q(t,r,[`refs home: ${e.home} (${e.config})`,Mg],e)})()})},$h,jg,Cp,...uh],Ig=(e,t)=>{for(let n of Fg)n(e,t)},Lg=[``,`Examples:`,` $ refs list --json`,` $ refs sync --stale-only --json`,` $ refs resolve zod/mini --json`,``,`Every command accepts --json for structured output and --verbose for stack traces on error.`].join(`
|
|
370
|
+
`),Rg=new Set([`commander.help`,`commander.helpDisplayed`,`commander.version`]),zg=`--json`,Bg=`--verbose`,Vg=/\n$/u,Hg=/^error: /u,Ug=e=>e.replace(Hg,``),Wg=(e,t)=>{for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1},Gg=e=>Wg(e,zg),Kg=e=>Wg(e,Bg),qg=(e,t,n)=>n&&t!==void 0?`${e}\n${t}`:e,Jg=e=>{let t=new Ld().name(`refs`).description(`Manage git-based reference checkouts shared across a workspace.`).version(Cd).option(zg,`emit machine-readable JSON on stdout instead of human-readable text`).option(Bg,`include stack traces in error output`).allowExcessArguments(!1).exitOverride().configureOutput({outputError:()=>{},writeErr:t=>{e.errLine(t.replace(Vg,``))},writeOut:t=>{e.out(t.replace(Vg,``))}});return t.addHelpText(`after`,Lg),Ig(t,e),t},Yg=()=>{process.exitCode=g.OK},Xg=(e,t,n)=>{Wd(e,t,{code:`usage`,message:qg(Ug(n.message),n.stack,t.verbose)}),process.exitCode=g.USAGE},Zg=(e,t,n)=>{if(Rg.has(n.code)){Yg();return}Xg(e,t,n)},Qg=(e,t,n)=>{let r=xe(n,{verbose:t.verbose});Wd(e,t,r),process.exitCode=r.exitCode},$g=async(e,t,n)=>{let r={json:Gg(n),verbose:Kg(n)};try{await t.parseAsync(n)}catch(t){if(t instanceof Ed){Zg(e,r,t);return}Qg(e,r,t)}},e_=(e,t)=>$g(e,Jg(e),t);import.meta.main&&await e_(Td(),process.argv);export{Jg as buildProgram,Z as cliOptsOf,Q as emit,Wd as emitError,Ud as errorMessageOf,Gd as progress,Td as realContext,Ig as registerCommands,e_ as run,$g as runProgram,Hd as warningsFor,$ as wrapAction};
|