knarr 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +65 -106
  2. package/dist/add-CyrFHzUe.mjs +1 -0
  3. package/dist/add-flow-BjjRSNWm.mjs +3 -0
  4. package/dist/batch-push-Cee2SPW3.mjs +1 -0
  5. package/dist/build-detect-Bo1fe8OV.mjs +1 -0
  6. package/dist/bundler-detect-BaShXORS.mjs +1 -0
  7. package/dist/check-ChNlHxR5.mjs +1 -0
  8. package/dist/chokidar-DoHpObCq.mjs +1 -0
  9. package/dist/clean-oNr4nUNk.mjs +1 -0
  10. package/dist/cli.d.ts +1 -0
  11. package/dist/cli.mjs +3 -4
  12. package/dist/config-D0TqqAAJ.mjs +2 -0
  13. package/dist/console-C8XtlRyM.mjs +1 -0
  14. package/dist/dev-vA8K5egW.mjs +1 -0
  15. package/dist/dist-jMqCJR3W.mjs +5 -0
  16. package/dist/doctor-ITFcIVoj.mjs +4 -0
  17. package/dist/dry-run-DPoN8bZo.mjs +1 -0
  18. package/dist/errors-DRugrv36.mjs +1 -0
  19. package/dist/explain-xtY13-Ex.mjs +1 -0
  20. package/dist/format-IsfSiyGV.mjs +1 -0
  21. package/dist/fs-Ce7wcxvx.mjs +1 -0
  22. package/dist/fs-DusqxRQR.mjs +1 -0
  23. package/dist/hints-BKo_2axg.mjs +1 -0
  24. package/dist/history-540r0BHF.mjs +1 -0
  25. package/dist/history-B3E1DMFO.mjs +1 -0
  26. package/dist/index.d.ts +17 -14
  27. package/dist/index.mjs +1 -3559
  28. package/dist/init-KBwXbX7j.mjs +2 -0
  29. package/dist/init-helpers-DGSTVbNx.mjs +13 -0
  30. package/dist/injector-BMOi1uN3.mjs +1 -0
  31. package/dist/json-1jsvqdBb.mjs +1 -0
  32. package/dist/list-BkniWIlD.mjs +1 -0
  33. package/dist/logger-Oo2Slehd.mjs +1 -0
  34. package/dist/migrate-DM80YXOF.mjs +3 -0
  35. package/dist/nextjs-config-BlbmHmCb.mjs +1 -0
  36. package/dist/nextjs-config-m83qz9Qp.mjs +2 -0
  37. package/dist/output-B7NC4xgj.mjs +1 -0
  38. package/dist/package-manager-Cs9kCsjJ.mjs +11 -0
  39. package/dist/paths-B5sEvS_7.mjs +1 -0
  40. package/dist/picomatch-DEttMFSR.mjs +1 -0
  41. package/dist/preflight-C_Zr3uyO.mjs +1 -0
  42. package/dist/preflight-fF8g1t6F.mjs +1 -0
  43. package/dist/publish-PaTRQ5Ga.mjs +1 -0
  44. package/dist/publisher-oHVy3LA2.mjs +2 -0
  45. package/dist/push-DX9dRKDw.mjs +1 -0
  46. package/dist/push-engine-ByiNZr52.mjs +1 -0
  47. package/dist/remove-BEBkMPak.mjs +1 -0
  48. package/dist/remove-DxezmGfU.mjs +1 -0
  49. package/dist/reset-B9Xcepo1.mjs +1 -0
  50. package/dist/restore-B8aEJn3N.mjs +1 -0
  51. package/dist/rollback-pqomySb-.mjs +1 -0
  52. package/dist/shell-DQfdqK0J.mjs +1 -0
  53. package/dist/status-2-lE-2hH.mjs +1 -0
  54. package/dist/store-CAzxNmpU.mjs +1 -0
  55. package/dist/tailwind-source-Ho_nKVtd.mjs +3 -0
  56. package/dist/timer-BZNWRS3O.mjs +1 -0
  57. package/dist/topo-sort-CNCKE3Ap.mjs +1 -0
  58. package/dist/topo-sort-I086ZoiN.mjs +1 -0
  59. package/dist/tracker-OhIA445x.mjs +1 -0
  60. package/dist/tracker-nsfA6PWa.mjs +1 -0
  61. package/dist/update-CjAl0ZO9.mjs +1 -0
  62. package/dist/use-BCXyvJf2.mjs +1 -0
  63. package/dist/vite-config-B6bZDoGe.mjs +1 -0
  64. package/dist/vite-config-D_iXaoHh.mjs +10 -0
  65. package/dist/vite-plugin.mjs +1 -210
  66. package/dist/watch-orchestrator-DGe9gBjj.mjs +1 -0
  67. package/dist/watch-orchestrator-DkuwJOEb.mjs +1 -0
  68. package/dist/watcher-DN6vT6nw.mjs +1 -0
  69. package/dist/watcher-LcNLwOgA.mjs +1 -0
  70. package/dist/webpack-plugin.mjs +1 -145
  71. package/dist/workspace-7rWwh6jI.mjs +1 -0
  72. package/dist/workspace-CSQVbAw4.mjs +1 -0
  73. package/package.json +6 -8
  74. package/dist/add-Clbi3vJ2.mjs +0 -3
  75. package/dist/add-flow-DdDziP5M.mjs +0 -5
  76. package/dist/batch-push-pVkjhRbp.mjs +0 -3
  77. package/dist/bell-BJuCym_5.mjs +0 -11
  78. package/dist/bell-CIzHg0kw.mjs +0 -3
  79. package/dist/bell-UNNirKkz.mjs +0 -3
  80. package/dist/build-detect-mSo9jKXK.mjs +0 -3
  81. package/dist/bundler-detect-Cx8_R2hT.mjs +0 -3
  82. package/dist/check-Boh8WU_W.mjs +0 -3
  83. package/dist/chokidar-BkIWf7Ix.mjs +0 -3
  84. package/dist/clean-DHh6fpmR.mjs +0 -3
  85. package/dist/config-CQpgsGyL.mjs +0 -4
  86. package/dist/console-BxhMcj-D.mjs +0 -81
  87. package/dist/console-X31Y_QS5.mjs +0 -3
  88. package/dist/dev-DeOwxr_7.mjs +0 -3
  89. package/dist/dist-CFkjiIqD.mjs +0 -7
  90. package/dist/doctor-XEdsr84Q.mjs +0 -6
  91. package/dist/dry-run-BxVjpNqJ.mjs +0 -3
  92. package/dist/errors-CV7G61Hr.mjs +0 -3
  93. package/dist/explain-BBv3U-D3.mjs +0 -3
  94. package/dist/format-DRqD29u-.mjs +0 -3
  95. package/dist/fs-BjaNhdzt.mjs +0 -683
  96. package/dist/fs-Cf1JTFyh.mjs +0 -3
  97. package/dist/fs-DUcoWJ1g.mjs +0 -3
  98. package/dist/hints-Hz3V4h3A.mjs +0 -3
  99. package/dist/history-BZS2YUIt.mjs +0 -3
  100. package/dist/history-C5ehozRy.mjs +0 -3
  101. package/dist/init-Dwf-EIG3.mjs +0 -4
  102. package/dist/init-helpers-BfDosqvf.mjs +0 -15
  103. package/dist/injector-XwK_LBUh.mjs +0 -3
  104. package/dist/json-C6XtcMC4.mjs +0 -46
  105. package/dist/json-CWzEb9Rt.mjs +0 -3
  106. package/dist/list-DcREV9JM.mjs +0 -3
  107. package/dist/logger-DlikgOlh.mjs +0 -3
  108. package/dist/migrate-DW5KQeDq.mjs +0 -5
  109. package/dist/nextjs-config-BfHv8mBE.mjs +0 -3
  110. package/dist/nextjs-config-CA4N_9VY.mjs +0 -4
  111. package/dist/output-BxyRer_F.mjs +0 -3
  112. package/dist/package-manager-DBBQ0XtZ.mjs +0 -13
  113. package/dist/picomatch-B0_Pxgms.mjs +0 -3
  114. package/dist/preflight-B17VQJs0.mjs +0 -3
  115. package/dist/preflight-B8ypfoKV.mjs +0 -3
  116. package/dist/publish-BLk5_qx1.mjs +0 -3
  117. package/dist/publisher-Br4Od-iL.mjs +0 -4
  118. package/dist/push-C6UFcNGO.mjs +0 -3
  119. package/dist/push-engine-D3rfg2Tj.mjs +0 -3
  120. package/dist/remove-Bz9dNgDM.mjs +0 -3
  121. package/dist/remove-DMj6k2PK.mjs +0 -3
  122. package/dist/reset--AuvAPTc.mjs +0 -3
  123. package/dist/restore-CIBe2F1d.mjs +0 -3
  124. package/dist/rollback-CFLIncnW.mjs +0 -3
  125. package/dist/rolldown-runtime-BZbIAPMk.mjs +0 -3
  126. package/dist/rolldown-runtime-D3KUYPsf.mjs +0 -12
  127. package/dist/shell-RQ7Hf1kp.mjs +0 -3
  128. package/dist/status-Dy-e_RtI.mjs +0 -3
  129. package/dist/store-BNeGfW_b.mjs +0 -3
  130. package/dist/tailwind-source-Cgva0Hte.mjs +0 -5
  131. package/dist/timer-DqgB175x.mjs +0 -3
  132. package/dist/topo-sort-DOCpHjT7.mjs +0 -3
  133. package/dist/topo-sort-yd4jxr_E.mjs +0 -3
  134. package/dist/tracker-DXSo5wXO.mjs +0 -3
  135. package/dist/tracker-DofCXLTP.mjs +0 -3
  136. package/dist/update-Dacjzw4f.mjs +0 -3
  137. package/dist/use-BSCV4IQ5.mjs +0 -3
  138. package/dist/vite-config-CbYEhn5K.mjs +0 -3
  139. package/dist/vite-config-DqxvL5TW.mjs +0 -12
  140. package/dist/watch-orchestrator-CghvwrNS.mjs +0 -3
  141. package/dist/watcher-Bw_qcI0M.mjs +0 -3
  142. package/dist/workspace-D4vhzpO4.mjs +0 -3
  143. package/dist/workspace-DVY5o1g8.mjs +0 -3
  144. package/dist/xxhash-wasm-D_QjdUuv.mjs +0 -3
