knarr 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +65 -106
  2. package/dist/{add-Clbi3vJ2.mjs → add-B_xzUp5y.mjs} +1 -1
  3. package/dist/add-flow-cvrMO_aV.mjs +5 -0
  4. package/dist/{batch-push-pVkjhRbp.mjs → batch-push-DXtZxRx0.mjs} +1 -1
  5. package/dist/build-detect-BTHh2OBm.mjs +3 -0
  6. package/dist/{bundler-detect-Cx8_R2hT.mjs → bundler-detect-Dq-QAbQj.mjs} +1 -1
  7. package/dist/check-CbVdpTsw.mjs +3 -0
  8. package/dist/clean-CyDDqbBD.mjs +3 -0
  9. package/dist/cli.mjs +3 -3
  10. package/dist/{config-CQpgsGyL.mjs → config-BJsL6NqN.mjs} +1 -1
  11. package/dist/console-CIiXr7ge.mjs +3 -0
  12. package/dist/{console-BxhMcj-D.mjs → console-CyaBcUd-.mjs} +19 -2
  13. package/dist/{dev-DeOwxr_7.mjs → dev-kqgY9NjI.mjs} +1 -1
  14. package/dist/doctor-D-S1P0UG.mjs +6 -0
  15. package/dist/{dry-run-BxVjpNqJ.mjs → dry-run-BkdMYSIx.mjs} +1 -1
  16. package/dist/errors-BlOfexcH.mjs +3 -0
  17. package/dist/explain-9Y4SZHjC.mjs +3 -0
  18. package/dist/{fs-DUcoWJ1g.mjs → fs-C4juVCTd.mjs} +1 -1
  19. package/dist/fs-CPnWm9CR.mjs +3 -0
  20. package/dist/{fs-BjaNhdzt.mjs → fs-DzsciYAL.mjs} +147 -73
  21. package/dist/{bell-UNNirKkz.mjs → history-DRhLwzhq.mjs} +1 -1
  22. package/dist/history-vS3w4EGu.mjs +3 -0
  23. package/dist/index.d.ts +17 -14
  24. package/dist/index.mjs +158 -80
  25. package/dist/init-TN84d5jM.mjs +4 -0
  26. package/dist/init-helpers-CYYWQm-P.mjs +15 -0
  27. package/dist/injector-nt40JxVt.mjs +3 -0
  28. package/dist/json-DbSkpxtr.mjs +3 -0
  29. package/dist/list-9hWJjw19.mjs +3 -0
  30. package/dist/{logger-DlikgOlh.mjs → logger-9C6B9Na8.mjs} +1 -1
  31. package/dist/migrate-Co4qcFt6.mjs +5 -0
  32. package/dist/{nextjs-config-BfHv8mBE.mjs → nextjs-config-BQgTWZ96.mjs} +1 -1
  33. package/dist/{nextjs-config-CA4N_9VY.mjs → nextjs-config-dUw2J6B9.mjs} +1 -1
  34. package/dist/{output-BxyRer_F.mjs → output-BxR2v-jn.mjs} +1 -1
  35. package/dist/{package-manager-DBBQ0XtZ.mjs → package-manager-DJ8CE0zL.mjs} +1 -1
  36. package/dist/{preflight-B8ypfoKV.mjs → preflight-BDsxR2Ct.mjs} +1 -1
  37. package/dist/{preflight-B17VQJs0.mjs → preflight-MzNjLXiy.mjs} +1 -1
  38. package/dist/{publish-BLk5_qx1.mjs → publish-C7ZUvHkE.mjs} +1 -1
  39. package/dist/publisher-CvXTbkLP.mjs +4 -0
  40. package/dist/{push-C6UFcNGO.mjs → push-B5KrkILW.mjs} +1 -1
  41. package/dist/push-engine-BpNr8qXR.mjs +3 -0
  42. package/dist/{remove-Bz9dNgDM.mjs → remove-DkOgVQMZ.mjs} +1 -1
  43. package/dist/remove-J5tY_BFk.mjs +3 -0
  44. package/dist/{reset--AuvAPTc.mjs → reset-ClGouUb5.mjs} +1 -1
  45. package/dist/{restore-CIBe2F1d.mjs → restore-Bx2V59SL.mjs} +1 -1
  46. package/dist/rollback-RPjHZWtG.mjs +3 -0
  47. package/dist/status-Rnvw6dG2.mjs +3 -0
  48. package/dist/store-DjPdOKqg.mjs +3 -0
  49. package/dist/{tailwind-source-Cgva0Hte.mjs → tailwind-source-D1cUiG-t.mjs} +1 -1
  50. package/dist/{history-BZS2YUIt.mjs → tracker-89eW0ArT.mjs} +1 -1
  51. package/dist/tracker-B3Fqx94J.mjs +3 -0
  52. package/dist/{update-Dacjzw4f.mjs → update-CAKFICZu.mjs} +1 -1
  53. package/dist/{use-BSCV4IQ5.mjs → use-CCx6J0mc.mjs} +1 -1
  54. package/dist/{vite-config-DqxvL5TW.mjs → vite-config-BHmawlD2.mjs} +1 -1
  55. package/dist/{vite-config-CbYEhn5K.mjs → vite-config-BRlYc4ni.mjs} +1 -1
  56. package/dist/{watch-orchestrator-CghvwrNS.mjs → watch-orchestrator-BfuCaZLA.mjs} +1 -1
  57. package/dist/watcher-T123sBDg.mjs +3 -0
  58. package/dist/workspace-CdLSxPFS.mjs +3 -0
  59. package/dist/{workspace-D4vhzpO4.mjs → workspace-DBxNrowu.mjs} +1 -1
  60. package/package.json +3 -2
  61. package/dist/add-flow-DdDziP5M.mjs +0 -5
  62. package/dist/bell-BJuCym_5.mjs +0 -11
  63. package/dist/bell-CIzHg0kw.mjs +0 -3
  64. package/dist/build-detect-mSo9jKXK.mjs +0 -3
  65. package/dist/check-Boh8WU_W.mjs +0 -3
  66. package/dist/clean-DHh6fpmR.mjs +0 -3
  67. package/dist/console-X31Y_QS5.mjs +0 -3
  68. package/dist/doctor-XEdsr84Q.mjs +0 -6
  69. package/dist/errors-CV7G61Hr.mjs +0 -3
  70. package/dist/explain-BBv3U-D3.mjs +0 -3
  71. package/dist/fs-Cf1JTFyh.mjs +0 -3
  72. package/dist/history-C5ehozRy.mjs +0 -3
  73. package/dist/init-Dwf-EIG3.mjs +0 -4
  74. package/dist/init-helpers-BfDosqvf.mjs +0 -15
  75. package/dist/injector-XwK_LBUh.mjs +0 -3
  76. package/dist/json-C6XtcMC4.mjs +0 -46
  77. package/dist/json-CWzEb9Rt.mjs +0 -3
  78. package/dist/list-DcREV9JM.mjs +0 -3
  79. package/dist/migrate-DW5KQeDq.mjs +0 -5
  80. package/dist/publisher-Br4Od-iL.mjs +0 -4
  81. package/dist/push-engine-D3rfg2Tj.mjs +0 -3
  82. package/dist/remove-DMj6k2PK.mjs +0 -3
  83. package/dist/rollback-CFLIncnW.mjs +0 -3
  84. package/dist/rolldown-runtime-D3KUYPsf.mjs +0 -12
  85. package/dist/status-Dy-e_RtI.mjs +0 -3
  86. package/dist/store-BNeGfW_b.mjs +0 -3
  87. package/dist/tracker-DXSo5wXO.mjs +0 -3
  88. package/dist/tracker-DofCXLTP.mjs +0 -3
  89. package/dist/watcher-Bw_qcI0M.mjs +0 -3
  90. package/dist/workspace-DVY5o1g8.mjs +0 -3
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  <p align="center">
2
- <img src="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/knarr-wordmark.png" width="360" alt="Knarr logo" />
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/knarr-wordmark.png" />
4
+ <img src="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/knarr-wordmark-light.png" width="360" alt="Knarr" />
5
+ </picture>
3
6
  </p>
4
7
 
5
8
  <p align="center">
6
9
  <a href="https://www.npmjs.com/package/knarr"><img src="https://img.shields.io/npm/v/knarr?color=blue" alt="npm version" /></a>
7
10
  <a href="https://www.npmjs.com/package/knarr"><img src="https://img.shields.io/npm/dm/knarr" alt="npm downloads" /></a>
8
- <a href="https://www.npmjs.com/package/knarr"><img src="https://img.shields.io/npm/unpacked-size/knarr" alt="unpacked size" /></a>
9
- <a href="https://bundlephobia.com/package/knarr"><img src="https://badgen.net/bundlephobia/minzip/knarr" alt="minzipped size" /></a>
10
- <br>
11
11
  <a href="https://github.com/oleg-kuibar/knarr/actions/workflows/ci.yml"><img src="https://github.com/oleg-kuibar/knarr/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
12
12
  <a href="https://github.com/oleg-kuibar/knarr/actions/workflows/compat.yml"><img src="https://github.com/oleg-kuibar/knarr/actions/workflows/compat.yml/badge.svg" alt="Compatibility" /></a>
13
13
  <a href="https://github.com/oleg-kuibar/knarr/blob/master/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="license" /></a>
@@ -16,151 +16,110 @@
16
16
 
17
17
  # Knarr
18
18
 
19
- Test local npm packages in real apps without `npm link` symlink surprises or local package references in `package.json`.
19
+ **Test a local npm package in a real app, without `npm link`.**
20
20
 
21
- Knarr copies the package files you would publish into the consumer app's `node_modules/`, then keeps registered consumers updated. It detects npm, pnpm, Bun, and Yarn projects that use `node_modules` or Yarn's pnpm linker. Yarn PnP is not compatible because it removes `node_modules`.
21
+ Knarr copies the files your package would publish into the app's `node_modules/`, then keeps them in sync while you work. The app sees a normal installed package: one copy of React, no symlinks for the bundler to trip on, and no `file:` paths in `package.json` or the lockfile.
22
22
 
23
23
  ```bash
24
24
  cd my-app
25
- npx knarr use ../my-lib
25
+ npx knarr use ../my-lib # build, publish, and copy my-lib into my-app
26
26
 
27
27
  cd ../my-lib
28
- knarr dev
28
+ npx knarr dev # on every save: rebuild and push to my-app
29
29
  ```
30
30
 
31
- If you have not installed Knarr globally, use `npx knarr dev` for the second command too.
32
-
33
- ![Knarr local package workflow](https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/knarr-demo.gif)
31
+ <p align="center">
32
+ <img src="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/demo.svg" width="960" alt="Terminal: knarr use links my-lib into my-app, then knarr dev rebuilds and pushes my-lib on save" />
33
+ </p>
34
34
 
35
- ## Who this is for
35
+ ## Why not `npm link`?
36
36
 
37
- - Library and design-system authors testing packages inside real consumer apps
38
- - React developers avoiding duplicate dependency instances and invalid hook calls from symlinks
39
- - pnpm users who want updates copied into the existing virtual-store install when possible
40
- - Teams that want local package overrides to stay out of dependency specs and lockfiles
37
+ <p align="center">
38
+ <img src="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/symlink-vs-copy.svg" width="960" alt="npm link makes node_modules/my-lib a symlink, so my-lib loads its own React. Knarr copies real files, so my-lib uses the app's React." />
39
+ </p>
41
40
 
42
- ## Why Knarr?
41
+ A symlinked package resolves its imports from its own folder, so the app can end up with two copies of React (or any other peer dependency), and some bundlers won't follow the link outside the project. yalc copies files too, but it rewrites the app's dependency to a `file:` path. Knarr leaves the dependency spec alone.
43
42
 
44
- `npm link` creates symlinks that can break module resolution: duplicate dependency instances, peer dependency mismatches, and bundlers that cannot follow links outside the project root. yalc improves this by copying files, but its workflow can rewrite consumer dependency specs or require extra watch tooling.
43
+ If pnpm workspaces, `file:`, or pnpm's `injected` dependencies already fit your repo, use those. Knarr is for testing a package in an app it doesn't share a workspace with, exactly as it will be installed. See the [comparison](docs/comparison.md).
45
44
 
46
- Knarr keeps the local override out of your dependency spec. It publishes a local package into `~/.knarr/store/`, injects that package into every registered consumer, and can watch, rebuild, and push changes continuously. Setup helpers may still add `.knarr/`, `.gitignore`, a restore hook, or bundler config when needed.
45
+ ## How it works
47
46
 
48
- If pnpm workspaces, `file:`, or `dependenciesMeta.*.injected` already fit your repo, use those native features first. Knarr is for the narrower case where you want publishable package files copied into real consumers while their dependency specs stay normal.
47
+ <p align="center">
48
+ <img src="https://raw.githubusercontent.com/oleg-kuibar/knarr/master/docs/assets/how-it-works.svg" width="960" alt="knarr publish copies my-lib's packed files into ~/.knarr/store. add or use copies them into each app's node_modules. knarr dev rebuilds, publishes, and pushes on save." />
49
+ </p>
49
50
 