@@ -1,210 +1 @@
1
- import { join, normalize } from "node:path";
2
- import { readFileSync } from "node:fs";
3
- // src/utils/json.ts
4
- function isJsonObject(value) {
5
- return typeof value === "object" && value !== null && !Array.isArray(value);
6
- }
7
- /** Parse JSON to `unknown`; callers must validate before use. */
8
- function parseJson(text) {
9
- return JSON.parse(text);
10
- }
11
- /** Parse JSON that must be an object (package.json, state files). Throws otherwise. */
12
- function parseJsonObject(text, label = "JSON") {
13
- const value = parseJson(text);
14
- if (!isJsonObject(value)) throw new Error(`${label} must contain a JSON object`);
15
- return value;
16
- }
17
- /** `obj[key]` when it is a JSON object. */
18
- function objectField(obj, key) {
19
- const value = obj[key];
20
- return isJsonObject(value) ? value : void 0;
21
- }
22
- // src/vite-plugin.ts
23
- /** Synchronously read linked package names from state.json */
24
- function readLinkedPackagesSync(stateFile) {
25
- try {
26
- const links = objectField(parseJsonObject(readFileSync(stateFile, "utf-8"), stateFile), "links");
27
- return links ? Object.keys(links) : [];
28
- } catch {
29
- return [];
30
- }
31
- }
32
- function knarrPlugin(options = {}) {
33
- const verbose = options.verbose ?? process.env.KNARR_VERBOSE === "1";
34
- /** Setup and bookkeeping details: only with verbose. User-facing events use console.log. */
35
- const debug = (msg) => {
36
- if (verbose) console.log(msg);
37
- };
38
- let knarrStateFile;
39
- let nodeModulesDir;
40
- let pollTimer;
41
- return {
42
- name: "vite-plugin-knarr",
43
- apply: "serve",
44
- config(config, { command }) {
45
- if (command !== "serve") return;
46
- const root = config.root ?? process.cwd();
47
- const linkedPackages = readLinkedPackagesSync(join(root, ".knarr", "state.json"));
48
- const result = {};
49
- if (linkedPackages.length > 0) {
50
- const existingExclude = config.optimizeDeps?.exclude ?? [];
51
- const newExclude = [...existingExclude, ...linkedPackages.filter((pkg) => !existingExclude.includes(pkg))];
52
- console.log(`[knarr] Excluding from pre-bundling: ${newExclude.join(", ")}`);
53
- result.optimizeDeps = { exclude: newExclude };
54
- }
55
- if (!!process.versions?.webcontainer && !config.server?.watch?.usePolling) {
56
- result.server = { watch: {
57
- usePolling: true,
58
- interval: 1e3
59
- } };
60
- console.log("[knarr] WebContainer detected, enabling filesystem polling");
61
- }
62
- if (Object.keys(result).length === 0) return;
63
- return result;
64
- },
65
- configResolved(config) {
66
- nodeModulesDir = join(config.root, "node_modules");
67
- knarrStateFile = normalize(join(config.root, ".knarr", "state.json"));
68
- debug(`[knarr] Watching state file: ${knarrStateFile}`);
69
- },
70
- configureServer(server) {
71
- const watchedPackages = /* @__PURE__ */ new Set();
72
- let isRestarting = false;
73
- let pendingRestart = false;
74
- let debounceTimer = null;
75
- let reloadTimer = null;
76
- /** Re-read state.json and add watchers for any new linked packages */
77
- function syncPackageWatchers() {
78
- let added = false;
79
- for (const pkg of readLinkedPackagesSync(knarrStateFile)) if (!watchedPackages.has(pkg)) {
80
- watchedPackages.add(pkg);
81
- added = true;
82
- }
83
- if (added && watchedPackages.size > 0) {
84
- const escaped = [...watchedPackages].sort((a, b) => b.length - a.length).map((p) => p.replace(/[/\\.*+?^${}()|[\]]/g, "\\$&")).join("|");
85
- server.watcher.options = {
86
- ...server.watcher.options,
87
- ignored: [
88
- new RegExp(`node_modules\\/(?!(?:${escaped})(?:\\/|$)).*`),
89
- /[/\\]\.git[/\\]/,
90
- /[/\\]test-results[/\\]/
91
- ]
92
- };
93
- server.watcher._userIgnored = void 0;
94
- for (const pkg of watchedPackages) {
95
- const pkgPath = join(nodeModulesDir, pkg);
96
- server.watcher.add(pkgPath);
97
- debug(`[knarr] Added watcher for package: ${pkgPath}`);
98
- }
99
- }
100
- }
101
- /** Restart the dev server to pick up changes */
102
- async function restartServer(source) {
103
- if (isRestarting) {
104
- pendingRestart = true;
105
- debug(`[knarr] Restart already in progress, queued: ${source}`);
106
- return;
107
- }
108
- isRestarting = true;
109
- syncPackageWatchers();
110
- console.log(`[knarr] ${source}, restarting server...`);
111
- try {
112
- await server.restart();
113
- } catch (err) {
114
- console.error(`[knarr] Dev server restart failed: ${err instanceof Error ? err.message : String(err)}`);
115
- } finally {
116
- isRestarting = false;
117
- if (pendingRestart) {
118
- pendingRestart = false;
119
- await restartServer("Queued change detected");
120
- }
121
- }
122
- }
123
- /** Debounced restart for state.json changes (new packages linked) */
124
- function scheduleRestart(source) {
125
- if (debounceTimer) return;
126
- debounceTimer = setTimeout(() => {
127
- debounceTimer = null;
128
- restartServer(source);
129
- }, 1500);
130
- }
131
- /** Send a debounced full-reload to the browser */
132
- function scheduleReload() {
133
- if (reloadTimer) clearTimeout(reloadTimer);
134
- reloadTimer = setTimeout(() => {
135
- reloadTimer = null;
136
- console.log("[knarr] Linked package updated, reloading");
137
- server.hot.send({
138
- type: "full-reload",
139
- path: "*"
140
- });
141
- }, 200);
142
- }
143
- /** Invalidate changed module and send debounced full-reload */
144
- function invalidateAndReload(changedPath) {
145
- const normalized = normalize(changedPath);
146
- const mods = server.moduleGraph.getModulesByFile(normalized);
147
- if (mods) mods.forEach((m) => server.moduleGraph.invalidateModule(m));
148
- scheduleReload();
149
- }
150
- /** Invalidate all cached modules for linked packages (polling fallback) */
151
- function invalidateLinkedModules() {
152
- for (const [url, mod] of server.moduleGraph.urlToModuleMap) for (const pkg of watchedPackages) if (url.includes(pkg)) {
153
- server.moduleGraph.invalidateModule(mod);
154
- break;
155
- }
156
- scheduleReload();
157
- }
158
- server.watcher.add(knarrStateFile);
159
- debug(`[knarr] Added watcher for: ${knarrStateFile}`);
160
- syncPackageWatchers();
161
- server.watcher.on("change", (changedPath) => {
162
- const normalizedChanged = normalize(changedPath);
163
- if (normalizedChanged === knarrStateFile) {
164
- if (readLinkedPackagesSync(knarrStateFile).some((pkg) => !watchedPackages.has(pkg))) scheduleRestart("New package linked");
165
- else invalidateLinkedModules();
166
- return;
167
- }
168
- if ([...watchedPackages].some((pkg) => normalizedChanged.includes(normalize(join(nodeModulesDir, pkg))))) invalidateAndReload(changedPath);
169
- });
170
- server.watcher.on("add", (addedPath) => {
171
- const normalizedAdded = normalize(addedPath);
172
- if ([...watchedPackages].some((pkg) => normalizedAdded.includes(normalize(join(nodeModulesDir, pkg))))) invalidateAndReload(addedPath);
173
- });
174
- if (process.versions?.webcontainer) {
175
- if (pollTimer) clearInterval(pollTimer);
176
- let lastStateContent = "";
177
- try {
178
- lastStateContent = readFileSync(knarrStateFile, "utf-8");
179
- } catch {}
180
- pollTimer = setInterval(() => {
181
- try {
182
- const content = readFileSync(knarrStateFile, "utf-8");
183
- if (lastStateContent && content !== lastStateContent) {
184
- lastStateContent = content;
185
- if (readLinkedPackagesSync(knarrStateFile).some((pkg) => !watchedPackages.has(pkg))) scheduleRestart("New package linked (polling fallback)");
186
- else invalidateLinkedModules();
187
- }
188
- if (!lastStateContent) lastStateContent = content;
189
- } catch {}
190
- }, 1e3);
191
- console.log("[knarr] WebContainer polling fallback active (1s interval)");
192
- }
193
- server.httpServer?.on("close", () => {
194
- if (pollTimer) {
195
- clearInterval(pollTimer);
196
- pollTimer = void 0;
197
- }
198
- if (debounceTimer) {
199
- clearTimeout(debounceTimer);
200
- debounceTimer = null;
201
- }
202
- if (reloadTimer) {
203
- clearTimeout(reloadTimer);
204
- reloadTimer = null;
205
- }
206
- });
207
- }
208
- };
209
- }
210
- export { knarrPlugin as default };
1
+ import{i as e,s as t}from"./json-1jsvqdBb.mjs";import{join as n,normalize as r}from"node:path";import{readFileSync as i}from"node:fs";function a(n){try{let r=i(n,`utf-8`),a=e(t(r,n),`links`);return a?Object.keys(a):[]}catch{return[]}}function o(e={}){let t=e.verbose??process.env.KNARR_VERBOSE===`1`,o=e=>{t&&console.log(e)},s,c,l;return{name:`vite-plugin-knarr`,apply:`serve`,config(e,{command:t}){if(t!==`serve`)return;let r=e.root??process.cwd(),i=a(n(r,`.knarr`,`state.json`)),o={};if(i.length>0){let t=e.optimizeDeps?.exclude??[],n=[...t,...i.filter(e=>!t.includes(e))];console.log(`[knarr] Excluding from pre-bundling: ${n.join(`, `)}`),o.optimizeDeps={exclude:n}}if(process.versions?.webcontainer&&!e.server?.watch?.usePolling&&(o.server={watch:{usePolling:!0,interval:1e3}},console.log(`[knarr] WebContainer detected, enabling filesystem polling`)),Object.keys(o).length!==0)return o},configResolved(e){c=n(e.root,`node_modules`),s=r(n(e.root,`.knarr`,`state.json`)),o(`[knarr] Watching state file: ${s}`)},configureServer(e){let t=/* @__PURE__ */ new Set,u=!1,d=!1,f=null,p=null;function m(){let r=!1;for(let e of a(s))t.has(e)||(t.add(e),r=!0);if(r&&t.size>0){let r=[...t].sort((e,t)=>t.length-e.length).map(e=>e.replace(/[/\\.*+?^${}()|[\]]/g,`\\$&`)).join(`|`);e.watcher.options={...e.watcher.options,ignored:[RegExp(`node_modules\\/(?!(?:${r})(?:\\/|$)).*`),/[/\\]\.git[/\\]/,/[/\\]test-results[/\\]/]},e.watcher._userIgnored=void 0;for(let r of t){let t=n(c,r);e.watcher.add(t),o(`[knarr] Added watcher for package: ${t}`)}}}async function h(t){if(u)d=!0,o(`[knarr] Restart already in progress, queued: ${t}`);else{u=!0,m(),console.log(`[knarr] ${t}, restarting server...`);try{await e.restart()}catch(e){console.error(`[knarr] Dev server restart failed: ${e instanceof Error?e.message:String(e)}`)}finally{u=!1,d&&(d=!1,await h(`Queued change detected`))}}}function g(e){f||=setTimeout(()=>{f=null,h(e)},1500)}function _(){p&&clearTimeout(p),p=setTimeout(()=>{p=null,console.log(`[knarr] Linked package updated, reloading`),e.hot.send({type:`full-reload`,path:`*`})},200)}function v(t){let n=r(t),i=e.moduleGraph.getModulesByFile(n);i&&i.forEach(t=>e.moduleGraph.invalidateModule(t)),_()}function y(){for(let[n,r]of e.moduleGraph.urlToModuleMap)for(let i of t)if(n.includes(i)){e.moduleGraph.invalidateModule(r);break}_()}if(e.watcher.add(s),o(`[knarr] Added watcher for: ${s}`),m(),e.watcher.on(`change`,e=>{let i=r(e);i===s?a(s).some(e=>!t.has(e))?g(`New package linked`):y():[...t].some(e=>i.includes(r(n(c,e))))&&v(e)}),e.watcher.on(`add`,e=>{let i=r(e);[...t].some(e=>i.includes(r(n(c,e))))&&v(e)}),process.versions?.webcontainer){l&&clearInterval(l);let e=``;try{e=i(s,`utf-8`)}catch{}l=setInterval(()=>{try{let n=i(s,`utf-8`);e&&n!==e&&(e=n,a(s).some(e=>!t.has(e))?g(`New package linked (polling fallback)`):y()),e||=n}catch{}},1e3),console.log(`[knarr] WebContainer polling fallback active (1s interval)`)}e.httpServer?.on(`close`,()=>{l&&=(clearInterval(l),void 0),f&&=(clearTimeout(f),null),p&&=(clearTimeout(p),null)})}}}export{o as default};
@@ -0,0 +1 @@
1
+ export{t as WatchOrchestrator}from"./watch-orchestrator-DkuwJOEb.mjs";
@@ -0,0 +1 @@
1
+ import{t as e}from"./console-C8XtlRyM.mjs";import{i as t}from"./logger-Oo2Slehd.mjs";import{t as n}from"./config-D0TqqAAJ.mjs";import{r,t as i}from"./push-engine-ByiNZr52.mjs";var a=class{packages=/* @__PURE__ */ new Map;dependents=/* @__PURE__ */ new Map;cascade;pushOptions={};constructor(e){this.cascade=e}async start(t,a,s){this.pushOptions=s;let{buildWorkspaceGraph:c,buildReverseAdjacency:l,filterPublishableWorkspaceGraph:u}=await import(`./workspace-CSQVbAw4.mjs`),{topoSort:d,CycleError:f}=await import(`./topo-sort-CNCKE3Ap.mjs`),{startWatcher:p}=await import(`./watcher-LcNLwOgA.mjs`),m=await c(t),h=u(m);if(h.packages.length===0){e.warn(`No publishable workspace packages found`);return}let g=m.packages.length-h.packages.length;g>0&&e.info(`Skipping ${g} private workspace package(s)`);let _;try{_=d(h.adjacency)}catch(t){if(t instanceof f){e.error(`Cannot watch: ${t.message}`);return}throw t}this.cascade&&(this.dependents=l(h.adjacency),e.info(`Cascade mode enabled`));let v=new Map(h.packages.map(e=>[e.name,e.dir]));for(let e of _){let t=v.get(e);if(!t)continue;let c=await n(t),{buildCmd:l,patterns:u}=await r(t,a,c),d=a.notify??c.notify??!1,f=async()=>{await this.runExclusive(e,async()=>{o(await i(t,s),e),await this.onPackagePushed(e)})},m=e=>{if(!e)return;let t=parseInt(e,10);return Number.isFinite(t)?t:void 0},h={dir:t,buildCmd:l,state:`idle`,watcher:{close:async()=>{}}};this.packages.set(e,h),h.watcher=await p(t,{patterns:u,buildCmd:l,debounce:m(a.debounce)??c.debounce,cooldown:m(a.cooldown)??c.cooldown,notify:d,label:e},f)}e.info(`Watching ${this.packages.size} workspace packages`),await new Promise(t=>{let n=()=>{e.info(`Stopping watchers...`),this.close().catch(t=>{e.warn(`Watchers did not close cleanly: ${t instanceof Error?t.message:String(t)}`)}).finally(t)};process.once(`SIGINT`,n),process.once(`SIGTERM`,n)})}async onPackagePushed(t){if(!this.cascade)return;let n=this.dependents.get(t);if(n&&n.size!==0){e.info(`${t} changed, rebuilding dependents: ${[...n].join(`, `)}`);for(let e of n)await this.requestRebuild(e)}}async runExclusive(e,n){let r=this.packages.get(e);if(r){if(r.state===`queued`)t(`[cascade] ${e} already queued, skipping`);else if(r.state===`building`)t(`[cascade] ${e} is building, marking as queued`),r.state=`queued`;else{r.state=`building`;try{await n(r)}finally{let t=r.state===`queued`;r.state=`idle`,t&&await this.requestRebuild(e)}}}}async requestRebuild(n){await this.runExclusive(n,async r=>{if(t(`[cascade] Rebuilding ${n}`),r.buildCmd){let{runBuildCommand:t}=await import(`./watcher-LcNLwOgA.mjs`);if(!await t(r.buildCmd,r.dir,n)){e.warn(`[cascade] Build failed for ${n}, skipping dependents`);return}}o(await i(r.dir,this.pushOptions),n),await this.onPackagePushed(n)}).catch(t=>{e.warn(`[cascade] Push failed for ${n}: ${t instanceof Error?t.message:String(t)}`)})}async close(){await Promise.all([...this.packages.values()].map(e=>e.watcher.close())),this.packages.clear()}};function o(e,t){if(e.failedConsumers!==0)throw Error(`Push for ${t} failed for ${e.failedConsumers} consumer(s)`)}export{a as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./console-C8XtlRyM.mjs";import{n as t}from"./shell-DQfdqK0J.mjs";import{platform as n,release as r}from"node:os";import{readdir as i,stat as a}from"node:fs/promises";import{join as o}from"node:path";function s(e){e&&process.stderr.write(`\x07`)}const c=/* @__PURE__ */ new Set;function l(){for(let e of c)e.killed||e.kill(`SIGTERM`);c.clear()}const u=/* @__PURE__ */ new Set([`node_modules`,`.git`,`.knarr`]);function d(e,t={platform:n(),release:r(),webcontainer:!!process.versions?.webcontainer}){return t.webcontainer?!0:t.platform===`linux`&&/microsoft|wsl/i.test(t.release)&&/^\/mnt\/[a-z](?:\/|$)/i.test(e)}async function f(e,t){let n;try{n=await i(e,{withFileTypes:!0})}catch{return}for(let r of n){if(u.has(r.name))continue;let n=o(e,r.name);if(r.isDirectory())await f(n,t);else try{let e=await a(n);t.set(n,e.mtimeMs)}catch{}}}async function p(e){let t=/* @__PURE__ */ new Map;for(let n of e)try{let e=await a(n);e.isDirectory()?await f(n,t):t.set(n,e.mtimeMs)}catch{}return t}async function m(t,n,r){let{watch:i}=await import(`./chokidar-DoHpObCq.mjs`),a=n.patterns??[`src`,`lib`],o=a.map(e=>e.startsWith(`/`)||e.includes(`:`)?e:`${t}/${e}`),c=n.label?`${n.label}: `:``,u=n.debounce??500,f=n.cooldown??500,m=null,g=!1,_=!1,v=0,y=0,b=null,x=!1,S=async()=>{if(g||_)return;let i=Date.now()-v;if(v>0&&i<f){let e=f-i;m&&clearTimeout(m),m=setTimeout(()=>{m=null,S()},e)}else{_=!0,x=!1,y++;try{if(e.info(`${c}Change cycle #${y} started`),n.buildCmd&&!await h(n.buildCmd,t,n.label)){e.warn(c+`Build failed (see output above), skipping push. Consumers keep the last pushed build`+(b?` (${b.toLocaleTimeString()})`:``)+`. Fix the error and save to retry.`),n.notify&&s(!0);return}await r(),b=/* @__PURE__ */ new Date,n.notify&&s(!0)}catch(t){e.error(`Push failed: ${t instanceof Error?t.message:String(t)}`),n.notify&&s(!0)}finally{_=!1,v=Date.now(),x&&!g&&(x=!1,m=setTimeout(()=>{m=null,S()},f))}}},C=e=>{if(g)return;if(_){x=!0;return}let t=Date.now()-v;if(v>0&&t<f){m&&clearTimeout(m);let e=f-t;m=setTimeout(()=>{m=null,S()},e+u)}else m&&clearTimeout(m),m=setTimeout(()=>{m=null,S()},u)},w=n.buildCmd?!1:n.awaitWriteFinish??{stabilityThreshold:200,pollInterval:50},T=d(t),E=i(o,{ignoreInitial:!0,ignored:[/[/\\]node_modules[/\\]/,/[/\\]\.git[/\\]/,/[/\\]\.knarr[/\\]/],awaitWriteFinish:w,backend:T?`polling`:`auto`,...T&&{pollingInterval:1e3}});E.on(`change`,C),E.on(`add`,C),E.on(`unlink`,C),E.on(`error`,t=>{e.error(`Watcher error: ${t instanceof Error?t.message:String(t)}`)});let D=null;if(T){let e=await p(o),t=async()=>{if(!g)try{let t=await p(o);for(let[n,r]of t){let t=e.get(n);if(t===void 0||t!==r){C(n);break}}if(!g){for(let n of e.keys())if(!t.has(n)){C(n);break}}e=t}catch{}};D=setInterval(()=>void t(),1e3)}return e.info(`${c}Watching for changes in: ${a.join(`, `)}`),{close:async()=>{g=!0,D&&clearInterval(D),m&&clearTimeout(m),l(),await E.close()}}}function h(n,r,i){return new Promise(a=>{e.start(`${i?`${i}: `:``}Running: ${n}`);let o=t(n,{cwd:r,stdio:`inherit`});c.add(o),o.on(`close`,t=>{c.delete(o),t===0?(e.success(`Build succeeded`),a(!0)):(e.error(`Build failed with code ${t}`),a(!1))}),o.on(`error`,t=>{c.delete(o),e.error(`Build error: ${t.message}`),a(!1)})})}export{s as a,m as i,h as n,d as r,l as t};
@@ -0,0 +1 @@
1
+ export{n as runBuildCommand,i as startWatcher}from"./watcher-DN6vT6nw.mjs";
@@ -1,145 +1 @@
1
- import { join, normalize } from "node:path";
2
- import { readFileSync } from "node:fs";
3
- // src/utils/json.ts
4
- function isJsonObject(value) {
5
- return typeof value === "object" && value !== null && !Array.isArray(value);
6
- }
7
- /** Parse JSON to `unknown`; callers must validate before use. */
8
- function parseJson(text) {
9
- return JSON.parse(text);
10
- }
11
- /** Parse JSON that must be an object (package.json, state files). Throws otherwise. */
12
- function parseJsonObject(text, label = "JSON") {
13
- const value = parseJson(text);
14
- if (!isJsonObject(value)) throw new Error(`${label} must contain a JSON object`);
15
- return value;
16
- }
17
- /** `obj[key]` when it is a JSON object. */
18
- function objectField(obj, key) {
19
- const value = obj[key];
20
- return isJsonObject(value) ? value : void 0;
21
- }
22
- // src/webpack-plugin.ts
23
- /** Synchronously read linked package names from state.json */
24
- function readLinkedPackagesSync(stateFile) {
25
- try {
26
- const links = objectField(parseJsonObject(readFileSync(stateFile, "utf-8"), stateFile), "links");
27
- return links ? Object.keys(links) : [];
28
- } catch {
29
- return [];
30
- }
31
- }
32
- /**
33
- * Webpack/rspack plugin for knarr.
34
- *
35
- * - Excludes linked packages from webpack's snapshot cache (managedPaths)
36
- * - Watches .knarr/state.json and linked package directories
37
- * - Invalidates the compiler on changes to trigger a rebuild
38
- * - Works with webpack 5 and rspack (uses loose typing, no webpack import)
39
- */
40
- var KnarrWebpackPlugin = class {
41
- options;
42
- constructor(options = {}) {
43
- this.options = options;
44
- }
45
- apply(compiler) {
46
- const root = this.options.root ?? compiler.options.context ?? process.cwd();
47
- const stateFile = normalize(join(root, ".knarr", "state.json"));
48
- const nodeModulesDir = join(root, "node_modules");
49
- let watcher = null;
50
- let pollTimer;
51
- let debounceTimer = null;
52
- let lastStateContent = "";
53
- const watchedPackages = /* @__PURE__ */ new Set();
54
- const invalidate = () => {
55
- if (debounceTimer) clearTimeout(debounceTimer);
56
- debounceTimer = setTimeout(() => {
57
- debounceTimer = null;
58
- if (compiler.watching) compiler.watching.invalidate();
59
- }, 200);
60
- };
61
- const syncPackages = () => {
62
- let changed = false;
63
- for (const pkg of readLinkedPackagesSync(stateFile)) if (!watchedPackages.has(pkg)) {
64
- watchedPackages.add(pkg);
65
- changed = true;
66
- }
67
- return changed;
68
- };
69
- compiler.hooks.afterEnvironment.tap("KnarrWebpackPlugin", () => {
70
- syncPackages();
71
- if (watchedPackages.size === 0) return;
72
- const snapshot = compiler.options.snapshot ??= {};
73
- const managedPaths = snapshot.managedPaths ??= [];
74
- const escaped = [...watchedPackages].sort((a, b) => b.length - a.length).map((p) => p.replace(/[/\\.*+?^${}()|[\]]/g, "\\$&")).join("|");
75
- const excludeRegex = new RegExp(`node_modules[\\\\/](?!(?:${escaped})(?:[\\\\/]|$))`);
76
- const filtered = managedPaths.filter((p) => {
77
- if (typeof p === "string") return !p.includes("node_modules");
78
- return !p.source?.includes("node_modules");
79
- });
80
- filtered.push(excludeRegex);
81
- snapshot.managedPaths = filtered;
82
- });
83
- compiler.hooks.watchRun.tapPromise("KnarrWebpackPlugin", async () => {
84
- if (watcher) return;
85
- const usePolling = !!process.versions?.webcontainer;
86
- if (usePolling) {
87
- try {
88
- lastStateContent = readFileSync(stateFile, "utf-8");
89
- } catch {}
90
- pollTimer = setInterval(() => {
91
- try {
92
- const content = readFileSync(stateFile, "utf-8");
93
- if (lastStateContent && content !== lastStateContent) {
94
- lastStateContent = content;
95
- syncPackages();
96
- invalidate();
97
- }
98
- if (!lastStateContent) lastStateContent = content;
99
- } catch {}
100
- }, 1e3);
101
- }
102
- const { watch } = await import("chokidar");
103
- const watchPaths = [stateFile];
104
- for (const pkg of watchedPackages) watchPaths.push(join(nodeModulesDir, pkg));
105
- const chokidarWatcher = watch(watchPaths, {
106
- ignoreInitial: true,
107
- ignored: [/[/\\]\.git[/\\]/],
108
- backend: usePolling ? "polling" : "auto",
109
- ...usePolling && { pollingInterval: 1e3 }
110
- });
111
- let chokidarClosed = false;
112
- chokidarWatcher.on("change", (changedPath) => {
113
- if (normalize(changedPath) === stateFile) {
114
- if (syncPackages() && !chokidarClosed) for (const pkg of watchedPackages) chokidarWatcher.add(join(nodeModulesDir, pkg));
115
- }
116
- invalidate();
117
- });
118
- chokidarWatcher.on("add", () => invalidate());
119
- chokidarWatcher.on("unlink", () => invalidate());
120
- watcher = { close: () => {
121
- chokidarClosed = true;
122
- return chokidarWatcher.close();
123
- } };
124
- });
125
- compiler.hooks.afterCompile.tapPromise("KnarrWebpackPlugin", (compilation) => {
126
- for (const pkg of watchedPackages) compilation.contextDependencies.add(join(nodeModulesDir, pkg));
127
- return Promise.resolve();
128
- });
129
- compiler.hooks.watchClose.tap("KnarrWebpackPlugin", () => {
130
- if (debounceTimer) {
131
- clearTimeout(debounceTimer);
132
- debounceTimer = null;
133
- }
134
- if (pollTimer) {
135
- clearInterval(pollTimer);
136
- pollTimer = void 0;
137
- }
138
- if (watcher) {
139
- watcher.close().catch(() => {});
140
- watcher = null;
141
- }
142
- });
143
- }
144
- };
145
- export { KnarrWebpackPlugin, KnarrWebpackPlugin as default };
1
+ import{i as e,s as t}from"./json-1jsvqdBb.mjs";import{join as n,normalize as r}from"node:path";import{readFileSync as i}from"node:fs";function a(n){try{let r=i(n,`utf-8`),a=e(t(r,n),`links`);return a?Object.keys(a):[]}catch{return[]}}var o=class{options;constructor(e={}){this.options=e}apply(e){let t=this.options.root??e.options.context??process.cwd(),o=r(n(t,`.knarr`,`state.json`)),s=n(t,`node_modules`),c=null,l,u=null,d=``,f=/* @__PURE__ */ new Set,p=()=>{u&&clearTimeout(u),u=setTimeout(()=>{u=null,e.watching&&e.watching.invalidate()},200)},m=()=>{let e=!1;for(let t of a(o))f.has(t)||(f.add(t),e=!0);return e};e.hooks.afterEnvironment.tap(`KnarrWebpackPlugin`,()=>{if(m(),f.size===0)return;let t=e.options.snapshot??={},n=t.managedPaths??=[],r=[...f].sort((e,t)=>t.length-e.length).map(e=>e.replace(/[/\\.*+?^${}()|[\]]/g,`\\$&`)).join(`|`),i=RegExp(`node_modules[\\\\/](?!(?:${r})(?:[\\\\/]|$))`),a=n.filter(e=>typeof e==`string`?!e.includes(`node_modules`):!e.source?.includes(`node_modules`));a.push(i),t.managedPaths=a}),e.hooks.watchRun.tapPromise(`KnarrWebpackPlugin`,async()=>{if(c)return;let e=!!process.versions?.webcontainer;if(e){try{d=i(o,`utf-8`)}catch{}l=setInterval(()=>{try{let e=i(o,`utf-8`);d&&e!==d&&(d=e,m(),p()),d||=e}catch{}},1e3)}let{watch:t}=await import(`./chokidar-DoHpObCq.mjs`),a=[o];for(let e of f)a.push(n(s,e));let u=t(a,{ignoreInitial:!0,ignored:[/[/\\]\.git[/\\]/],backend:e?`polling`:`auto`,...e&&{pollingInterval:1e3}}),h=!1;u.on(`change`,e=>{if(r(e)===o&&m()&&!h)for(let e of f)u.add(n(s,e));p()}),u.on(`add`,()=>p()),u.on(`unlink`,()=>p()),c={close:()=>(h=!0,u.close())}}),e.hooks.afterCompile.tapPromise(`KnarrWebpackPlugin`,e=>{for(let t of f)e.contextDependencies.add(n(s,t));return Promise.resolve()}),e.hooks.watchClose.tap(`KnarrWebpackPlugin`,()=>{u&&=(clearTimeout(u),null),l&&=(clearInterval(l),void 0),c&&=(c.close().catch(()=>{}),null)})}};export{o as KnarrWebpackPlugin,o as default};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./picomatch-DEttMFSR.mjs";import{c as n}from"./fs-DusqxRQR.mjs";import{p as r}from"./paths-B5sEvS_7.mjs";import{a as i,c as a,r as o,t as s}from"./json-1jsvqdBb.mjs";import{readFile as c,readdir as l}from"node:fs/promises";import{dirname as u,join as d,relative as f,resolve as p}from"node:path";var m=/* @__PURE__ */ e(t(),1);async function h(e){let t=e;for(;;){if(await n(d(t,`pnpm-workspace.yaml`)))return t;let e=u(t);if(e===t)return null;t=e}}async function g(e){return await h(e)??await b(e)}async function _(e){let t={default:i(),named:i()},n=d(e,`pnpm-workspace.yaml`),r;try{r=await c(n,`utf-8`)}catch{return t}let a=r.split(/\r?\n/),o=`top`,s=``;for(let e of a){if(e.trim()===``||e.trim().startsWith(`#`))continue;let n=e.length-e.trimStart().length;if(n===0){if(e.startsWith(`catalog:`)){o=`default-catalog`;continue}if(e.startsWith(`catalogs:`)){o=`named-catalogs`;continue}o=`top`}else if(o===`default-catalog`&&n>=2){let n=E(e);n&&(t.default[n[0]]=n[1])}else if(o===`named-catalogs`&&n>=2&&n<4){let n=e.trim();n.endsWith(`:`)&&(s=n.slice(0,-1),t.named[s]=i(),o=`named-catalog-entries`)}else if(o===`named-catalog-entries`&&n>=4){let n=E(e),r=s?t.named[s]:void 0;n&&r&&(r[n[0]]=n[1])}else if(o===`named-catalog-entries`&&n>=2&&n<4){let n=e.trim();n.endsWith(`:`)?(s=n.slice(0,-1),t.named[s]=i()):o=`named-catalogs`}}return t}async function v(e){let t=await h(e);if(t){let e=await y(t),n=e.filter(e=>!e.startsWith(`!`)),r=e.filter(e=>e.startsWith(`!`)).map(e=>e.slice(1));if(n.length>0)return x(t,n,r)}let n=t??await b(e);if(!n)return[];try{let e=(await a(d(n,`package.json`))).workspaces,t=Array.isArray(e)?e:o(e)?e.packages:[],r=Array.isArray(t)?t.filter(e=>typeof e==`string`):[];return r.length===0?[]:x(n,r.filter(e=>!e.startsWith(`!`)),r.filter(e=>e.startsWith(`!`)).map(e=>e.slice(1)))}catch{return[]}}async function y(e){let t=d(e,`pnpm-workspace.yaml`),n;try{n=await c(t,`utf-8`)}catch{return[]}let r=[],i=!1;for(let e of n.split(/\r?\n/)){let t=e.trim();if(t===``||t.startsWith(`#`))continue;let n=e.length-e.trimStart().length;if(n===0)i=t===`packages:`;else if(i&&n>=2){let e=t.match(/^-\s+["']?([^"']+)["']?$/);e?.[1]&&r.push(e[1])}}return r}async function b(e){let t=e;for(;;){try{if((await a(d(t,`package.json`))).workspaces)return t}catch{}let e=u(t);if(e===t)return null;t=e}}async function x(e,t,i=[]){let a=[];for(let i of t)if(i.includes(`*`)){let t=i.split(`/`),o=e,s=[],c=!1;for(let e of t)c||e.includes(`*`)?(c=!0,s.push(e)):o=d(o,e);if(s.length===1&&s[0]===`*`)try{let e=await l(o,{withFileTypes:!0});for(let t of e)if(t.isDirectory()){let e=d(o,t.name);await n(d(e,`package.json`))&&a.push(e)}}catch{}else{let t=(0,m.default)(i),o=await S(e,8);for(let i of o)t(r(f(e,i)))&&await n(d(i,`package.json`))&&a.push(i)}}else{let t=p(e,i);await n(d(t,`package.json`))&&a.push(t)}let o=[...new Set(a)];if(i.length===0)return o;let s=(0,m.default)(i);return o.filter(t=>{let n=r(f(e,t));return!s(n)})}async function S(e,t){if(t<=0)return[];let n=[];try{let r=await l(e,{withFileTypes:!0});for(let i of r){if(!i.isDirectory()||i.name===`node_modules`||i.name===`.git`)continue;let r=d(e,i.name);n.push(r),n.push(...await S(r,t-1))}}catch{}return n}async function C(e){let t=await v(e),n=[];for(let e of t)try{let t=s(await a(d(e,`package.json`)));t?.name&&t.version&&n.push({name:t.name,version:t.version,dir:e,pkg:t})}catch{}let r=new Set(n.map(e=>e.name)),i=/* @__PURE__ */ new Map;for(let e of n){let t=/* @__PURE__ */ new Set;for(let n of[`dependencies`,`devDependencies`]){let i=e.pkg[n];if(i)for(let e of Object.keys(i))r.has(e)&&t.add(e)}i.set(e.name,t)}return{packages:n,adjacency:i}}function w(e){let t=e.packages.filter(e=>!e.pkg.private),n=new Set(t.map(e=>e.name)),r=/* @__PURE__ */ new Map;for(let i of t){let t=e.adjacency.get(i.name)??/* @__PURE__ */ new Set;r.set(i.name,new Set([...t].filter(e=>n.has(e))))}return{packages:t,adjacency:r}}function T(e){let t=/* @__PURE__ */ new Map;for(let n of e.keys())t.set(n,/* @__PURE__ */ new Set);for(let[n,r]of e)for(let e of r){let r=t.get(e);r||(r=/* @__PURE__ */ new Set,t.set(e,r)),r.add(n)}return t}function E(e){let t=e.trim(),n=t.indexOf(`:`);if(n<=0)return null;let r=t.slice(0,n).trim(),i=D(t.slice(n+1)).trim();return!r||!i?null:[r.replace(/^["']|["']$/g,``),i.replace(/^["']|["']$/g,``)]}function D(e){let t=null;for(let n=0;n<e.length;n++){let r=e[n];if((r===`"`||r===`'`)&&e[n-1]!==`\\`)t=t===r?null:t??r;else if(!t&&r===`#`&&(n===0||/\s/.test(e[n-1]??``)))return e.slice(0,n)}return e}export{v as a,g as i,C as n,h as o,w as r,_ as s,T as t};
@@ -0,0 +1 @@
1
+ export{t as buildReverseAdjacency,n as buildWorkspaceGraph,r as filterPublishableWorkspaceGraph,i as findWorkspacePackageRoot,a as findWorkspacePackages,s as parseCatalogs}from"./workspace-7rWwh6jI.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "knarr",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Copy local npm package builds into consumer node_modules with incremental sync and watch mode.",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
@@ -88,10 +88,15 @@
88
88
  "node": ">=22.22.0"
89
89
  },
90
90
  "devDependencies": {
91
+ "@arethetypeswrong/core": "^0.18.5",
91
92
  "@types/node": "^26.6.6",
92
93
  "@types/picomatch": "^4.0.3",
94
+ "chokidar": "^6.0.0",
95
+ "citty": "^0.2.2",
93
96
  "oxlint": "^1.92.0",
94
97
  "oxlint-tsgolint": "^7.0.2006",
98
+ "picomatch": "^4.0.7",
99
+ "publint": "^0.3.25",
95
100
  "tsdown": "^0.23.7",
96
101
  "typescript": "^7.0.2",
97
102
  "vite": "^8.3.6",
@@ -112,12 +117,5 @@
112
117
  "@rspack/core": {
113
118
  "optional": true
114
119
  }
115
- },
116
- "dependencies": {
117
- "chokidar": "^6.0.0",
118
- "citty": "^0.2.2",
119
- "picocolors": "^1.1.1",
120
- "picomatch": "^4.0.7",
121
- "xxhash-wasm": "^1.1.0"
122
120
  }
123
121
  }