50
- ## Quick Start
51
+ 1. **`publish`** picks files the way `npm pack` does (`files`, `.npmignore`, `publishConfig.directory`) and copies them into a store at `~/.knarr/store/<name>@<version>/`.
52
+ 2. **`add`** copies a package from the store into an app's `node_modules/` and registers the app. **`use`** does `publish` + `add` in one step.
53
+ 3. **`push`** publishes and updates every registered app. Only files whose contents changed are copied.
54
+ 4. **`dev`** watches the source, runs your build, and pushes after each change. `dev --all` does this for every package in a workspace, in dependency order.
51
55
 
52
- One command links a local package into the app you are testing:
56
+ ## What it changes in your app
53
57
 
54
- ```bash
55
- # In your app
56
- cd my-app
57
- npx knarr use ../my-lib
58
- ```
59
-
60
- Then run the continuous package dev loop from the library:
58
+ | | |
59
+ | --- | --- |
60
+ | `node_modules/<pkg>/` | Replaced with the published files. The original install is backed up, and `knarr remove` restores it. |
61
+ | `.knarr/` | Link state and the restore script. Added to `.gitignore`. |
62
+ | `package.json` | A `postinstall` hook that puts links back after `npm install` wipes them. It does nothing for teammates without Knarr. Dependencies are untouched. |
63
+ | Bundler config | Vite: adds the `knarr/vite` plugin. Next.js: adds the package to `transpilePackages`. Tailwind v4: adds an `@source` line. Each is skipped with instructions if the config is too complex to edit safely. |
64
+ | Lockfile | Untouched. |
61
65
 
62
- ```bash
63
- # In your library
64
- cd ../my-lib
65
- knarr dev
66
- ```
66
+ ## Compatibility
67
67
 
68
- If Knarr is not installed globally, run `npx knarr dev` instead.
68
+ | | |
69
+ | --- | --- |
70
+ | Package managers | npm, pnpm (including its virtual store), Yarn 4 with `node-modules` or `pnpm` linker, Bun. Yarn PnP isn't supported because it has no `node_modules`. |
71
+ | Bundlers | Vite, Webpack, rspack, Next.js. Others pick up the changed files in `node_modules` on their own. |
72
+ | Platforms | macOS, Linux, Windows. |
73
+ | Node.js | 22.22 or newer. |
69
74
 
70
- That is the everyday loop: edit `my-lib`, Knarr rebuilds it, pushes changed files into `my-app/node_modules/`, and your dev server sees normal file changes there.
75
+ CI runs the test suite on all three platforms, and links a package into real npm, pnpm, Yarn, Bun, Vite, Webpack, rspack, and Next.js apps (`pnpm compat:smoke`).
71
76
 
72
- If you prefer the explicit steps:
77
+ ## Install
73
78
 
74
79
  ```bash
75
- cd my-lib
76
- pnpm build
77
- knarr publish
78
-
79
- cd ../my-app
80
- knarr add my-lib
81
- ```
82
-
83
- ## How It Works
84
-
85
- ```mermaid
86
- graph LR
87
- A["my-lib/"] -- "knarr publish" --> B["~/.knarr/store/<br/>my-lib@1.0.0"]
88
- B -- "knarr use ../my-lib<br/>or knarr add my-lib" --> C["app/node_modules/<br/>my-lib/"]
89
- B -- "knarr push" --> D["app-2/node_modules/<br/>my-lib/"]
90
-
91
- style A fill:#2e7d32,stroke:#66bb6a,color:#e8f5e9
92
- style B fill:#1565c0,stroke:#64b5f6,color:#e3f2fd
93
- style C fill:#e65100,stroke:#ffb74d,color:#fff3e0
94
- style D fill:#e65100,stroke:#ffb74d,color:#fff3e0
80
+ npm install -g knarr # or: pnpm add -g knarr
95
81
  ```
96
82
 
97
- 1. `publish` copies built files to a local store at `~/.knarr/store/`
98
- 2. `use` publishes from a local path and links it into the current app
99
- 3. `add` links an already-published package from the store
100
- 4. `push` publishes and copies to all registered consumers
101
- 5. `dev` watches, builds, publishes, and pushes continuously
83
+ Or skip the install and run every command through `npx knarr`.
102
84
 
103
- ## What Knarr Does
85
+ ## Commands
104
86
 
105
- | Area | Behavior |
87
+ | Command | What it does |
106
88
  | --- | --- |
107
- | Store | `~/.knarr/store/<name>@<version>/package/`, or `KNARR_HOME/store/...` when `KNARR_HOME` is set |
108
- | Consumer copy | Copies package files into `node_modules/<package>/` and records link state in `.knarr/state.json` |
109
- | Package files | Uses npm-pack-compatible file resolution, including the `files` field and `publishConfig.directory` |
110
- | pnpm | Follows existing pnpm virtual-store symlinks when present; falls back to a direct `node_modules` path |
111
- | Watch loop | `knarr dev` runs an initial push, then watches, rebuilds, publishes, and pushes again |
112
- | Reinstall recovery | `knarr restore` re-injects registered packages after `node_modules` is replaced |
113
- | Bundlers | Vite plugin triggers reload/restart, Next.js uses `transpilePackages`, Webpack/rspack plugin invalidates watch/cache, and other bundlers rely on file changes under `node_modules` |
114
- | Incremental sync | Skips same size and mtime, hashes same-size changed-mtime files with xxHash64, and removes stale destination files |
89
+ | `knarr use <path>` | Build, publish, and link a local package into this app. |
90
+ | `knarr dev [--all]` | Watch, build, and push on every change. |
91
+ | `knarr publish` / `knarr push` | Copy into the store / and update every linked app. |
92
+ | `knarr add <pkg>` / `knarr remove <pkg>` | Link from the store / restore the original install. |
93
+ | `knarr status`, `knarr list`, `knarr explain` | What is linked where, and why. |
94
+ | `knarr restore`, `knarr update`, `knarr rollback` | Re-apply links, pull the latest build, go back to an earlier build. |
95
+ | `knarr doctor`, `knarr check` | Diagnose setup problems; check a package's `exports` and files. |
96
+ | `knarr init`, `knarr migrate`, `knarr clean`, `knarr reset` | Set up an app, move from yalc, prune the store, undo everything. |
115
97
 
116
- See [detailed comparison](docs/comparison.md) for native pnpm options, yalc, symlink workflows, and Knarr tradeoffs.
98
+ Every command takes `--dry-run`, `--json`, and `--verbose`. Full reference: [docs/commands.md](docs/commands.md).
117
99
 
118
- ## Migrate From yalc In 60 Seconds
100
+ ## Coming from yalc
119
101
 
120
102
  ```bash
121
103
  cd my-app
122
- npx knarr migrate
123
- npx knarr use ../my-lib
124
-
125
- cd ../my-lib
126
- knarr dev
127
- ```
128
-
129
- See [Migrating from yalc](docs/migrating-from-yalc.md) for the full guide.
130
-
131
- ## Install
132
-
133
- ```bash
134
- pnpm add -g knarr # or npm install -g knarr
135
- npx knarr init # optional consumer setup and repair helpers
104
+ npx knarr migrate --from ../my-lib # remove .yalc/, yalc.lock, and file:.yalc deps, then link my-lib
136
105
  ```
137
106
 
138
- ## Performance Notes
139
-
140
- Knarr uses Node's copy-on-write reflink mode when the current filesystem supports it, with automatic fallback to a normal copy. Reflink support is probed once per volume and cached. Incremental sync checks size and mtime first, then falls back to xxHash64 only when needed, so unchanged files are skipped quickly.
107
+ See [Migrating from yalc](docs/migrating-from-yalc.md).
141
108
 
142
109
  ## Documentation
143
110
 
144
- - [Getting Started](docs/getting-started.md)
111
+ - [Getting started](docs/getting-started.md)
145
112
  - [Commands](docs/commands.md)
146
- - [Comparison](docs/comparison.md)
147
- - [Troubleshooting](docs/troubleshooting.md)
148
- - [CI/CD](docs/ci-cd.md)
149
- - [Examples](examples/)
113
+ - [How it works](docs/how-it-works.md)
114
+ - [Bundlers](docs/bundlers.md) and [monorepos](docs/monorepo.md)
115
+ - [Troubleshooting](docs/troubleshooting.md) and [FAQ](docs/faq.md)
116
+ - [CI/CD](docs/ci-cd.md): Knarr is for local development; use canary releases in CI.
117
+ - [Programmatic API](docs/api.md) (experimental)
150
118
  - [Contributing](CONTRIBUTING.md)
151
119
 
152
- Additional guides for bundlers, CI, monorepos, internals, and the experimental programmatic API live in [docs/](docs/).
153
-
154
120
  ## Acknowledgments
155
121
 
156
- Knarr is built on top of excellent open-source projects:
157
-
158
- - [chokidar](https://github.com/paulmillr/chokidar) - file watching
159
- - [xxhash-wasm](https://github.com/nicolo-ribaudo/xxhash-wasm-legacy) - fast file hashing
160
- - [citty](https://github.com/unjs/citty) - CLI framework
161
- - [tsup](https://github.com/egoist/tsup) - TypeScript bundler
162
- - [vitest](https://vitest.dev) - test runner
163
- - [Vite](https://vite.dev) - frontend tooling
122
+ Built on [chokidar](https://github.com/paulmillr/chokidar) (file watching), [xxhash-wasm](https://github.com/jungomi/xxhash-wasm) (hashing), [citty](https://github.com/unjs/citty) (CLI), and [picomatch](https://github.com/micromatch/picomatch) (globs), bundled with [tsdown](https://tsdown.dev) and tested with [Vitest](https://vitest.dev).
164
123
 
165
124
  ## License
166
125
 
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
- import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{t}from"./timer-DqgB175x.mjs";import{n}from"./output-BxyRer_F.mjs";import{t as r}from"./add-flow-DdDziP5M.mjs";var i=e({meta:{name:`add`,description:`Link a package from the Knarr store into this project`},args:{package:{type:`positional`,description:`Package name to add`,required:!0},from:{type:`string`,description:`Path to package source (will publish first)`},build:{type:`string`,description:`Build command to run before publishing --from`},"skip-build":{type:`boolean`,description:`Skip build detection before publishing --from`,default:!1},yes:{type:`boolean`,alias:`y`,description:`Auto-accept prompts (install missing deps, etc.)`,default:!1}},async run({args:e}){n(),await r({packageArg:e.package,from:e.from,build:e.build,skipBuild:e[`skip-build`],yes:e.yes,timer:new t})}});export{i as default};
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{t}from"./timer-DqgB175x.mjs";import{n}from"./output-BxR2v-jn.mjs";import{t as r}from"./add-flow-cvrMO_aV.mjs";var i=e({meta:{name:`add`,description:`Link a package from the Knarr store into this project`},args:{package:{type:`positional`,description:`Package name to add`,required:!0},from:{type:`string`,description:`Path to package source (will publish first)`},build:{type:`string`,description:`Build command to run before publishing --from`},"skip-build":{type:`boolean`,description:`Skip build detection before publishing --from`,default:!1},yes:{type:`boolean`,alias:`y`,description:`Auto-accept prompts (install missing deps, etc.)`,default:!1}},async run({args:e}){n(),await r({packageArg:e.package,from:e.from,build:e.build,skipBuild:e[`skip-build`],yes:e.yes,timer:new t})}});export{i as default};
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{n as e}from"./shell-RQ7Hf1kp.mjs";import{t}from"./hints-Hz3V4h3A.mjs";import{t as n}from"./console-CIiXr7ge.mjs";import{n as r,t as i}from"./store-DjPdOKqg.mjs";import{t as a}from"./publisher-CvXTbkLP.mjs";import{i as o,n as s,r as c,t as l}from"./injector-nt40JxVt.mjs";import{d as u,h as d,n as f,o as p}from"./tracker-B3Fqx94J.mjs";import{M as m,N as h,P as g,c as _,v}from"./fs-CPnWm9CR.mjs";import{t as y}from"./package-manager-DJ8CE0zL.mjs";import{t as b}from"./build-detect-BTHh2OBm.mjs";import{n as x}from"./bundler-detect-Dq-QAbQj.mjs";import{i as S,o as C}from"./init-helpers-CYYWQm-P.mjs";import{t as w}from"./nextjs-config-dUw2J6B9.mjs";import{t as T}from"./timer-DqgB175x.mjs";import{t as E}from"./output-BxR2v-jn.mjs";import{t as D}from"./errors-BlOfexcH.mjs";import{i as O,n as k,r as A}from"./logger-9C6B9Na8.mjs";import{i as j,r as M}from"./dry-run-BkdMYSIx.mjs";import{o as N}from"./json-DbSkpxtr.mjs";import{readFile as P}from"node:fs/promises";import{basename as F,join as I,resolve as L}from"node:path";async function addPackageToConsumer(e){let s=e.timer??new T,m=L(`.`),{name:b,version:x}=parsePackageArg(e.packageArg),w,O=null,A=!1,j=!1;if(validatePackageNameArg(b,e.packageArg),x)try{h(x)}catch{D(`Invalid package version "${x}" in "${e.packageArg}".`),process.exit(1)}let N=(await y(m)).resolve(),P=N.packageManager;if(N.nodeModulesCompatible||(n.error(N.incompatibilityReason),process.exit(1)),e.from){let t=L(e.from);w=t;let r=await maybeBuildSource(t,{build:e.build,skipBuild:e.skipBuild,yes:e.yes??!1});O=r.buildCmd,A=r.ran,j=r.skipped,n.info(`Publishing from ${t}...`),await a(t)}let F=x?await r(b,x):await i(b);if(!F){let e=x?`@${x}`:``;D(`Package "${b}${e}" not found in store. Run 'knarr publish' in the package directory first, or use --from <path>.`),process.exit(1)}await _(v(m))||(await S(m,P),n.success(`Auto-initialized knarr (consumer mode)`)),n.info(`Detected package manager: ${P}`);let I=await p(m,b);I&&(I.version===F.version?n.info(`Updating ${b}@${F.version} (already linked)`):n.info(`Updating ${b}: ${I.version} -> ${F.version}`));let R=I?I.backupExists:await l(m,b,P);!I&&R&&n.info(`Backed up existing ${b} installation`),await g(m,b,F.version),await configureBundler(m,b,N),await handleMissingDeps(F,m,N,e.yes??!1);let z=await c(F,m,P);n.success(`Linked ${b}@${F.version} -> node_modules/${b} (${z.copied} files copied, ${z.skipped} unchanged)`),z.binLinks>0&&n.info(`Created ${z.binLinks} bin link(s)`);let B={version:F.version,contentHash:F.meta.contentHash,linkedAt:(/* @__PURE__ */ new Date()).toISOString(),sourcePath:F.meta.sourcePath,backupExists:R,packageManager:P,buildId:F.meta.buildId??``};await f(m,b,B),await u(b,m).catch(d),await C(m),await o(m,b)||n.info(`${b} isn't in package.json, so adding or removing other packages can prune it. Run \`knarr restore\` afterwards, or add it to dependencies.`);let V=w?[`cd ${w} && knarr dev`]:[];w&&n.info(`Next: ${t(w,process.cwd(),await workspaceRootFor(w))}`),n.info(`Done in ${s.elapsed()}`);let H={package:b,version:F.version,copied:z.copied,skipped:z.skipped,binLinks:z.binLinks,elapsed:s.elapsedMs(),buildCmd:O,buildRan:A,buildSkipped:j,nextSteps:V};return e.emitOutput!==!1&&E(H),k()&&M(),H}async function readPackageNameFromSource(e){let t=L(e);await _(t)||(D(`Source path not found: ${t}`),process.exit(1));let n=I(t,`package.json`);await _(n)||(D(`No package.json found at ${n}. Pass a package directory to 'knarr use'.`),process.exit(1));let r;try{r=N(await P(n,`utf-8`))}catch(e){D(`Could not read package.json at ${n}: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}r&&typeof r==`object`&&typeof r.name==`string`||(D(`package.json at ${n} must include a package name for 'knarr use'.`),process.exit(1));let i=r.name.trim();return validatePackageNameArg(i,i),i}function parsePackageArg(e){if(e.startsWith(`@`)){let t=e.indexOf(`/`);if(t>0){let n=e.indexOf(`@`,t);if(n>t)return{name:e.slice(0,n),version:e.slice(n+1)}}return{name:e,version:null}}let t=e.lastIndexOf(`@`);return t>0?{name:e.slice(0,t),version:e.slice(t+1)}:{name:e,version:null}}function validatePackageNameArg(e,t){try{m(e)}catch{D(`Invalid package name "${t}". Use format: package-name or @scope/package-name.`),process.exit(1)}}async function maybeBuildSource(e,t){if(t.skipBuild)return t.build&&n.warn(`--skip-build was provided; ignoring --build`),{buildCmd:null,ran:!1,skipped:!0};let r=t.build,i=!!r;if(!r){let t=(await y(e)).resolve().packageManager;r=await b(e,t)??void 0}if(!r)return{buildCmd:null,ran:!1,skipped:!1};if(!i&&!t.yes&&!A()){let e=await n.prompt(`Run detected build command before publishing? (${r})`,{type:`confirm`,initial:!0});if(!e||typeof e==`symbol`)return n.info(`Skipping build before publish`),{buildCmd:r,ran:!1,skipped:!0}}else if(!i&&A()&&!t.yes)return O(`[add] Detected build command but skipping in json mode: ${r}`),{buildCmd:r,ran:!1,skipped:!0};return n.info(k()?`[dry-run] Would run build command: ${r}`:`Running build command: ${r}`),await runShellCommand(r,e)||(D(`Build command failed: ${r}`),await explainBuildFailure(e),process.exit(1)),{buildCmd:r,ran:!0,skipped:!1}}async function workspaceRootFor(e){let{findWorkspacePackageRoot:t,findWorkspacePackages:n}=await import(`./workspace-DBxNrowu.mjs`),r=await t(e);if(!r)return null;let i=await n(r),a=L(e);return i.some(e=>L(e)===a)?r:null}async function explainBuildFailure(e){if(!await _(I(e,`node_modules`))){let t=(await y(e)).resolve().packageManager;n.info(`Suggestion: ${e} has no node_modules. Run \`${t} install\` there, then retry.`)}n.info(`Suggestion: if the package is already built, re-run with --skip-build.`)}async function handleMissingDeps(e,t,r,i){let a=r.packageManager,o=await s(e,t,a);if(o.length!==0){if(A())O(`[add] Missing transitive deps (json mode): ${o.join(`, `)}`);else if(i){let e=r.installCommand(o),t=r.formatCommand(e);n.info(k()?`[dry-run] Would install missing dependencies: ${o.join(`, `)}`:`Installing missing dependencies: ${o.join(`, `)}`);let i=await r.run(e);i&&!k()?n.success(`Installed missing dependencies`):i||n.warn(`Install failed. Run manually: ${t}`)}else if(await n.prompt(`Install ${o.length} missing dependencies? (${o.join(`, `)})`,{type:`confirm`,initial:!0})){let e=r.installCommand(o),t=r.formatCommand(e),i=await r.run(e);i&&!k()?n.success(`Installed missing dependencies`):i||n.warn(`Install failed. Run manually: ${t}`)}else{let e=r.installCommand(o);n.warn(`Missing transitive dependencies: ${o.join(`, `)}\n Run: ${r.formatCommand(e)}`)}}}async function configureBundler(e,t,r){let i=await x(e);if(i.type===`next`&&i.configFile){let e=await w(i.configFile,t);e.modified?n.success(`Added ${t} to transpilePackages in ${F(i.configFile)}`):e.error&&n.info(`Add to next.config manually: transpilePackages: ['${t}']`)}else if(i.type===`vite`&&i.configFile){let{addKnarrVitePlugin:e}=await import(`./vite-config-BRlYc4ni.mjs`),t=await e(i.configFile);if(t.modified){n.success(`Added knarr plugin to ${F(i.configFile)}`);let e=r.installCommand([`knarr`],{dev:!0}),t=r.formatCommand(e);n.info(k()?`[dry-run] Would install knarr as devDependency`:`Installing knarr as devDependency...`);let a=await r.run(e);a&&!k()?n.success(`Installed knarr`):a||n.warn(`Install failed. Run manually: ${t}`)}else t.error&&n.info(`Add manually:
4
+ import knarr from "knarr/vite"
5
+ plugins: [knarr()]`)}let{findTailwindCss:a,addTailwindSource:o}=await import(`./tailwind-source-D1cUiG-t.mjs`),s=await a(e);if(s){let r=await o(s,t,e);r.modified?n.success(`Added @source for ${t} to ${F(s)}`):r.error&&n.info(`Add to your CSS manually: @source "../node_modules/${t}";`)}}function runShellCommand(t,n){return k()?(j({type:`command-skip`,path:n,detail:t}),Promise.resolve(!0)):new Promise(r=>{let i=e(t,{cwd:n,stdio:`inherit`});i.on(`close`,e=>r(e===0)),i.on(`error`,()=>r(!1))})}export{readPackageNameFromSource as n,addPackageToConsumer as t};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
- import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./console-X31Y_QS5.mjs";import{n as t,r as n,t as r}from"./workspace-DVY5o1g8.mjs";import{n as i,t as a}from"./topo-sort-yd4jxr_E.mjs";import{t as o}from"./push-engine-D3rfg2Tj.mjs";import{t as s}from"./timer-DqgB175x.mjs";import{i as c}from"./logger-DlikgOlh.mjs";async function doPushAll(l,u={}){let d=new s,f=await t(l),p=n(f);if(p.packages.length===0){e.warn(`No publishable workspace packages found`);return}let m=f.packages.length-p.packages.length;m>0&&e.info(`Skipping ${m} private workspace package(s)`);let h;try{h=i(p.adjacency)}catch(t){throw t instanceof a&&e.error(`Cannot push: ${t.message}`),t}let g=new Map(p.packages.map(e=>[e.name,e.dir]));e.info(`Pushing ${h.length} packages in dependency order`),c(`[batch-push] Order: ${h.join(` → `)}`);let _=r(p.adjacency),v=new Set(u.skipPackages??[]);for(let e of[...v])markTransitiveDependentsBlocked(e,_,v);let y=0,b=0,x=0;for(let t of h){let n=g.get(t);if(n){if(v.has(t))c(`[batch-push] Skipping ${t}: dependency build/push failed`),x++;else try{(await o(n,u)).failedConsumers>0?(b++,markTransitiveDependentsBlocked(t,_,v)):y++}catch(n){e.warn(`Failed to push ${t}: ${n instanceof Error?n.message:String(n)}`),b++,markTransitiveDependentsBlocked(t,_,v)}}}let S=[b>0?`${b} failed`:null,x>0?`${x} skipped`:null].filter(e=>e!==null),C=`Pushed ${y}/${h.length} packages in ${d.elapsed()}`+(S.length>0?` (${S.join(`, `)})`:``);if(b>0)throw e.warn(C),Error(`Failed to push ${b} workspace package(s)`);x>0?e.warn(C):e.success(C)}function markTransitiveDependentsBlocked(e,t,n){for(let r of t.get(e)??[])n.has(r)||(n.add(r),markTransitiveDependentsBlocked(r,t,n))}export{doPushAll as t};
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./console-CIiXr7ge.mjs";import{n as t,r as n,t as r}from"./workspace-CdLSxPFS.mjs";import{n as i,t as a}from"./topo-sort-yd4jxr_E.mjs";import{t as o}from"./push-engine-BpNr8qXR.mjs";import{t as s}from"./timer-DqgB175x.mjs";import{i as c}from"./logger-9C6B9Na8.mjs";async function doPushAll(l,u={}){let d=new s,f=await t(l),p=n(f);if(p.packages.length===0){e.warn(`No publishable workspace packages found`);return}let m=f.packages.length-p.packages.length;m>0&&e.info(`Skipping ${m} private workspace package(s)`);let h;try{h=i(p.adjacency)}catch(t){throw t instanceof a&&e.error(`Cannot push: ${t.message}`),t}let g=new Map(p.packages.map(e=>[e.name,e.dir]));e.info(`Pushing ${h.length} packages in dependency order`),c(`[batch-push] Order: ${h.join(` → `)}`);let _=r(p.adjacency),v=new Set(u.skipPackages??[]);for(let e of[...v])markTransitiveDependentsBlocked(e,_,v);let y=0,b=0,x=0;for(let t of h){let n=g.get(t);if(n){if(v.has(t))c(`[batch-push] Skipping ${t}: dependency build/push failed`),x++;else try{(await o(n,u)).failedConsumers>0?(b++,markTransitiveDependentsBlocked(t,_,v)):y++}catch(n){e.warn(`Failed to push ${t}: ${n instanceof Error?n.message:String(n)}`),b++,markTransitiveDependentsBlocked(t,_,v)}}}let S=[b>0?`${b} failed`:null,x>0?`${x} skipped`:null].filter(e=>e!==null),C=`Pushed ${y}/${h.length} packages in ${d.elapsed()}`+(S.length>0?` (${S.join(`, `)})`:``);if(b>0)throw e.warn(C),Error(`Failed to push ${b} workspace package(s)`);x>0?e.warn(C):e.success(C)}function markTransitiveDependentsBlocked(e,t,n){for(let r of t.get(e)??[])n.has(r)||(n.add(r),markTransitiveDependentsBlocked(r,t,n))}export{doPushAll as t};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{c as e,u as t}from"./json-DbSkpxtr.mjs";import{join as n}from"node:path";async function detectBuildCommand(r,i){let a=i===`npm`||i===`bun`?`${i} run `:`${i} `;try{let i=t(await e(n(r,`package.json`)),`scripts`);for(let e of[`build`,`compile`,`bundle`,`tsc`])if(i[e])return`${a}${e}`}catch{}return null}export{detectBuildCommand as t};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
- import"./rolldown-runtime-BZbIAPMk.mjs";import{c as e}from"./fs-Cf1JTFyh.mjs";import{join as t}from"node:path";const n=[[`vite`,[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]],[`next`,[`next.config.js`,`next.config.ts`,`next.config.mjs`]],[`webpack`,[`webpack.config.js`,`webpack.config.ts`]],[`turbo`,[`turbo.json`]],[`rollup`,[`rollup.config.js`,`rollup.config.ts`,`rollup.config.mjs`]]];async function detectBundler(r){for(let[i,a]of n)for(let n of a){let a=t(r,n);if(await e(a))return{type:i,configFile:a}}return{type:null,configFile:null}}async function detectAllBundlers(r){let i=n.flatMap(([n,i])=>i.map(async i=>({type:n,configFile:t(r,i),found:await e(t(r,i))}))),a=await Promise.all(i),o=/* @__PURE__ */ new Set,s=[];for(let{type:e,configFile:t,found:n}of a)n&&!o.has(e)&&(o.add(e),s.push({type:e,configFile:t}));return s}export{detectBundler as n,detectAllBundlers as t};
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{c as e}from"./fs-CPnWm9CR.mjs";import{join as t}from"node:path";const n=[[`vite`,[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]],[`next`,[`next.config.js`,`next.config.ts`,`next.config.mjs`]],[`webpack`,[`webpack.config.js`,`webpack.config.ts`]],[`turbo`,[`turbo.json`]],[`rollup`,[`rollup.config.js`,`rollup.config.ts`,`rollup.config.mjs`]]];async function detectBundler(r){for(let[i,a]of n)for(let n of a){let a=t(r,n);if(await e(a))return{type:i,configFile:a}}return{type:null,configFile:null}}async function detectAllBundlers(r){let i=n.flatMap(([n,i])=>i.map(async i=>({type:n,configFile:t(r,i),found:await e(t(r,i))}))),a=await Promise.all(i),o=/* @__PURE__ */ new Set,s=[];for(let{type:e,configFile:t,found:n}of a)n&&!o.has(e)&&(o.add(e),s.push({type:e,configFile:t}));return s}export{detectBundler as n,detectAllBundlers as t};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t,t as n}from"./console-CIiXr7ge.mjs";import{t as r}from"./preflight-MzNjLXiy.mjs";import{n as i,t as a}from"./output-BxR2v-jn.mjs";import{resolve as o}from"node:path";var s=e({meta:{name:`check`,description:`Validate package configuration (exports, types, entry points)`},args:{dir:{type:`positional`,description:`Package directory (default: current directory)`,required:!1}},async run({args:e}){i();let s=o(e.dir||`.`),c=await r(s);if(c.length===0){n.success(`All pre-flight checks passed`),a({issues:[],passed:!0});return}let l=c.filter(e=>e.severity===`error`),u=c.filter(e=>e.severity===`warn`);n.info(`Found ${c.length} issue(s):\n`);for(let e of l)n.log(` ${t.red(`ERROR`)} ${t.dim(`[${e.code}]`)} ${e.message}`);for(let e of u)n.log(` ${t.yellow(`WARN`)} ${t.dim(`[${e.code}]`)} ${e.message}`);l.length>0?n.error(`\n${l.length} error(s), ${u.length} warning(s)`):n.warn(`\n${u.length} warning(s)`),a({issues:c,passed:l.length===0})}});export{s as default};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{t}from"./console-CIiXr7ge.mjs";import{c as n,l as r,r as i}from"./tracker-B3Fqx94J.mjs";import{a,r as o,s}from"./store-DjPdOKqg.mjs";import{D as c,E as l,a as u,c as d,f}from"./fs-CPnWm9CR.mjs";import{t as p}from"./format-DRqD29u-.mjs";import{i as m,n as h}from"./logger-9C6B9Na8.mjs";import{r as g}from"./dry-run-BkdMYSIx.mjs";import{n as _,t as v}from"./output-BxR2v-jn.mjs";import{t as y}from"./timer-DqgB175x.mjs";import{readdir as b}from"node:fs/promises";import{join as x}from"node:path";const S=3e5;var C=e({meta:{name:`clean`,description:`Remove unreferenced store entries and stale consumer registrations`},args:{yes:{type:`boolean`,alias:`y`,description:`Skip confirmation prompts`,default:!1}},async run({args:e}){_();let C=new y;t.start(`Checking consumer registrations...`);let{removedConsumers:w,removedPackages:T}=await i();w>0&&t.success(`Removed ${w} stale consumer registration(s) across ${T} package(s)`);let E=await r(),D=/* @__PURE__ */ new Set,O=[...new Set(Object.values(E).flat())],k=await Promise.all(O.map(async e=>{let{state:t,reliable:r}=await n(e);return{path:e,state:t,reliable:r}}));for(let{state:e,reliable:t}of k)if(t)for(let[t,n]of Object.entries(e.links))D.add(`${t}@${n.version}`);let A=/* @__PURE__ */ new Set,j=k.filter(e=>!e.reliable);if(j.length>0){t.warn(`${j.length} consumer(s) have corrupt state; their store entries will be preserved`);let e=new Set(j.map(e=>c(e.path)));for(let[t,n]of Object.entries(E))n.some(t=>e.has(t))&&A.add(t);m(`[clean] Protected packages (corrupt state): ${[...A].join(`, `)}`)}m(`[clean] Referenced entries: ${[...D].join(`, `)||`(none)`}`);let M=await o(),N=[];for(let e of M){let t=`${e.name}@${e.version}`;if(!D.has(t)){if(A.has(e.name)){m(`[clean] Preserving ${t} (consumer state unreadable)`);continue}let n=Date.now()-new Date(e.meta.publishedAt).getTime();if(n<S){m(`[clean] Skipping recently published entry: ${t} (${Math.round(n/1e3)}s old)`);continue}N.push(e)}}let P=[],F=l();if(await d(F)){let e=await b(F,{withFileTypes:!0});for(let t of e){let e=t.isDirectory()?a(t.name):null;if(e===null)continue;let n=Date.now()-e;n<S?m(`[clean] Skipping recent temp directory: ${t.name} (${Math.round(n/1e3)}s old)`):P.push(t.name)}}if(N.length+P.length>0&&!e.yes){let e=[];N.length>0&&e.push(`${N.length} unreferenced store entry(ies)`),P.length>0&&e.push(`${P.length} orphaned temp directory(ies)`);let n=await t.prompt(`Remove ${e.join(` and `)}?`,{type:`confirm`});if(!n||typeof n==`symbol`){t.info(`Cancelled`);return}}let I=0,L=await Promise.all(N.map(e=>u(e.packageDir))),R=await Promise.all(P.map(e=>u(x(F,e)))),z=0;for(let[e,t]of N.entries())m(`[clean] Removing unreferenced store entry: ${t.name}@${t.version}`),await s(t.name,t.version),I+=L[e]??0,z++;z>0&&t.success(`Removed ${z} unreferenced store entry(ies)`);let B=0;for(let[e,t]of P.entries())m(`[clean] Removing orphaned directory: ${t}`),await f(x(F,t)),I+=R[e]??0,B++;B>0&&t.success(`Removed ${B} orphaned temp directory(ies)`),w===0&&z===0&&B===0&&t.info(`Store is clean; no stale entries or registrations found`);let V=I>0?` (reclaimed ${p(I)})`:``;t.info(`Clean complete in ${C.elapsed()}${V}`),v({removedConsumers:w,removedPackages:T,removedEntries:z,removedOrphans:B,reclaimedBytes:I,elapsed:C.elapsedMs()}),h()&&g()}});export{C as default};
package/dist/cli.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
- import{r as e}from"./rolldown-runtime-BZbIAPMk.mjs";import{n as t,t as n}from"./dist-CFkjiIqD.mjs";import{t as r}from"./logger-DlikgOlh.mjs";import{n as i,t as a}from"./console-X31Y_QS5.mjs";import{availableParallelism as o}from"node:os";var s=/* @__PURE__ */ e(i(),1);function showBanner(){console.log(s.default.yellow(`
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{n as e,t}from"./dist-CFkjiIqD.mjs";import{t as n}from"./logger-9C6B9Na8.mjs";import{n as r,t as i}from"./console-CIiXr7ge.mjs";import{availableParallelism as a}from"node:os";function showBanner(){console.log(r.yellow(`
4
4
  _ __
5
5
  | |/ /_ __ __ _ _ __ _ __
6
6
  | ' /| '_ \\ / _\` | '__| '__|
7
7
  | . \\| | | | (_| | | | |
8
8
  |_|\\_\\_| |_|\\__,_|_| |_|
9
- `)),console.log(s.default.cyan(` Local npm package development without symlinks`)),console.log(s.default.dim(` Copies built files into consumer node_modules with incremental sync
10
- `))}process.env.UV_THREADPOOL_SIZE??=String(Math.max(o(),8)),r();const c=process.argv.slice(2),l=[`init`,`publish`,`add`,`use`,`remove`,`push`,`dev`,`restore`,`list`,`status`,`update`,`clean`,`gc`,`doctor`,`explain`,`migrate`,`reset`,`rollback`,`check`],u=c.some(e=>!e.startsWith(`-`)&&l.includes(e)),d=c.includes(`--help`)||c.includes(`-h`)||c.includes(`--version`);if(!u&&!d&&process.stdin.isTTY){showBanner();let e=await showInteractiveMenu();e&&process.argv.splice(2,0,e)}else u||showBanner();async function showInteractiveMenu(){try{let{readConsumerStateSafe:e}=await import(`./tracker-DXSo5wXO.mjs`),{resolve:t}=await import(`node:path`),{state:n}=await e(t(`.`)),r=Object.keys(n.links).length;r>0&&a.info(`${r} package(s) linked in this project`)}catch{}return await a.prompt(`What would you like to do?`,{type:`select`,options:[{label:`init - Set up knarr in this project`,value:`init`},{label:`publish - Publish package to the knarr store`,value:`publish`},{label:`add - Link a package from the store`,value:`add`},{label:`use - Link a local package path`,value:`use`},{label:`push - Publish and push to all consumers`,value:`push`},{label:`dev - Watch, rebuild, and push continuously`,value:`dev`},{label:`list - Show linked packages`,value:`list`},{label:`status - Show project status`,value:`status`},{label:`explain - Explain linked package state`,value:`explain`},{label:`help - Show help`,value:`--help`}]})||null}const f=n({meta:{name:`knarr`,version:`0.2.0`,description:`Local npm package development - copies built files into consumer node_modules`},args:{verbose:{type:`boolean`,alias:`v`,description:`Enable verbose debug logging`,default:!1},"dry-run":{type:`boolean`,description:`Preview changes without writing files`,default:!1},json:{type:`boolean`,description:`Output machine-readable JSON`,default:!1}},subCommands:{init:()=>import(`./init-Dwf-EIG3.mjs`).then(e=>e.default),publish:()=>import(`./publish-BLk5_qx1.mjs`).then(e=>e.default),add:()=>import(`./add-Clbi3vJ2.mjs`).then(e=>e.default),use:()=>import(`./use-BSCV4IQ5.mjs`).then(e=>e.default),remove:()=>import(`./remove-Bz9dNgDM.mjs`).then(e=>e.default),push:()=>import(`./push-C6UFcNGO.mjs`).then(e=>e.default),dev:()=>import(`./dev-DeOwxr_7.mjs`).then(e=>e.default),restore:()=>import(`./restore-CIBe2F1d.mjs`).then(e=>e.default),list:()=>import(`./list-DcREV9JM.mjs`).then(e=>e.default),status:()=>import(`./status-Dy-e_RtI.mjs`).then(e=>e.default),explain:()=>import(`./explain-BBv3U-D3.mjs`).then(e=>e.default),update:()=>import(`./update-Dacjzw4f.mjs`).then(e=>e.default),clean:()=>import(`./clean-DHh6fpmR.mjs`).then(e=>e.default),gc:()=>import(`./clean-DHh6fpmR.mjs`).then(e=>e.default),doctor:()=>import(`./doctor-XEdsr84Q.mjs`).then(e=>e.default),migrate:()=>import(`./migrate-DW5KQeDq.mjs`).then(e=>e.default),reset:()=>import(`./reset--AuvAPTc.mjs`).then(e=>e.default),rollback:()=>import(`./rollback-CFLIncnW.mjs`).then(e=>e.default),check:()=>import(`./check-Boh8WU_W.mjs`).then(e=>e.default)}});t(f);export{};
9
+ `)),console.log(r.cyan(` Local npm package development without symlinks`)),console.log(r.dim(` Copies built files into consumer node_modules with incremental sync
10
+ `))}process.env.UV_THREADPOOL_SIZE??=String(Math.max(a(),8)),n();const o=process.argv.slice(2),s=[`init`,`publish`,`add`,`use`,`remove`,`push`,`dev`,`restore`,`list`,`status`,`update`,`clean`,`gc`,`doctor`,`explain`,`migrate`,`reset`,`rollback`,`check`],c=o.some(e=>!e.startsWith(`-`)&&s.includes(e)),l=o.includes(`--help`)||o.includes(`-h`)||o.includes(`--version`);if(!c&&!l&&process.stdin.isTTY){showBanner();let e=await showInteractiveMenu();e&&process.argv.splice(2,0,e)}else c||showBanner();async function showInteractiveMenu(){try{let{readConsumerStateSafe:e}=await import(`./tracker-89eW0ArT.mjs`),{resolve:t}=await import(`node:path`),{state:n}=await e(t(`.`)),r=Object.keys(n.links).length;r>0&&i.info(`${r} package(s) linked in this project`)}catch{}return await i.prompt(`What would you like to do?`,{type:`select`,options:[{label:`init - Set up knarr in this project`,value:`init`},{label:`publish - Publish package to the knarr store`,value:`publish`},{label:`add - Link a package from the store`,value:`add`},{label:`use - Link a local package path`,value:`use`},{label:`push - Publish and push to all consumers`,value:`push`},{label:`dev - Watch, rebuild, and push continuously`,value:`dev`},{label:`list - Show linked packages`,value:`list`},{label:`status - Show project status`,value:`status`},{label:`explain - Explain linked package state`,value:`explain`},{label:`help - Show help`,value:`--help`}]})||null}const u=t({meta:{name:`knarr`,version:`0.3.0`,description:`Local npm package development - copies built files into consumer node_modules`},args:{verbose:{type:`boolean`,alias:`v`,description:`Enable verbose debug logging`,default:!1},"dry-run":{type:`boolean`,description:`Preview changes without writing files`,default:!1},json:{type:`boolean`,description:`Output machine-readable JSON`,default:!1}},subCommands:{init:()=>import(`./init-TN84d5jM.mjs`).then(e=>e.default),publish:()=>import(`./publish-C7ZUvHkE.mjs`).then(e=>e.default),add:()=>import(`./add-B_xzUp5y.mjs`).then(e=>e.default),use:()=>import(`./use-CCx6J0mc.mjs`).then(e=>e.default),remove:()=>import(`./remove-DkOgVQMZ.mjs`).then(e=>e.default),push:()=>import(`./push-B5KrkILW.mjs`).then(e=>e.default),dev:()=>import(`./dev-kqgY9NjI.mjs`).then(e=>e.default),restore:()=>import(`./restore-Bx2V59SL.mjs`).then(e=>e.default),list:()=>import(`./list-9hWJjw19.mjs`).then(e=>e.default),status:()=>import(`./status-Rnvw6dG2.mjs`).then(e=>e.default),explain:()=>import(`./explain-9Y4SZHjC.mjs`).then(e=>e.default),update:()=>import(`./update-CAKFICZu.mjs`).then(e=>e.default),clean:()=>import(`./clean-CyDDqbBD.mjs`).then(e=>e.default),gc:()=>import(`./clean-CyDDqbBD.mjs`).then(e=>e.default),doctor:()=>import(`./doctor-D-S1P0UG.mjs`).then(e=>e.default),migrate:()=>import(`./migrate-Co4qcFt6.mjs`).then(e=>e.default),reset:()=>import(`./reset-ClGouUb5.mjs`).then(e=>e.default),rollback:()=>import(`./rollback-RPjHZWtG.mjs`).then(e=>e.default),check:()=>import(`./check-CbVdpTsw.mjs`).then(e=>e.default)}});e(u);export{};
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
- import"./rolldown-runtime-BZbIAPMk.mjs";import{i as e}from"./logger-DlikgOlh.mjs";import{t}from"./fs-Cf1JTFyh.mjs";import{i as n,n as r,o as i}from"./json-CWzEb9Rt.mjs";import{readFile as a}from"node:fs/promises";import{join as o}from"node:path";function finiteNumber(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}async function loadKnarrConfig(t){try{let r=await a(o(t,`package.json`),`utf-8`),s=n(i(r,`package.json`),`knarr`);if(!s)return{};let c={};typeof s.buildCmd==`string`&&(c.buildCmd=s.buildCmd);let l=s.watchPatterns;Array.isArray(l)&&(c.watchPatterns=l.filter(e=>typeof e==`string`));let u=finiteNumber(s.debounce);u!==void 0&&(c.debounce=u);let d=finiteNumber(s.cooldown);d!==void 0&&(c.cooldown=d);let f=finiteNumber(s.historyLimit);return f!==void 0&&(c.historyLimit=Math.max(0,Math.floor(f))),typeof s.notify==`boolean`&&(c.notify=s.notify),e(`[config] Loaded knarr config from package.json: ${JSON.stringify(c)}`),c}catch{return{}}}async function setKnarrBuildCmdIfMissing(e,o){if(!o)return!1;let s=await a(e,`utf-8`),c=i(s,e),l=n(c,`knarr`);return l&&typeof l.buildCmd==`string`?!1:(c.knarr={...l,buildCmd:o},await t(e,JSON.stringify(c,null,r(s))+`
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{i as e}from"./logger-9C6B9Na8.mjs";import{t}from"./fs-CPnWm9CR.mjs";import{i as n,n as r,s as i}from"./json-DbSkpxtr.mjs";import{readFile as a}from"node:fs/promises";import{join as o}from"node:path";function finiteNumber(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}async function loadKnarrConfig(t){try{let r=await a(o(t,`package.json`),`utf-8`),s=n(i(r,`package.json`),`knarr`);if(!s)return{};let c={};typeof s.buildCmd==`string`&&(c.buildCmd=s.buildCmd);let l=s.watchPatterns;Array.isArray(l)&&(c.watchPatterns=l.filter(e=>typeof e==`string`));let u=finiteNumber(s.debounce);u!==void 0&&(c.debounce=u);let d=finiteNumber(s.cooldown);d!==void 0&&(c.cooldown=d);let f=finiteNumber(s.historyLimit);return f!==void 0&&(c.historyLimit=Math.max(0,Math.floor(f))),typeof s.notify==`boolean`&&(c.notify=s.notify),e(`[config] Loaded knarr config from package.json: ${JSON.stringify(c)}`),c}catch{return{}}}async function setKnarrBuildCmdIfMissing(e,o){if(!o)return!1;let s=await a(e,`utf-8`),c=i(s,e),l=n(c,`knarr`);return l&&typeof l.buildCmd==`string`?!1:(c.knarr={...l,buildCmd:o},await t(e,JSON.stringify(c,null,r(s))+`
4
4
  `),!0)}export{setKnarrBuildCmdIfMissing as n,loadKnarrConfig as t};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{styleText as e}from"node:util";import{createInterface as t}from"node:readline/promises";import{stdin as n,stdout as r}from"node:process";function style(t){return n=>e(t,String(n))}const i={bold:style(`bold`),dim:style(`dim`),cyan:style(`cyan`),green:style(`green`),red:style(`red`),yellow:style(`yellow`)};let a=3;async function prompt(e,a){if(!n.isTTY)return answerNonInteractive(e,a);let o=t({input:n,output:r});try{if(a.type===`confirm`){let t=a.initial===!1?`y/N`:`Y/n`,n=(await o.question(`${i.cyan(`?`)} ${e} ${i.dim(`(${t})`)} `)).trim().toLowerCase();return n===``?a.initial!==!1:n===`y`||n===`yes`}if(a.type===`text`){let t=a.default?i.dim(` (${a.default})`):``;return(await o.question(`${i.cyan(`?`)} ${e}${t} `)).trim()||a.default||``}console.log(`${i.cyan(`?`)} ${e}`);for(let[e,t]of a.options.entries())console.log(` ${i.cyan(`${e+1}.`)} ${t.label}`);let t=await o.question(`${i.dim(`Enter number:`)} `),n=a.options[parseInt(t,10)-1]??a.options[0];if(!n)throw Error(`No options to choose from for "${e}"`);return n.value}finally{o.close()}}function answerNonInteractive(e,t){if(t.type===`confirm`&&t.initial!==void 0)return console.error(`${i.cyan(`i`)} ${e} ${i.dim(`-> ${t.initial?`yes`:`no`} (no interactive terminal, using default)`)}`),t.initial;if(t.type===`text`)return t.default??``;console.error(`${i.red(`x`)} Cannot ask "${e}": no interactive terminal (stdin is not a TTY).`),console.error(`${i.cyan(`i`)} ${i.dim(`Suggestion:`)} ${t.type===`confirm`?`Re-run with --yes to confirm.`:t.nonInteractiveHint??`Pass the choice as a flag (see --help).`}`),process.exit(1)}const o={get level(){return a},set level(e){a=e},info(e,...t){a>=3&&console.log(i.cyan(`i`),e,...t)},success(e,...t){a>=3&&console.log(i.green(`OK`),e,...t)},warn(e,...t){a>=2&&console.warn(i.yellow(`!`),e,...t)},error(e,...t){a>=1&&console.error(i.red(`x`),e,...t)},start(e,...t){a>=3&&console.log(i.cyan(`...`),e,...t)},debug(e,...t){a>=4&&console.debug(i.dim(`D`),e,...t)},log(e,...t){a>=3&&console.log(e,...t)},prompt};export{i as n,o as t};
@@ -1,6 +1,23 @@
1
- import pc from "picocolors";
1
+ import { styleText } from "node:util";
2
2
  import { createInterface } from "node:readline/promises";
3
3
  import { stdin, stdout } from "node:process";
4
+ // src/utils/colors.ts
5
+ /**
6
+ * Terminal colors via Node's built-in `util.styleText` (stable since 22.13).
7
+ * It checks the output stream and honours NO_COLOR, NODE_DISABLE_COLORS and
8
+ * FORCE_COLOR, so piped or CI output stays plain unless FORCE_COLOR is set.
9
+ */
10
+ function style(format) {
11
+ return (text) => styleText(format, String(text));
12
+ }
13
+ const pc = {
14
+ bold: style("bold"),
15
+ dim: style("dim"),
16
+ cyan: style("cyan"),
17
+ green: style("green"),
18
+ red: style("red"),
19
+ yellow: style("yellow")
20
+ };
4
21
  // src/utils/console.ts
5
22
  /** Logging level: -1=silent, 0=fatal, 1=error, 2=warn, 3=info, 4=debug */
6
23
  let _level = 3;
@@ -78,4 +95,4 @@ const consola = {
78
95
  },
79
96
  prompt
80
97
  };
81
- export { consola as t };
98
+ export { pc as n, consola as t };
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
- import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t}from"./output-BxyRer_F.mjs";import{a as n,i as r,o as i,s as a,t as o}from"./push-engine-D3rfg2Tj.mjs";import{t as s}from"./batch-push-pVkjhRbp.mjs";import{t as c}from"./config-CQpgsGyL.mjs";import{n as l}from"./logger-DlikgOlh.mjs";import{r as u}from"./dry-run-BxVjpNqJ.mjs";import{resolve as d}from"node:path";var f=e({meta:{name:`dev`,description:`Watch, rebuild, and push to all consumers. Auto-detects build command.`},args:{all:{type:`boolean`,description:`Watch all workspace packages in dependency order`,default:!1},build:{type:`string`,description:`Override build command (default: auto-detect from package.json)`},"skip-build":{type:`boolean`,description:`Watch output dirs directly, skip build command detection`,default:!1},debounce:{type:`string`,description:`Debounce delay in ms (default: 500)`},cooldown:{type:`string`,description:`Minimum time between builds in ms (default: 500)`},"no-scripts":{type:`boolean`,description:`Skip prepack/postpack lifecycle hooks`,default:!1},force:{type:`boolean`,alias:`f`,description:`Force copy all files, bypassing hash comparison`,default:!1},notify:{type:`boolean`,description:`Ring terminal bell on push completion`,default:!1},"no-cascade":{type:`boolean`,description:`Disable cascading rebuilds in --all mode`,default:!1}},async run({args:e}){t();let f=d(`.`),p=await c(f),m={runScripts:!e[`no-scripts`],force:e.force,historyLimit:p.historyLimit};if(e.all){let t=await n(f,e),r=/* @__PURE__ */ new Set([...t.failedPackages,...t.skippedPackages]);if(t.canPush&&await s(f,{...m,skipPackages:r}),l()){u();return}await i(f,e,m)}else{let push=()=>o(f,m);if(await r(f,e,p)&&await push(),l()){u();return}await a(f,e,push)}}});export{f as default};
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t}from"./output-BxR2v-jn.mjs";import{a as n,i as r,o as i,s as a,t as o}from"./push-engine-BpNr8qXR.mjs";import{t as s}from"./batch-push-DXtZxRx0.mjs";import{t as c}from"./config-BJsL6NqN.mjs";import{n as l}from"./logger-9C6B9Na8.mjs";import{r as u}from"./dry-run-BkdMYSIx.mjs";import{resolve as d}from"node:path";var f=e({meta:{name:`dev`,description:`Watch, rebuild, and push to all consumers. Auto-detects build command.`},args:{all:{type:`boolean`,description:`Watch all workspace packages in dependency order`,default:!1},build:{type:`string`,description:`Override build command (default: auto-detect from package.json)`},"skip-build":{type:`boolean`,description:`Watch output dirs directly, skip build command detection`,default:!1},debounce:{type:`string`,description:`Debounce delay in ms (default: 500)`},cooldown:{type:`string`,description:`Minimum time between builds in ms (default: 500)`},"no-scripts":{type:`boolean`,description:`Skip prepack/postpack lifecycle hooks`,default:!1},force:{type:`boolean`,alias:`f`,description:`Force copy all files, bypassing hash comparison`,default:!1},notify:{type:`boolean`,description:`Ring terminal bell on push completion`,default:!1},"no-cascade":{type:`boolean`,description:`Disable cascading rebuilds in --all mode`,default:!1}},async run({args:e}){t();let f=d(`.`),p=await c(f),m={runScripts:!e[`no-scripts`],force:e.force,historyLimit:p.historyLimit};if(e.all){let t=await n(f,e),r=/* @__PURE__ */ new Set([...t.failedPackages,...t.skippedPackages]);if(t.canPush&&await s(f,{...m,skipPackages:r}),l()){u();return}await i(f,e,m)}else{let push=()=>o(f,m);if(await r(f,e,p)&&await push(),l()){u();return}await a(f,e,push)}}});export{f as default};
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t,t as n}from"./console-CIiXr7ge.mjs";import{c as r,i,m as a,r as o,u as s}from"./tracker-B3Fqx94J.mjs";import{n as c,r as l}from"./store-DjPdOKqg.mjs";import{o as u}from"./injector-nt40JxVt.mjs";import{E as d,_ as f,c as p,u as m,v as h,y as g}from"./fs-CPnWm9CR.mjs";import{t as _}from"./package-manager-DJ8CE0zL.mjs";import{n as v}from"./bundler-detect-Dq-QAbQj.mjs";import{a as y,c as b,d as x,l as S,o as C,u as w}from"./init-helpers-CYYWQm-P.mjs";import{n as T,t as E}from"./output-BxR2v-jn.mjs";import{n as D,r as O}from"./logger-9C6B9Na8.mjs";import{r as k}from"./dry-run-BkdMYSIx.mjs";import{c as A,i as j,l as M}from"./json-DbSkpxtr.mjs";import{readFile as N,stat as P}from"node:fs/promises";import{basename as F,join as I,resolve as L}from"node:path";async function runDoctorDiagnostics(e,t={}){let n=[],m=D(),w=t.fix===!0,T=m?`Would `:``;async function addCheck(e,t){let r={fixable:!1,fixed:!1,fixes:[],...e};if(w&&r.fixable&&t){let e=await t();e&&(r.fixed=!m,r.fixes.push(`${T}${e}`))}n.push(r)}let E=(await _(e)).resolve(),O=E.packageManager,k=!!E.nodeModulesCompatible,N="Yarn PnP has no node_modules tree for Knarr to manage. Set `nodeLinker: node-modules` or `nodeLinker: pnpm`, run `yarn install`, then re-run `knarr doctor --fix`.",P=d();await p(P)?await addCheck({name:`Store directory`,status:`pass`,message:`${(await l()).length} entries in ${P}`}):await addCheck({name:`Store directory`,status:`warn`,message:`Store not found at ${P}. Run 'knarr publish' to create it.`});let L=g(),{registry:R,reliable:z}=await s();if(!z)await addCheck({name:`Global registry`,status:`fail`,message:`${L} is corrupt or unreadable.`,unfixableReason:i()});else if(await p(L)){let e=Object.values(R).flat().length;await addCheck({name:`Global registry`,status:`pass`,message:`${Object.keys(R).length} packages, ${e} consumer registrations`})}else await addCheck({name:`Global registry`,status:`warn`,message:`No consumers registered yet. Use 'knarr add' to link packages.`});let B=await findStaleRegistryEntries(R),V=B.missingDirectories+B.missingLinks;V>0&&await addCheck({name:`Stale registry entries`,status:`warn`,message:`${V} stale consumer registration(s) found`+(B.unreadableConsumers>0?`; ${B.unreadableConsumers} unreadable state file(s) skipped`:``),fixable:!0},async()=>`remove ${(await o({removeMissingLinks:!0})).removedConsumers} stale consumer registration(s)`);let H=h(e),U=f(e),W=await pathKind(U),G=await p(H),{state:K,reliable:q}=await r(e);if(W===`file`)await addCheck({name:`Consumer state`,status:`fail`,message:`${U} exists but is not a directory.`,unfixableReason:`Move or delete ${U}, then run 'knarr init'.`}),q=!1;else if(G)q||await addCheck({name:`Consumer state`,status:`fail`,message:`state.json is corrupt or unreadable. Delete .knarr/state.json and re-run 'knarr add' for each package.`,unfixableReason:`Corrupt state may contain links Knarr cannot safely reconstruct.`});else{let t={name:`Consumer state`,status:`warn`,message:`No .knarr/state.json found.`,fixable:k,fixed:!1,fixes:[],...k?{}:{unfixableReason:N}};w&&t.fixable&&(await a(e,e=>{e.packageManager=O,e.role=`consumer`}),t.fixed=!m,t.fixes.push(`${T}create .knarr/state.json`),G=await p(H),{state:K,reliable:q}=await r(e)),n.push(t)}let J=q?Object.entries(K.links):[];q&&G&&(J.length>0?await addCheck({name:`Consumer state`,status:`pass`,message:`${J.length} linked package(s)`}):await addCheck({name:`Consumer state`,status:`warn`,message:`No packages linked. Use 'knarr add' to link a package.`}));for(let[t,n]of J){let r=await c(t,n.version);r?r.meta.contentHash===n.contentHash?await addCheck({name:`Store: ${t}`,status:`pass`,message:`${t}@${n.version} in sync`}):await addCheck({name:`Store: ${t}`,status:`warn`,message:`Store has newer content. Run 'knarr update' to sync.`}):await addCheck({name:`Store: ${t}`,status:`fail`,message:`Store entry missing for ${t}@${n.version}. Re-publish it.`});let i;try{i=await u(e,t,n.packageManager,n.version,{warnOnFallback:!1})}catch(e){await addCheck({name:`node_modules: ${t}`,status:`fail`,message:`Cannot resolve package target. ${e instanceof Error?e.message:String(e)}`});continue}if(!await p(i))await addCheck({name:`node_modules: ${t}`,status:`fail`,message:`Missing from node_modules. Run 'knarr restore'.`});else try{let e=await A(I(i,`package.json`)),r=M(e,`name`),a=M(e,`version`);r&&r!==t?await addCheck({name:`node_modules: ${t}`,status:`fail`,message:`node_modules target contains package "${r}". Run your package manager install, then 'knarr restore'.`}):a&&a!==n.version?await addCheck({name:`node_modules: ${t}`,status:`warn`,message:`node_modules has v${a} but Knarr linked v${n.version}. Run 'knarr restore'.`}):await addCheck({name:`node_modules: ${t}`,status:`pass`,message:`present`})}catch{await addCheck({name:`node_modules: ${t}`,status:`pass`,message:`present`})}}await addCheck({name:`Package manager`,status:`pass`,message:O}),E.yarnLinkerDiagnostic&&await addCheck({name:`Yarn linker`,...E.yarnLinkerDiagnostic});let Y=await v(e);if(Y.type?await addCheck({name:`Bundler`,status:`pass`,message:`${Y.type}${Y.configFile?` (${Y.configFile})`:``}`}):await addCheck({name:`Bundler`,status:`warn`,message:`No bundler config detected`}),Y.type===`vite`&&Y.configFile){let{addKnarrVitePlugin:e,hasKnarrVitePlugin:t}=await import(`./vite-config-BRlYc4ni.mjs`),r=await t(Y.configFile);if(r.error)await addCheck({name:`Vite integration`,status:`warn`,message:r.error});else if(r.configured)await addCheck({name:`Vite integration`,status:`pass`,message:`Knarr plugin configured`});else{let t={name:`Vite integration`,status:`warn`,message:`Knarr Vite plugin is missing.`,fixable:k,fixed:!1,fixes:[],...k?{}:{unfixableReason:N}};if(w&&t.fixable){let n=await e(Y.configFile);n.modified?(t.fixed=!m,t.fixes.push(`${T}add Knarr Vite plugin to ${F(Y.configFile)}`)):n.error&&(t.unfixableReason=n.error)}n.push(t)}}if(Y.type===`next`&&Y.configFile){let{addToTranspilePackages:e,hasTranspilePackage:t}=await import(`./nextjs-config-BQgTWZ96.mjs`);for(let[r]of J){let i=await t(Y.configFile,r);if(i.configured){await addCheck({name:`Next.js integration: ${r}`,status:`pass`,message:`transpilePackages configured`});continue}let a={name:`Next.js integration: ${r}`,status:`warn`,message:`${r} is missing from transpilePackages.`,fixable:!i.error&&k,fixed:!1,fixes:[],...i.error?{unfixableReason:i.error}:k?{}:{unfixableReason:N}};if(w&&a.fixable){let t=await e(Y.configFile,r);t.modified?(a.fixed=!m,a.fixes.push(`${T}add ${r} to transpilePackages in ${F(Y.configFile)}`)):t.error&&(a.unfixableReason=t.error)}n.push(a)}}let X=I(e,`.gitignore`);await gitignoreIncludesKnarr(X)?await addCheck({name:`.gitignore`,status:`pass`,message:`.knarr/ is ignored`}):await addCheck({name:`.gitignore`,status:`warn`,message:`.knarr/ not in .gitignore.`,fixable:k,...k?{}:{unfixableReason:N}},async()=>await y(X)?`add .knarr/ to .gitignore`:null);let Z=I(e,`package.json`);if(await p(Z)){let t=await readJsonFile(Z),n=t?j(t,`scripts`)?.postinstall:void 0;typeof n==`string`&&S(n)?await p(I(e,`.knarr`,`restore.cjs`))?await addCheck({name:`Postinstall restore`,status:`pass`,message:`postinstall re-applies links via .knarr/restore.cjs`}):await addCheck({name:`Postinstall restore`,status:`warn`,message:`.knarr/restore.cjs is missing, so installs won't re-apply links.`,fixable:k,...k?{}:{unfixableReason:N}},async()=>(await x(e),`write .knarr/restore.cjs`)):typeof n==`string`&&b(n)?await canVerifyKnarrForPostinstall(e,t,n)?await addCheck({name:`Postinstall restore`,status:`pass`,message:`postinstall runs knarr restore`}):n.includes(`knarr restore --silent || node -e "process.exit(0)"`)?await addCheck({name:`Postinstall restore`,status:`warn`,message:`postinstall runs knarr restore, but no local knarr dependency or binary was found, so installs silently drop links.`,fixable:k,...k?{}:{unfixableReason:N}},async()=>(await C(e),`upgrade postinstall restore hook (works without a global knarr)`)):await addCheck({name:`Postinstall restore`,status:`warn`,message:`postinstall runs knarr restore, but no local knarr dependency or binary was found.`,unfixableReason:`Install knarr as a devDependency for reliable auto-restore, or ensure a global knarr binary is available during installs.`}):typeof n==`string`?await addCheck({name:`Postinstall restore`,status:`warn`,message:`postinstall exists but does not run knarr restore.`,unfixableReason:`Existing postinstall scripts are not merged automatically.`}):await addCheck({name:`Postinstall restore`,status:`warn`,message:`postinstall restore hook is missing.`,fixable:k,...k?{}:{unfixableReason:N}},async()=>(await C(e),`add postinstall restore hook to package.json`))}else await addCheck({name:`Postinstall restore`,status:`warn`,message:`No package.json found.`});let[Q=0,$=0]=process.versions.node.split(`.`).map(e=>parseInt(e,10));return Q>22||Q===22&&$>=22?await addCheck({name:`Node.js version`,status:`pass`,message:`v${process.versions.node}`}):await addCheck({name:`Node.js version`,status:`fail`,message:`v${process.versions.node}; Knarr requires Node.js >= 22.22`}),{results:n,failures:n.filter(e=>e.status===`fail`).length,warnings:n.filter(e=>e.status===`warn`).length,fixed:n.filter(e=>e.fixed).length,plannedFixes:m?n.reduce((e,t)=>e+t.fixes.length,0):0,dryRun:m}}var R=e({meta:{name:`doctor`,description:`Run diagnostic checks on your Knarr setup`},args:{fix:{type:`boolean`,description:`Apply safe automatic repairs`,default:!1}},async run({args:e}){T();let r=L(`.`);n.info(e.fix?`Running Knarr diagnostics with safe fixes...
4
+ `:`Running Knarr diagnostics...
5
+ `);let i=await runDoctorDiagnostics(r,{fix:e.fix}),a={pass:t.green(`PASS`),fail:t.red(`FAIL`),warn:t.yellow(`WARN`)};for(let e of i.results){n.log(` ${a[e.status]} ${e.name}: ${t.dim(e.message)}`);for(let r of e.fixes)n.log(` ${t.cyan(D()?`PLAN`:`FIX`)} ${t.dim(r)}`);e.unfixableReason&&n.log(` ${t.yellow(`!`)} ${t.dim(e.unfixableReason)}`)}n.log(``),i.plannedFixes>0?n.info(`${i.plannedFixes} fix(es) would be applied`):i.fixed>0&&n.success(`Applied ${i.fixed} fix(es)`),i.failures>0?n.error(`${i.failures} issue(s) found that need attention`):i.warnings>0?n.warn(`${i.warnings} warning(s), but no critical issues`):n.success(`All checks passed!`),E(i),e.fix&&D()&&!O()&&k()}});async function findStaleRegistryEntries(e){let t=0,n=0,i=0;for(let[a,o]of Object.entries(e))for(let e of o){if(!await p(e)){t++;continue}let{state:o,reliable:s}=await r(e);s?o.links[a]||n++:i++}return{missingDirectories:t,missingLinks:n,unreadableConsumers:i}}async function gitignoreIncludesKnarr(e){try{return(await N(e,`utf-8`)).split(`
6
+ `).some(e=>{let t=e.trim();return t===`.knarr/`||t===`.knarr`||t===`/.knarr/`||t===`/.knarr`})}catch{return!1}}async function pathKind(e){try{return(await P(e)).isDirectory()?`dir`:`file`}catch(e){return m(e)&&e.code===`ENOENT`?`missing`:`file`}}async function canVerifyKnarrForPostinstall(e,t,n){return w(n)||declaresKnarrDependency(t)?!0:await p(I(e,`node_modules`,`.bin`,`knarr`))||await p(I(e,`node_modules`,`.bin`,`knarr.cmd`))}function declaresKnarrDependency(e){return e?[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`].some(t=>j(e,t)?.knarr!==void 0):!1}async function readJsonFile(e){try{return await A(e)}catch{return null}}export{R as default};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
- import"./rolldown-runtime-BZbIAPMk.mjs";import{r as e}from"./logger-DlikgOlh.mjs";import{t}from"./console-X31Y_QS5.mjs";import{homedir as n}from"node:os";import{isAbsolute as r,relative as i,sep as a}from"node:path";function displayMutationPath(e,t=process.cwd(),o=n()){let inside=t=>{let n=i(t,e);return n!==``&&!n.startsWith(`..`)&&!r(n)?n:n===``?`.`:null},s=inside(t);if(s!==null)return s;let c=inside(o);return c===null?e:c===`.`?`~`:`~${a}${c}`}const o=[];let s=!1;function recordMutation(e){o.push(e)}function getMutations(){return[...o]}function markDryRunJsonReportPrinted(){s=!0}function printDryRunReport(){if(o.length===0){t.info(`[dry-run] No mutations would be performed`);return}if(e()){if(s)return;console.log(JSON.stringify({dryRun:!0,mutations:o},null,2)),s=!0;return}let n=/* @__PURE__ */ new Map;for(let e of o){let t=n.get(e.type);t||(t=[],n.set(e.type,t)),t.push(e)}t.info(`\n[dry-run] ${o.length} mutation(s) would be performed:\n`);let r={copy:`Copy`,remove:`Remove`,move:`Move`,mkdir:`Create directory`,write:`Write file`,"bin-link":`Create bin link`,"bin-unlink":`Remove bin link`,"cache-invalidate":`Invalidate cache`,"lock-skip":`Skip lock`,"lifecycle-skip":`Skip lifecycle hook`,"command-skip":`Skip command`};for(let[e,i]of n){t.info(` ${r[e]} (${i.length}):`);for(let e of i.slice(0,20)){let n=e.dest?` → ${displayMutationPath(e.dest)}`:``,r=e.detail?` (${e.detail})`:``;t.info(` ${displayMutationPath(e.path)}${n}${r}`)}i.length>20&&t.info(` ... and ${i.length-20} more`)}}export{recordMutation as i,markDryRunJsonReportPrinted as n,printDryRunReport as r,getMutations as t};
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{r as e}from"./logger-9C6B9Na8.mjs";import{t}from"./console-CIiXr7ge.mjs";import{homedir as n}from"node:os";import{isAbsolute as r,relative as i,sep as a}from"node:path";function displayMutationPath(e,t=process.cwd(),o=n()){let inside=t=>{let n=i(t,e);return n!==``&&!n.startsWith(`..`)&&!r(n)?n:n===``?`.`:null},s=inside(t);if(s!==null)return s;let c=inside(o);return c===null?e:c===`.`?`~`:`~${a}${c}`}const o=[];let s=!1;function recordMutation(e){o.push(e)}function getMutations(){return[...o]}function markDryRunJsonReportPrinted(){s=!0}function printDryRunReport(){if(o.length===0){t.info(`[dry-run] No mutations would be performed`);return}if(e()){if(s)return;console.log(JSON.stringify({dryRun:!0,mutations:o},null,2)),s=!0;return}let n=/* @__PURE__ */ new Map;for(let e of o){let t=n.get(e.type);t||(t=[],n.set(e.type,t)),t.push(e)}t.info(`\n[dry-run] ${o.length} mutation(s) would be performed:\n`);let r={copy:`Copy`,remove:`Remove`,move:`Move`,mkdir:`Create directory`,write:`Write file`,"bin-link":`Create bin link`,"bin-unlink":`Remove bin link`,"cache-invalidate":`Invalidate cache`,"lock-skip":`Skip lock`,"lifecycle-skip":`Skip lifecycle hook`,"command-skip":`Skip command`};for(let[e,i]of n){t.info(` ${r[e]} (${i.length}):`);for(let e of i.slice(0,20)){let n=e.dest?` → ${displayMutationPath(e.dest)}`:``,r=e.detail?` (${e.detail})`:``;t.info(` ${displayMutationPath(e.path)}${n}${r}`)}i.length>20&&t.info(` ... and ${i.length-20} more`)}}export{recordMutation as i,markDryRunJsonReportPrinted as n,printDryRunReport as r,getMutations as t};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{n as e,t}from"./console-CIiXr7ge.mjs";const n=[{pattern:/not found in store/i,message:`Run 'knarr publish' in the package directory first, or use --from <path>.`},{pattern:/is not linked/i,message:`Run 'knarr add <package>' to link it first.`},{pattern:/No package\.json/i,message:`Make sure you're in a valid package directory with a package.json.`},{pattern:/missing 'name'/i,message:`Add a 'name' field to your package.json.`},{pattern:/missing 'version'/i,message:`Add a 'version' field to your package.json.`},{pattern:/store entry missing/i,message:`Re-publish the package with 'knarr publish'.`},{pattern:/EACCES|EPERM/i,message:`Permission denied. Try running with elevated privileges or check file ownership.`},{pattern:/ENOSPC/i,message:`Disk is full. Free up some space and try again.`},{pattern:/No publishable files/i,message:`Check the 'files' field in package.json, or ensure the build output exists.`},{pattern:/private.*package/i,message:`Use --private flag to publish private packages.`},{pattern:/Failed to read store entry/i,message:`The store may be corrupted. Try 'knarr clean' then re-publish.`},{pattern:/Failed to acquire lock/i,message:`Another Knarr process may be running. Wait or delete stale .lk directories.`},{pattern:/not a directory/i,message:`Check that the path exists and is a directory.`},{pattern:/timed out/i,message:`Set KNARR_HOOK_TIMEOUT to a higher value (in ms) if your scripts need more time.`},{pattern:/state.*corrupt|corrupt.*state/i,message:`Delete .knarr/state.json and re-run 'knarr add' for each package.`},{pattern:/EBUSY/i,message:`A file is locked by another process (e.g. dev server). Stop the process and retry.`},{pattern:/Invalid package name/i,message:`Package names must be non-empty. Use format: package-name or @scope/package-name.`}];function errorWithSuggestion(r){t.error(r);for(let{pattern:i,message:a}of n)if(i.test(r)){t.info(`${e.dim(`Suggestion:`)} ${a}`);break}}export{errorWithSuggestion as t};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t,t as n}from"./console-CIiXr7ge.mjs";import{n as r,t as i}from"./store-DjPdOKqg.mjs";import{o as a}from"./injector-nt40JxVt.mjs";import{c as o,l as s}from"./tracker-B3Fqx94J.mjs";import{t as c}from"./package-manager-DJ8CE0zL.mjs";import{D as l,c as u,g as d,x as f}from"./fs-CPnWm9CR.mjs";import{n as p,t as m}from"./output-BxR2v-jn.mjs";import{c as h,l as g}from"./json-DbSkpxtr.mjs";import{join as _,resolve as v}from"node:path";async function explainState(e,t){let{state:n,reliable:r}=await o(e),i=(await c(e)).resolve().packageManager;if(!r)return{consumerPath:e,stateReliable:!1,packages:t?[await explainPackage(e,t,null,i,!1)]:[]};let a=t?[[t,n.links[t]??null]]:Object.entries(n.links);return{consumerPath:e,stateReliable:!0,packages:await Promise.all(a.map(([t,n])=>explainPackage(e,t,n,i,!0)))}}var y=e({meta:{name:`explain`,description:`Explain linked package state and suggested recovery actions`},args:{package:{type:`positional`,description:`Package name to explain (default: all linked packages)`,required:!1}},async run({args:e}){p();let r=await explainState(v(`.`),e.package);if(!r.stateReliable)n.error(`Consumer state is corrupt or unreadable`),n.info(`Delete .knarr/state.json and re-run 'knarr add' for each package.`);else if(!r.packages[0])n.info(`No linked packages in this project`);else if(e.package)renderDetailed(r.packages[0]);else{n.info(`Linked packages (${r.packages.length}):\n`);for(let e of r.packages){let r=e.status===`ok`?t.green(`OK`):e.status===`warn`?t.yellow(`!`):t.red(`FAIL`),i=e.version?t.dim(`@${e.version}`):t.dim(`(not linked)`),a=e.buildId?t.dim(` [${e.buildId}]`):``;n.log(` ${r} ${t.cyan(e.name)} ${i}${a}`),n.log(` ${t.dim(e.summary)}`)}n.log(``),n.info(`Run ${t.cyan(`knarr explain <package>`)} for details.`)}m(r)}});async function explainPackage(e,t,n,c,p){let m=n?await r(t,n.version):await i(t),h=(await s())[t]??[],g=l(e),_=[];p||_.push(`consumer state is corrupt or unreadable`),n||_.push(`package is not linked in this project`);let v=n?.sourcePath??m?.meta.sourcePath??null,y=v?await u(v):null;v&&y===!1&&_.push(`source directory missing: ${v}`),m?n&&m.meta.contentHash!==n.contentHash&&_.push(`store has newer content than the current link`):_.push(n?`store entry missing for ${t}@${n.version}`:`package not found in store`);let b=f(e,t),x=n?await a(e,t,n.packageManager,n.version,{warnOnFallback:!1}):b,S=await u(x),C=S?await readPackageVersion(x):null;n&&!S?_.push(`package is missing from node_modules`):n&&C&&C!==n.version&&_.push(`node_modules has v${C} but link expects v${n.version}`);let w=n?d(e,t):null,T=w?await u(w):!1;n?.backupExists&&!T&&_.push(`backup is recorded but missing on disk`);let E=await Promise.all(h.map(async e=>{if(!await u(e))return{path:e,exists:!1,stateReliable:null,hasLink:null};let{state:n,reliable:r}=await o(e);return{path:e,exists:!0,stateReliable:r,hasLink:r?!!n.links[t]:null}}));return n&&!h.includes(g)&&_.push(`current project is not registered for pushes`),{name:t,status:_.some(e=>e.includes(`corrupt`)||e.includes(`missing from node_modules`)||e.includes(`store entry missing`)||e.includes(`not linked`))?`fail`:_.length>0?`warn`:`ok`,summary:summarize(t,n,_),suggestedAction:suggestAction(t,n,_,v),linked:!!n,version:n?.version??m?.version??null,buildId:n?.buildId||m?.meta.buildId||null,sourcePath:v,sourceExists:y,packageManager:n?.packageManager??c,store:{exists:!!m,path:m?.packageDir??null,contentHash:m?.meta.contentHash??null,matchesLink:n&&m?m.meta.contentHash===n.contentHash:null,publishedAt:m?.meta.publishedAt??null},nodeModules:{path:b,targetPath:x,exists:S,packageVersion:C},backup:{expected:n?.backupExists??!1,exists:T,path:w},consumers:E,issues:_}}function renderDetailed(e){let r=e.status===`ok`?t.green(`OK`):e.status===`warn`?t.yellow(`WARN`):t.red(`FAIL`);if(n.info(`${r} ${t.cyan(e.name)} ${t.dim(e.summary)}\n`),n.log(` Version: ${e.version??`(not linked)`}`),n.log(` Build ID: ${e.buildId??`(none)`}`),n.log(` Package manager: ${e.packageManager}`),n.log(` Source: ${e.sourcePath??`(unknown)`}${e.sourceExists===!1?` (missing)`:``}`),n.log(` Store: ${e.store.exists?e.store.path:`(missing)`}`),e.store.matchesLink!==null&&n.log(` Content hash: ${e.store.matchesLink?`matches link`:`differs from link`}`),n.log(` node_modules: ${e.nodeModules.targetPath}${e.nodeModules.exists?``:` (missing)`}`),n.log(` Backup: ${e.backup.expected?e.backup.exists?`present`:`missing`:`not recorded`}`),n.log(` Registered consumers: ${e.consumers.length}`),e.issues.length>0){n.log(``);for(let r of e.issues)n.log(` ${t.yellow(`!`)} ${r}`)}n.log(``),n.info(`Suggested action: ${e.suggestedAction}`)}function summarize(e,t,n){return t?n.length===0?`link, store, and node_modules are in sync`:n[0]??`link, store, and node_modules are in sync`:`${e} is not linked in this project`}function suggestAction(e,t,n,r){return n.some(e=>e.includes(`corrupt`))?`Delete .knarr/state.json and re-run 'knarr add' for each package.`:t?n.some(e=>e.includes(`store entry missing`))?r?`Run 'knarr publish' in ${r}, then 'knarr restore'.`:`Re-publish the package, then run 'knarr restore'.`:n.some(e=>e.includes(`newer content`))?`Run 'knarr update ${e}'.`:n.some(e=>e.includes(`node_modules`))?`Run 'knarr restore'.`:n.some(e=>e.includes(`not registered`))?`Run 'knarr add ${e}' again to refresh registration.`:n.some(e=>e.includes(`source directory`))?`Check the source path or re-run 'knarr use <path>'.`:`No action needed.`:`Run 'knarr add ${e}' or 'knarr use <path>'.`}async function readPackageVersion(e){try{let t=await h(_(e,`package.json`));return g(t,`version`)??null}catch{return null}}export{y as default};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
- export{c as exists}from"./fs-Cf1JTFyh.mjs";
3
+ export{c as exists}from"./fs-CPnWm9CR.mjs";
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import"./rolldown-runtime-BZbIAPMk.mjs";import{i as e,n as t}from"./logger-9C6B9Na8.mjs";import{t as n}from"./console-CIiXr7ge.mjs";import{a as r,s as i,u as a}from"./json-DbSkpxtr.mjs";import{i as o}from"./dry-run-BkdMYSIx.mjs";import{availableParallelism as s,homedir as c}from"node:os";import{constants as l,copyFile as u,cp as d,lstat as f,mkdir as p,readFile as m,readdir as h,realpath as g,rename as _,rm as v,stat as y,symlink as b,writeFile as x}from"node:fs/promises";import{dirname as S,isAbsolute as C,join as w,parse as T,relative as E,resolve as D}from"node:path";import{createHash as O,randomUUID as k}from"node:crypto";import{setTimeout as A}from"node:timers/promises";const j=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,M=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,N=/[\x00-\x1F\x7F]/;function validatePackageName(e){if(!e||e.length>214||N.test(e)||e.includes(`\\`)||e.includes(`//`)||e.split(`/`).some(e=>e===`.`||e===`..`)||!j.test(e))throw Error(`Invalid package name "${e}"`)}function validatePackageVersion(e){if(!e||N.test(e)||e.includes(`/`)||e.includes(`\\`)||e.includes(`..`)||!M.test(e))throw Error(`Invalid package version "${e}"`)}function validatePackageIdentity(e,t){validatePackageName(e),validatePackageVersion(t)}function isKnarrMeta(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.contentHash==`string`&&typeof t.publishedAt==`string`&&typeof t.sourcePath==`string`&&(t.buildId===void 0||typeof t.buildId==`string`)&&(t.schemaVersion===void 0||typeof t.schemaVersion==`number`)}function isLinkEntry(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.version==`string`&&typeof t.contentHash==`string`&&typeof t.linkedAt==`string`&&typeof t.sourcePath==`string`&&typeof t.backupExists==`boolean`&&typeof t.packageManager==`string`&&[`npm`,`pnpm`,`yarn`,`bun`].includes(t.packageManager)&&(t.buildId===void 0||typeof t.buildId==`string`)}function parseConsumerState(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.version!==`1`||typeof t.links!=`object`||t.links===null)return null;let n=r();for(let[e,r]of Object.entries(t.links)){if(!isLinkEntry(r))return null;n[e]=r}return{...t,links:n}}async function warnVersionMismatch(e,t,r){try{let o=await m(w(e,`package.json`),`utf-8`),s=i(o,`package.json`),c=a(s,`dependencies`)[t]??a(s,`devDependencies`)[t]??a(s,`peerDependencies`)[t];if(!c||/^(workspace:|catalog:|\*)/.test(c))return;let l=c.match(/(\d+)\.\d+\.\d+/);if(!l?.[1])return;parseInt(l[1],10)!==parseInt(r.split(`.`)[0]??``,10)&&n.warn(`Version mismatch: store has ${t}@${r} but your package.json declares "${c}". Consider updating your dependency range.`)}catch{}}function parseConsumersRegistry(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=r();for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||!r.every(e=>typeof e==`string`))return null;t[n]=r}return t}function assertInside(e,t,n){let r=D(e),i=D(t),a=E(r,i);if(a!==``&&(a.startsWith(`..`)||C(a)))throw Error(`${n} escapes expected directory: ${t}`)}function getKnarrHome(){return process.env.KNARR_HOME||w(c(),`.knarr`)}function getStorePath(){return w(getKnarrHome(),`store`)}function getConsumersPath(){return w(getKnarrHome(),`consumers.json`)}function encodePackageName(e){return validatePackageName(e),e.replace(/\//g,`+`)}function decodePackageName(e){if(e.startsWith(`@`)){let t=e.indexOf(`+`);if(t!==-1)return e.slice(0,t)+`/`+e.slice(t+1)}return e}function getStoreEntryPath(e,t){validatePackageIdentity(e,t);let n=getStorePath(),r=w(n,`${encodePackageName(e)}@${t}`);return assertInside(n,r,`Store entry path`),r}function getStorePackagePath(e,t){return w(getStoreEntryPath(e,t),`package`)}function getStoreMetaPath(e,t){return w(getStoreEntryPath(e,t),`.knarr-meta.json`)}function getStoreHistoryPath(e,t){return w(getStoreEntryPath(e,t),`history`)}function getHistoryEntryPath(e,t,n){if(!/^[a-f0-9]{8,64}$/i.test(n))throw Error(`Invalid build id "${n}"`);return w(getStoreHistoryPath(e,t),n)}function getConsumerKnarrDir(e){return w(e,`.knarr`)}function getConsumerStatePath(e){return w(e,`.knarr`,`state.json`)}function getConsumerBackupPath(e,t){validatePackageName(t);let n=w(e,`.knarr`,`backups`),r=w(n,encodePackageName(t));return assertInside(n,r,`Backup path`),r}function normalizePath(e){return e.replace(/\\/g,`/`)}function getNodeModulesPackagePath(e,t){validatePackageName(t);let n=w(e,`node_modules`),r=w(n,t);return assertInside(n,r,`node_modules package path`),r}function pLimit(e){let t=0,n=[],r=0,next=()=>{let i=t<e?n[r]:void 0;i&&(r++,t++,i()),r>0&&r===n.length&&(n.length=0,r=0)};return r=>new Promise((i,a)=>{let run=()=>{r().then(e=>{t--,i(e),next()},e=>{t--,a(e),next()})};t<e?(t++,run()):n.push(run)})}let P=null;function getXXHash(){return P||=import(`./xxhash-wasm-D_QjdUuv.mjs`).then(e=>e.default()).catch(e=>{throw P=null,e}),P}const F=pLimit(Math.max(s(),8));async function computeContentHash(t,n,r=/* @__PURE__ */ new Map){let i=new Map(t.map(e=>[normalizePath(E(n,e)),e]));for(let e of r.keys())i.has(e)||i.set(e,w(n,e));let a=[...i.entries()].sort(([e],[t])=>e.localeCompare(t)),o=await Promise.all(a.map(([e,t])=>F(async()=>{let n=r.get(e);return n===void 0?{rel:e,content:await m(t)}:{rel:e,content:Buffer.isBuffer(n)?n:Buffer.from(n)}})));e(`[hash] Computing content hash for ${a.length} files`);let s=O(`sha256`),c=Buffer.alloc(4);for(let{rel:e,content:t}of o)s.update(e),s.update(`\0`),c.writeUInt32LE(t.length),s.update(c),s.update(t);let l=`sha256v2:`+s.digest(`hex`);return e(`[hash] Result: ${l.slice(0,20)}...`),l}async function hashFile(e,t){let n=t??(await y(e)).size,r=await getXXHash();if(n>1048576)return hashFileStream(e,r);let i=await m(e);return r.h64Raw(i).toString(16)}async function hashFileStream(e,t){let{createReadStream:n}=await import(`node:fs`),r=t.create64();return new Promise((t,i)=>{let a=n(e);a.on(`data`,e=>r.update(e)),a.on(`end`,()=>t(r.digest().toString(16))),a.on(`error`,i)})}const I=pLimit(Math.max(s(),8));function isNodeError(e){return e instanceof Error&&`code`in e}const L=/* @__PURE__ */ new Map;function volumeRoot(e){let{root:t}=T(e);return t||`/`}async function copyWithCoW(n,r,i){if(t()){e(`[dry-run] would copy ${n} → ${r}`),o({type:`copy`,path:n,dest:r});return}i?.ensureParent!==!1&&await p(S(r),{recursive:!0});let a=`${r}${R}${process.pid}-${k()}`;try{await copyToFreshFile(n,a,volumeRoot(r)),await renameOverLockedTarget(a,r)}catch(e){throw await v(a,{force:!0}),e}}const R=`.knarr-tmp-`,z=/\.knarr-tmp-(\d+)-[0-9a-f-]{36}$/;function isInFlightCopyTemp(e){let t=z.exec(e)?.[1];if(t===void 0)return!1;try{return process.kill(Number(t),0),!0}catch(e){return isNodeError(e)&&e.code===`EPERM`}}const B=[10,20,40,80,160,300,400],V=/* @__PURE__ */ new Set([`EPERM`,`EACCES`,`EBUSY`]);async function renameOverLockedTarget(e,t){for(let n of B)try{await _(e,t);return}catch(e){if(process.platform!==`win32`||!isNodeError(e)||!V.has(e.code??``))throw e;await A(n)}await _(e,t)}async function copyToFreshFile(t,n,r){let i=L.get(r);if(i===!1)await u(t,n);else if(i===!0)await u(t,n,l.COPYFILE_FICLONE);else try{await u(t,n,l.COPYFILE_FICLONE_FORCE),L.set(r,!0)}catch{L.set(r,!1),e(`[copy] reflink not supported on ${r}, using plain copy`),await u(t,n)}}async function collectFiles(e){return(await h(e,{recursive:!0,withFileTypes:!0})).filter(e=>e.isFile()).map(e=>w(e.parentPath,e.name))}async function removeDestinationConflicts(e,n){let r=n.split(/[\\/]/).filter(Boolean),i=e;for(let[e,n]of r.entries()){i=w(i,n);try{let n=await y(i),a=e===r.length-1;if(n.isDirectory()){a&&(t()?o({type:`remove`,path:i}):await v(i,{recursive:!0,force:!0}));continue}if(!a){if(t()){o({type:`remove`,path:i});return}await v(i,{force:!0})}}catch(e){if(isNodeError(e)&&e.code===`ENOENT`)return;throw e}}}async function incrementalCopy(n,r,i={}){let a=collectFiles(n),s=collectFiles(r).catch(e=>{if(isNodeError(e)&&e.code===`ENOENT`)return[];throw e}),[c,l]=await Promise.all([a,s]),u=0,d=0,f=await Promise.all(c.map(t=>I(async()=>{let a=E(n,t),o=w(r,a),s=!0;if(i.force)e(`[copy] ${a} (forced)`);else try{let[n,r]=await Promise.all([y(t),y(o)]);if(n.size!==r.size)e(`[copy] ${a} (size differs: ${n.size} vs ${r.size})`);else{let[i,c]=await Promise.all([hashFile(t,n.size),hashFile(o,r.size)]);i===c?(s=!1,e(`[skip] ${a} (unchanged)`)):e(`[copy] ${a} (hash differs)`)}}catch(t){if(isNodeError(t)&&(t.code===`ENOENT`||t.code===`ENOTDIR`))e(`[copy] ${a} (new file)`);else throw t}return s?(await removeDestinationConflicts(r,a),await copyWithCoW(t,o),`copied`):`skipped`})));for(let e of f)e===`copied`?u++:d++;let p=new Set(c.map(e=>E(n,e))),m=l.filter(e=>!p.has(E(r,e))&&!isInFlightCopyTemp(e));await Promise.all(m.map(n=>I(async()=>{e(`[remove] ${E(r,n)} (no longer in source)`),t()?o({type:`remove`,path:n}):await v(n,{force:!0}).catch(e=>{if(!isNodeError(e)||e.code!==`ENOENT`&&e.code!==`ENOTDIR`&&e.code!==`EISDIR`&&e.code!==`ERR_FS_EISDIR`)throw e})})));let h=m.length;return{copied:u,removed:h,skipped:d}}async function moveDir(n,r){if(t())e(`[dry-run] would move ${n} → ${r}`),o({type:`move`,path:n,dest:r});else try{await _(n,r)}catch(e){if(isNodeError(e)&&e.code===`EXDEV`)await d(n,r,{recursive:!0}),await v(n,{recursive:!0,force:!0});else throw e}}async function removeDir(n){t()?(e(`[dry-run] would remove ${n}`),o({type:`remove`,path:n})):await v(n,{recursive:!0,force:!0})}async function ensureDir(n){t()?(e(`[dry-run] would ensure dir ${n}`),o({type:`mkdir`,path:n})):await p(n,{recursive:!0})}async function ensurePrivateDir(n){t()?(e(`[dry-run] would ensure private dir ${n}`),o({type:`mkdir`,path:n})):await p(n,{recursive:!0,mode:448})}async function exists(e){try{return await y(e),!0}catch{return!1}}async function atomicWriteFile(n,r){if(t()){e(`[dry-run] would write ${n}`),o({type:`write`,path:n});return}let i=`${n}.tmp-${process.pid}-${k()}`;try{await x(i,r),await _(i,n)}catch(e){throw await v(i,{force:!0}),e}}async function dirSize(e){try{let t=await collectFiles(e);return(await Promise.all(t.map(e=>y(e).then(e=>e.size).catch(()=>0)))).reduce((e,t)=>e+t,0)}catch{return 0}}async function copyDir(n,r){if(t())e(`[dry-run] would copy directory ${n} → ${r}`),o({type:`copy`,path:n,dest:r});else try{await d(n,r,{recursive:!0})}catch(e){if(process.platform!==`win32`||!isNodeError(e)||e.code!==`EPERM`||e.syscall!==`symlink`||!(await f(n)).isSymbolicLink())throw e;let t=await g(n);if(!(await y(t)).isDirectory())throw e;await p(S(r),{recursive:!0}),await b(t,r,`junction`)}}export{parseConsumersRegistry as A,getStoreHistoryPath as C,normalizePath as D,getStorePath as E,validatePackageName as M,validatePackageVersion as N,isKnarrMeta as O,warnVersionMismatch as P,getStoreEntryPath as S,getStorePackagePath as T,getConsumerKnarrDir as _,dirSize as a,getHistoryEntryPath as b,exists as c,moveDir as d,removeDir as f,getConsumerBackupPath as g,decodePackageName as h,copyWithCoW as i,validatePackageIdentity as j,parseConsumerState as k,incrementalCopy as l,pLimit as m,collectFiles as n,ensureDir as o,computeContentHash as p,copyDir as r,ensurePrivateDir as s,atomicWriteFile as t,isNodeError as u,getConsumerStatePath as v,getStoreMetaPath as w,getNodeModulesPackagePath as x,getConsumersPath as y};