@@ -1,3 +0,0 @@
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"./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};
@@ -1,5 +0,0 @@
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-X31Y_QS5.mjs";import{n as r,t as i}from"./store-BNeGfW_b.mjs";import{t as a}from"./publisher-Br4Od-iL.mjs";import{i as o,n as s,r as c,t as l}from"./injector-XwK_LBUh.mjs";import{c as u,i as d,t as f}from"./tracker-DofCXLTP.mjs";import{F as p,N as m,P as h,c as g,y as _}from"./fs-Cf1JTFyh.mjs";import{t as v}from"./package-manager-DBBQ0XtZ.mjs";import{t as y}from"./build-detect-mSo9jKXK.mjs";import{n as b}from"./bundler-detect-Cx8_R2hT.mjs";import{i as x,o as S}from"./init-helpers-BfDosqvf.mjs";import{t as C}from"./nextjs-config-CA4N_9VY.mjs";import{t as w}from"./timer-DqgB175x.mjs";import{t as T}from"./output-BxyRer_F.mjs";import{t as E}from"./errors-CV7G61Hr.mjs";import{i as D,n as O,r as k}from"./logger-DlikgOlh.mjs";import{i as A,r as j}from"./dry-run-BxVjpNqJ.mjs";import{a as M}from"./json-CWzEb9Rt.mjs";import{readFile as N}from"node:fs/promises";import{basename as P,join as F,resolve as I}from"node:path";async function addPackageToConsumer(e){let s=e.timer??new w,m=I(`.`),{name:y,version:b}=parsePackageArg(e.packageArg),C,D=null,k=!1,A=!1;if(validatePackageNameArg(y,e.packageArg),b)try{h(b)}catch{E(`Invalid package version "${b}" in "${e.packageArg}".`),process.exit(1)}let M=(await v(m)).resolve(),N=M.packageManager;if(M.nodeModulesCompatible||(n.error(M.incompatibilityReason),process.exit(1)),e.from){let t=I(e.from);C=t;let r=await maybeBuildSource(t,{build:e.build,skipBuild:e.skipBuild,yes:e.yes??!1});D=r.buildCmd,k=r.ran,A=r.skipped,n.info(`Publishing from ${t}...`),await a(t)}let P=b?await r(y,b):await i(y);if(!P){let e=b?`@${b}`:``;E(`Package "${y}${e}" not found in store. Run 'knarr publish' in the package directory first, or use --from <path>.`),process.exit(1)}await g(_(m))||(await x(m,N),n.success(`Auto-initialized knarr (consumer mode)`)),n.info(`Detected package manager: ${N}`);let F=await d(m,y);F&&(F.version===P.version?n.info(`Updating ${y}@${P.version} (already linked)`):n.info(`Updating ${y}: ${F.version} -> ${P.version}`));let L=F?F.backupExists:await l(m,y,N);!F&&L&&n.info(`Backed up existing ${y} installation`),await p(m,y,P.version),await configureBundler(m,y,M),await handleMissingDeps(P,m,M,e.yes??!1);let R=await c(P,m,N);n.success(`Linked ${y}@${P.version} -> node_modules/${y} (${R.copied} files copied, ${R.skipped} unchanged)`),R.binLinks>0&&n.info(`Created ${R.binLinks} bin link(s)`);let z={version:P.version,contentHash:P.meta.contentHash,linkedAt:(/* @__PURE__ */ new Date()).toISOString(),sourcePath:P.meta.sourcePath,backupExists:L,packageManager:N,buildId:P.meta.buildId??``};await f(m,y,z),await u(y,m),await S(m),await o(m,y)||n.info(`${y} isn't in package.json, so adding or removing other packages can prune it. Run \`knarr restore\` afterwards, or add it to dependencies.`);let B=C?[`cd ${C} && knarr dev`]:[];C&&n.info(`Next: ${t(C,process.cwd(),await workspaceRootFor(C))}`),n.info(`Done in ${s.elapsed()}`);let V={package:y,version:P.version,copied:R.copied,skipped:R.skipped,binLinks:R.binLinks,elapsed:s.elapsedMs(),buildCmd:D,buildRan:k,buildSkipped:A,nextSteps:B};return e.emitOutput!==!1&&T(V),O()&&j(),V}async function readPackageNameFromSource(e){let t=I(e);await g(t)||(E(`Source path not found: ${t}`),process.exit(1));let n=F(t,`package.json`);await g(n)||(E(`No package.json found at ${n}. Pass a package directory to 'knarr use'.`),process.exit(1));let r;try{r=M(await N(n,`utf-8`))}catch(e){E(`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`||(E(`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{E(`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 v(e)).resolve().packageManager;r=await y(e,t)??void 0}if(!r)return{buildCmd:null,ran:!1,skipped:!1};if(!i&&!t.yes&&!k()){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&&k()&&!t.yes)return D(`[add] Detected build command but skipping in json mode: ${r}`),{buildCmd:r,ran:!1,skipped:!0};return n.info(O()?`[dry-run] Would run build command: ${r}`:`Running build command: ${r}`),await runShellCommand(r,e)||(E(`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-D4vhzpO4.mjs`),r=await t(e);if(!r)return null;let i=await n(r),a=I(e);return i.some(e=>I(e)===a)?r:null}async function explainBuildFailure(e){if(!await g(F(e,`node_modules`))){let t=(await v(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(k())D(`[add] Missing transitive deps (json mode): ${o.join(`, `)}`);else if(i){let e=r.installCommand(o),t=r.formatCommand(e);n.info(O()?`[dry-run] Would install missing dependencies: ${o.join(`, `)}`:`Installing missing dependencies: ${o.join(`, `)}`);let i=await r.run(e);i&&!O()?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&&!O()?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 b(e);if(i.type===`next`&&i.configFile){let e=await C(i.configFile,t);e.modified?n.success(`Added ${t} to transpilePackages in ${P(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-CbYEhn5K.mjs`),t=await e(i.configFile);if(t.modified){n.success(`Added knarr plugin to ${P(i.configFile)}`);let e=r.installCommand([`knarr`],{dev:!0}),t=r.formatCommand(e);n.info(O()?`[dry-run] Would install knarr as devDependency`:`Installing knarr as devDependency...`);let a=await r.run(e);a&&!O()?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-Cgva0Hte.mjs`),s=await a(e);if(s){let r=await o(s,t,e);r.modified?n.success(`Added @source for ${t} to ${P(s)}`):r.error&&n.info(`Add to your CSS manually: @source "../node_modules/${t}";`)}}function runShellCommand(t,n){return O()?(A({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 +0,0 @@
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"./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};
@@ -1,11 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
2
- // src/utils/bell.ts
3
- var bell_exports = /* @__PURE__ */ __exportAll({ ringBell: () => ringBell });
4
- /**
5
- * Ring the terminal bell (BEL character).
6
- * Writes to stderr so it doesn't interfere with --json output on stdout.
7
- */
8
- function ringBell(enabled) {
9
- if (enabled) process.stderr.write("\x07");
10
- }
11
- export { ringBell as n, bell_exports as t };
@@ -1,3 +0,0 @@
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";function ringBell(e){e&&process.stderr.write(`\x07`)}export{ringBell as t};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
- export{t as ringBell}from"./bell-CIzHg0kw.mjs";
@@ -1,3 +0,0 @@
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{l as e,s as t}from"./json-CWzEb9Rt.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=e(await t(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 +0,0 @@
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}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};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
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{t}from"./dist-CFkjiIqD.mjs";import{n,t as r}from"./console-X31Y_QS5.mjs";import{t as i}from"./preflight-B17VQJs0.mjs";import{n as a,t as o}from"./output-BxyRer_F.mjs";import{resolve as s}from"node:path";var c=/* @__PURE__ */ e(n(),1),l=t({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}){a();let t=s(e.dir||`.`),n=await i(t);if(n.length===0){r.success(`All pre-flight checks passed`),o({issues:[],passed:!0});return}let l=n.filter(e=>e.severity===`error`),u=n.filter(e=>e.severity===`warn`);r.info(`Found ${n.length} issue(s):\n`);for(let e of l)r.log(` ${c.default.red(`ERROR`)} ${c.default.dim(`[${e.code}]`)} ${e.message}`);for(let e of u)r.log(` ${c.default.yellow(`WARN`)} ${c.default.dim(`[${e.code}]`)} ${e.message}`);l.length>0?r.error(`\n${l.length} error(s), ${u.length} warning(s)`):r.warn(`\n${u.length} warning(s)`),o({issues:n,passed:l.length===0})}});export{l as default};