knarr 0.1.3 → 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.
- package/README.md +66 -107
- package/dist/add-B_xzUp5y.mjs +3 -0
- package/dist/add-flow-cvrMO_aV.mjs +5 -0
- package/dist/batch-push-DXtZxRx0.mjs +3 -0
- package/dist/build-detect-BTHh2OBm.mjs +3 -0
- package/dist/bundler-detect-Dq-QAbQj.mjs +3 -0
- package/dist/check-CbVdpTsw.mjs +3 -0
- package/dist/chokidar-BkIWf7Ix.mjs +3 -0
- package/dist/clean-CyDDqbBD.mjs +3 -0
- package/dist/cli.mjs +4 -4
- package/dist/config-BJsL6NqN.mjs +4 -0
- package/dist/console-CIiXr7ge.mjs +3 -0
- package/dist/console-CyaBcUd-.mjs +98 -0
- package/dist/dev-kqgY9NjI.mjs +3 -0
- package/dist/dist-CFkjiIqD.mjs +7 -0
- package/dist/doctor-D-S1P0UG.mjs +6 -0
- package/dist/dry-run-BkdMYSIx.mjs +3 -0
- package/dist/errors-BlOfexcH.mjs +3 -0
- package/dist/explain-9Y4SZHjC.mjs +3 -0
- package/dist/format-DRqD29u-.mjs +3 -0
- package/dist/fs-C4juVCTd.mjs +3 -0
- package/dist/fs-CPnWm9CR.mjs +3 -0
- package/dist/fs-DzsciYAL.mjs +757 -0
- package/dist/hints-Hz3V4h3A.mjs +3 -0
- package/dist/history-DRhLwzhq.mjs +3 -0
- package/dist/history-vS3w4EGu.mjs +3 -0
- package/dist/index.d.ts +249 -264
- package/dist/index.mjs +3426 -4668
- package/dist/init-TN84d5jM.mjs +4 -0
- package/dist/init-helpers-CYYWQm-P.mjs +15 -0
- package/dist/injector-nt40JxVt.mjs +3 -0
- package/dist/json-DbSkpxtr.mjs +3 -0
- package/dist/list-9hWJjw19.mjs +3 -0
- package/dist/logger-9C6B9Na8.mjs +3 -0
- package/dist/migrate-Co4qcFt6.mjs +5 -0
- package/dist/nextjs-config-BQgTWZ96.mjs +3 -0
- package/dist/nextjs-config-dUw2J6B9.mjs +4 -0
- package/dist/output-BxR2v-jn.mjs +3 -0
- package/dist/package-manager-DJ8CE0zL.mjs +13 -0
- package/dist/picomatch-B0_Pxgms.mjs +3 -0
- package/dist/preflight-BDsxR2Ct.mjs +3 -0
- package/dist/preflight-MzNjLXiy.mjs +3 -0
- package/dist/publish-C7ZUvHkE.mjs +3 -0
- package/dist/publisher-CvXTbkLP.mjs +4 -0
- package/dist/push-B5KrkILW.mjs +3 -0
- package/dist/push-engine-BpNr8qXR.mjs +3 -0
- package/dist/remove-DkOgVQMZ.mjs +3 -0
- package/dist/remove-J5tY_BFk.mjs +3 -0
- package/dist/reset-ClGouUb5.mjs +3 -0
- package/dist/restore-Bx2V59SL.mjs +3 -0
- package/dist/rollback-RPjHZWtG.mjs +3 -0
- package/dist/rolldown-runtime-BZbIAPMk.mjs +3 -0
- package/dist/shell-RQ7Hf1kp.mjs +3 -0
- package/dist/status-Rnvw6dG2.mjs +3 -0
- package/dist/store-DjPdOKqg.mjs +3 -0
- package/dist/tailwind-source-D1cUiG-t.mjs +5 -0
- package/dist/timer-DqgB175x.mjs +3 -0
- package/dist/topo-sort-DOCpHjT7.mjs +3 -0
- package/dist/topo-sort-yd4jxr_E.mjs +3 -0
- package/dist/tracker-89eW0ArT.mjs +3 -0
- package/dist/tracker-B3Fqx94J.mjs +3 -0
- package/dist/update-CAKFICZu.mjs +3 -0
- package/dist/use-CCx6J0mc.mjs +3 -0
- package/dist/vite-config-BHmawlD2.mjs +12 -0
- package/dist/vite-config-BRlYc4ni.mjs +3 -0
- package/dist/vite-plugin.d.ts +6 -5
- package/dist/vite-plugin.mjs +206 -211
- package/dist/watch-orchestrator-BfuCaZLA.mjs +3 -0
- package/dist/watcher-T123sBDg.mjs +3 -0
- package/dist/webpack-plugin.d.ts +29 -30
- package/dist/webpack-plugin.mjs +140 -138
- package/dist/workspace-CdLSxPFS.mjs +3 -0
- package/dist/workspace-DBxNrowu.mjs +3 -0
- package/dist/xxhash-wasm-D_QjdUuv.mjs +3 -0
- package/package.json +23 -31
- package/dist/add-LQ6WMCGD.mjs +0 -3
- package/dist/bell-SIN4ERLS.mjs +0 -2
- package/dist/check-7CJHAF6Y.mjs +0 -6
- package/dist/chokidar-2G63V464.mjs +0 -4
- package/dist/chunk-3SXN6MQL.mjs +0 -4
- package/dist/chunk-7GCKCCHU.mjs +0 -3
- package/dist/chunk-BH2WXCLS.mjs +0 -4
- package/dist/chunk-CBOYKBSM.mjs +0 -13
- package/dist/chunk-E3HZCU3S.mjs +0 -5
- package/dist/chunk-G7HFTV5Y.mjs +0 -3
- package/dist/chunk-HVN6HBWZ.mjs +0 -3
- package/dist/chunk-ICU4V73X.mjs +0 -3
- package/dist/chunk-IP5ROSRE.mjs +0 -3
- package/dist/chunk-J6HZHQVL.mjs +0 -3
- package/dist/chunk-K6OAYJKS.mjs +0 -6
- package/dist/chunk-KRX4JX6V.mjs +0 -4
- package/dist/chunk-KUQULMM6.mjs +0 -3
- package/dist/chunk-L7O2RSTN.mjs +0 -3
- package/dist/chunk-M3TRMEJV.mjs +0 -3
- package/dist/chunk-MN4DV2NO.mjs +0 -3
- package/dist/chunk-N3B2JO4H.mjs +0 -13
- package/dist/chunk-NGPAGRK4.mjs +0 -7
- package/dist/chunk-NV3ASN6X.mjs +0 -3
- package/dist/chunk-OQDZJP55.mjs +0 -3
- package/dist/chunk-QEH5VHRO.mjs +0 -13
- package/dist/chunk-QFHYSC3K.mjs +0 -3
- package/dist/chunk-QHNHLR6T.mjs +0 -3
- package/dist/chunk-RIHOZDFW.mjs +0 -22
- package/dist/chunk-SMR4HT6A.mjs +0 -3
- package/dist/chunk-SPHWZS5P.mjs +0 -3
- package/dist/chunk-U6O35NZ7.mjs +0 -3
- package/dist/chunk-W2MMKBWU.mjs +0 -3
- package/dist/chunk-WBTSRLB6.mjs +0 -7
- package/dist/chunk-WN3DOKIM.mjs +0 -3
- package/dist/chunk-XDWZZBCM.mjs +0 -3
- package/dist/chunk-Z5K6DFA6.mjs +0 -3
- package/dist/clean-EJIYYQZM.mjs +0 -3
- package/dist/dev-WU5KB5PJ.mjs +0 -3
- package/dist/doctor-W2G34POC.mjs +0 -6
- package/dist/explain-LZLNIMVZ.mjs +0 -5
- package/dist/fs-NU36NNEG.mjs +0 -2
- package/dist/history-MLJHRV3Q.mjs +0 -2
- package/dist/init-SNG5LBZK.mjs +0 -7
- package/dist/list-4PTHMIQ4.mjs +0 -5
- package/dist/migrate-USY26Y5R.mjs +0 -8
- package/dist/nextjs-config-T5D6LOJE.mjs +0 -2
- package/dist/preflight-IXICTR6G.mjs +0 -2
- package/dist/publish-2IH7IQV4.mjs +0 -3
- package/dist/push-W3TM2QYK.mjs +0 -3
- package/dist/remove-MVQOIN2I.mjs +0 -2
- package/dist/reset-BTOJ54MJ.mjs +0 -3
- package/dist/restore-TWOOF2BN.mjs +0 -3
- package/dist/rollback-CFYSE5YG.mjs +0 -3
- package/dist/status-3ZXM3CRH.mjs +0 -4
- package/dist/tailwind-source-HCTY2XDU.mjs +0 -5
- package/dist/topo-sort-ZNGR6D7M.mjs +0 -2
- package/dist/tracker-QAKEXYUJ.mjs +0 -2
- package/dist/update-TGGCUOOO.mjs +0 -3
- package/dist/use-4Z5KXRVR.mjs +0 -3
- package/dist/vite-config-XOGAKYGQ.mjs +0 -2
- package/dist/watch-orchestrator-6BQYU5YS.mjs +0 -3
- package/dist/watcher-ES2APFH4.mjs +0 -3
- package/dist/workspace-T6PNO4L3.mjs +0 -2
- package/dist/xxhash-wasm-I6Q3T2SL.mjs +0 -3
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { styleText } from "node:util";
|
|
2
|
+
import { createInterface } from "node:readline/promises";
|
|
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
|
+
};
|
|
21
|
+
// src/utils/console.ts
|
|
22
|
+
/** Logging level: -1=silent, 0=fatal, 1=error, 2=warn, 3=info, 4=debug */
|
|
23
|
+
let _level = 3;
|
|
24
|
+
async function prompt(message, options) {
|
|
25
|
+
if (!stdin.isTTY) return answerNonInteractive(message, options);
|
|
26
|
+
const rl = createInterface({
|
|
27
|
+
input: stdin,
|
|
28
|
+
output: stdout
|
|
29
|
+
});
|
|
30
|
+
try {
|
|
31
|
+
if (options.type === "confirm") {
|
|
32
|
+
const hint = options.initial !== false ? "Y/n" : "y/N";
|
|
33
|
+
const val = (await rl.question(`${pc.cyan("?")} ${message} ${pc.dim(`(${hint})`)} `)).trim().toLowerCase();
|
|
34
|
+
if (val === "") return options.initial !== false;
|
|
35
|
+
return val === "y" || val === "yes";
|
|
36
|
+
}
|
|
37
|
+
if (options.type === "text") {
|
|
38
|
+
const hint = options.default ? pc.dim(` (${options.default})`) : "";
|
|
39
|
+
return (await rl.question(`${pc.cyan("?")} ${message}${hint} `)).trim() || options.default || "";
|
|
40
|
+
}
|
|
41
|
+
console.log(`${pc.cyan("?")} ${message}`);
|
|
42
|
+
for (const [i, option] of options.options.entries()) console.log(` ${pc.cyan(`${i + 1}.`)} ${option.label}`);
|
|
43
|
+
const answer = await rl.question(`${pc.dim("Enter number:")} `);
|
|
44
|
+
const chosen = options.options[parseInt(answer, 10) - 1] ?? options.options[0];
|
|
45
|
+
if (!chosen) throw new Error(`No options to choose from for "${message}"`);
|
|
46
|
+
return chosen.value;
|
|
47
|
+
} finally {
|
|
48
|
+
rl.close();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Without a TTY, readline never resolves: Node drains the event loop and exits
|
|
53
|
+
* 0 mid-command, so a script or CI job "succeeds" having done nothing. Answer
|
|
54
|
+
* from the prompt's declared default instead, and fail loudly when there is no
|
|
55
|
+
* safe default (destructive confirms declare none; selects need a choice).
|
|
56
|
+
*/
|
|
57
|
+
function answerNonInteractive(message, options) {
|
|
58
|
+
if (options.type === "confirm" && options.initial !== void 0) {
|
|
59
|
+
console.error(`${pc.cyan("i")} ${message} ${pc.dim(`-> ${options.initial ? "yes" : "no"} (no interactive terminal, using default)`)}`);
|
|
60
|
+
return options.initial;
|
|
61
|
+
}
|
|
62
|
+
if (options.type === "text") return options.default ?? "";
|
|
63
|
+
console.error(`${pc.red("x")} Cannot ask "${message}": no interactive terminal (stdin is not a TTY).`);
|
|
64
|
+
console.error(`${pc.cyan("i")} ${pc.dim("Suggestion:")} ${options.type === "confirm" ? "Re-run with --yes to confirm." : options.nonInteractiveHint ?? "Pass the choice as a flag (see --help)."}`);
|
|
65
|
+
process.exit(1);
|
|
66
|
+
}
|
|
67
|
+
const consola = {
|
|
68
|
+
get level() {
|
|
69
|
+
return _level;
|
|
70
|
+
},
|
|
71
|
+
set level(n) {
|
|
72
|
+
_level = n;
|
|
73
|
+
},
|
|
74
|
+
info(msg, ...args) {
|
|
75
|
+
if (_level >= 3) console.log(pc.cyan("i"), msg, ...args);
|
|
76
|
+
},
|
|
77
|
+
success(msg, ...args) {
|
|
78
|
+
if (_level >= 3) console.log(pc.green("OK"), msg, ...args);
|
|
79
|
+
},
|
|
80
|
+
warn(msg, ...args) {
|
|
81
|
+
if (_level >= 2) console.warn(pc.yellow("!"), msg, ...args);
|
|
82
|
+
},
|
|
83
|
+
error(msg, ...args) {
|
|
84
|
+
if (_level >= 1) console.error(pc.red("x"), msg, ...args);
|
|
85
|
+
},
|
|
86
|
+
start(msg, ...args) {
|
|
87
|
+
if (_level >= 3) console.log(pc.cyan("..."), msg, ...args);
|
|
88
|
+
},
|
|
89
|
+
debug(msg, ...args) {
|
|
90
|
+
if (_level >= 4) console.debug(pc.dim("D"), msg, ...args);
|
|
91
|
+
},
|
|
92
|
+
/** Plain log (no icon) that still respects level suppression */
|
|
93
|
+
log(msg, ...args) {
|
|
94
|
+
if (_level >= 3) console.log(msg, ...args);
|
|
95
|
+
},
|
|
96
|
+
prompt
|
|
97
|
+
};
|
|
98
|
+
export { pc as n, consola 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}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,7 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
+
import{n as e}from"./rolldown-runtime-BZbIAPMk.mjs";import{parseArgs as t}from"node:util";const n=/\d/,r=[`-`,`_`,`/`,`.`];function isUppercase(e=``){if(!n.test(e))return e!==e.toLowerCase()}function splitByCase(e,t){let n=t??r,i=[];if(!e||typeof e!=`string`)return i;let a=``,o,s;for(let t of e){let e=n.includes(t);if(e===!0){i.push(a),a=``,o=void 0;continue}let r=isUppercase(t);if(s===!1){if(o===!1&&r===!0){i.push(a),a=t,o=r;continue}if(o===!0&&r===!1&&a.length>1){let e=a.at(-1);i.push(a.slice(0,Math.max(0,a.length-1))),a=e+t,o=r;continue}}a+=t,o=r,s=e}return i.push(a),i}function upperFirst(e){return e?e[0].toUpperCase()+e.slice(1):``}function lowerFirst(e){return e?e[0].toLowerCase()+e.slice(1):``}function pascalCase(e,t){return e?(Array.isArray(e)?e:splitByCase(e)).map(e=>upperFirst(t?.normalize?e.toLowerCase():e)).join(``):``}function camelCase(e,t){return lowerFirst(pascalCase(e||``,t))}function kebabCase(e,t){return e?(Array.isArray(e)?e:splitByCase(e)).map(e=>e.toLowerCase()).join(t??`-`):``}function snakeCase(e){return kebabCase(e||``,`_`)}function toArray(e){return Array.isArray(e)?e:e===void 0?[]:[e]}function formatLineColumns(e,t=``){let n=[];for(let t of e)for(let[e,r]of t.entries())n[e]=Math.max(n[e]||0,r.length);return e.map(e=>e.map((e,r)=>t+e[r===0?`padStart`:`padEnd`](n[r])).join(` `)).join(`
|
|
4
|
+
`)}function resolveValue(e){return typeof e==`function`?e():e}var CLIError=class extends Error{code;constructor(e,t){super(e),this.name=`CLIError`,this.code=t}};function parseRawArgs(e=[],n={}){let r=new Set(n.boolean||[]),i=new Set(n.string||[]),a=n.alias||{},o=n.default||{},s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let[e,t]of Object.entries(a)){let n=t;for(let t of n)s.set(e,t),c.has(t)||c.set(t,[]),c.get(t).push(e),s.set(t,e),c.has(e)||c.set(e,[]),c.get(e).push(t)}let l={};function getType(e){if(r.has(e))return`boolean`;let t=c.get(e)||[];for(let e of t)if(r.has(e))return`boolean`;return`string`}function isStringType(e){if(i.has(e))return!0;let t=c.get(e)||[];for(let e of t)if(i.has(e))return!0;return!1}let u=/* @__PURE__ */ new Set([...r,...i,...Object.keys(a),...Object.values(a).flat(),...Object.keys(o)]);for(let e of u)l[e]||(l[e]={type:getType(e),default:o[e]});for(let[e,t]of s.entries())e.length===1&&l[t]&&!l[t].short&&(l[t].short=e);let d=[],f={};for(let t=0;t<e.length;t++){let n=e[t];if(n===`--`){d.push(...e.slice(t));break}if(n.startsWith(`--no-`)){let e=n.slice(5);f[e]=!0}else d.push(n)}let p;try{p=t({args:d,options:Object.keys(l).length>0?l:void 0,allowPositionals:!0,strict:!1})}catch{p={values:{},positionals:d}}let m={_:[]};m._=p.positionals;for(let[e,t]of Object.entries(p.values)){let n=t;getType(e)===`boolean`&&typeof t==`string`?n=t!==`false`:isStringType(e)&&typeof t==`boolean`&&(n=``),m[e]=n}for(let[e]of Object.entries(f)){m[e]=!1;let t=s.get(e);t&&(m[t]=!1);let n=c.get(e);if(n)for(let e of n)m[e]=!1}for(let[e,t]of s.entries())m[e]!==void 0&&m[t]===void 0&&(m[t]=m[e]),m[t]!==void 0&&m[e]===void 0&&(m[e]=m[t]),m[e]!==m[t]&&o[t]===m[t]&&(m[t]=m[e]);return m}const i=/* @__PURE__ */ (()=>{let e=globalThis.process?.env??{};return e.NO_COLOR===`1`||e.TERM===`dumb`||e.TEST||e.CI})(),_c=(e,t=39)=>n=>i?n:`\u001B[${e}m${n}\u001B[${t}m`,a=/* @__PURE__ */ _c(1,22),o=/* @__PURE__ */ _c(36),s=/* @__PURE__ */ _c(90),c=/* @__PURE__ */ _c(4,24);function parseArgs$2(e,t){let n={boolean:[],string:[],alias:{},default:{}},r=resolveArgs(t);for(let e of r){if(e.type===`positional`)continue;e.type===`string`||e.type===`enum`?n.string.push(e.name):e.type===`boolean`&&n.boolean.push(e.name),e.default!==void 0&&(n.default[e.name]=e.default),e.alias&&(n.alias[e.name]=e.alias);let t=camelCase(e.name),r=kebabCase(e.name);if(t!==e.name||r!==e.name){let i=toArray(n.alias[e.name]||[]);t!==e.name&&!i.includes(t)&&i.push(t),r!==e.name&&!i.includes(r)&&i.push(r),i.length>0&&(n.alias[e.name]=i)}}let i=parseRawArgs(e,n),[...a]=i._,s=new Proxy(i,{get(e,t){return e[t]??e[camelCase(t)]??e[kebabCase(t)]}});for(let[,e]of r.entries())if(e.type===`positional`){let t=a.shift();if(t!==void 0)s[e.name]=t;else if(e.default===void 0&&e.required!==!1)throw new CLIError(`Missing required positional argument: ${e.name.toUpperCase()}`,`EARG`);else s[e.name]=e.default}else if(e.type===`enum`){let t=s[e.name],n=e.options||[];if(t!==void 0&&n.length>0&&!n.includes(t))throw new CLIError(`Invalid value for argument: ${o(`--${e.name}`)} (${o(t)}). Expected one of: ${n.map(e=>o(e)).join(`, `)}.`,`EARG`)}else if(e.required&&s[e.name]===void 0)throw new CLIError(`Missing required argument: --${e.name}`,`EARG`);return s}e(parseArgs$2,`parseArgs`);function resolveArgs(e){let t=[];for(let[n,r]of Object.entries(e||{}))t.push({...r,name:n,alias:toArray(r.alias)});return t}async function resolvePlugins(e){return Promise.all(e.map(e=>resolveValue(e)))}function defineCommand(e){return e}async function runCommand(e,t){let n=await resolveValue(e.args||{}),r=parseArgs$2(t.rawArgs,n),i={rawArgs:t.rawArgs,args:r,data:t.data,cmd:e},a=await resolvePlugins(e.plugins??[]),s,c;try{for(let e of a)await e.setup?.(i);typeof e.setup==`function`&&await e.setup(i);let r=await resolveValue(e.subCommands);if(r&&Object.keys(r).length>0){let i=findSubCommandIndex(t.rawArgs,n),a=t.rawArgs[i];if(a){let e=await _findSubCommand(r,a);if(!e)throw new CLIError(`Unknown command ${o(a)}`,`E_UNKNOWN_COMMAND`);await runCommand(e,{rawArgs:t.rawArgs.slice(i+1)})}else{let n=await resolveValue(e.default);if(n){if(e.run)throw new CLIError(`Cannot specify both 'run' and 'default' on the same command.`,`E_DEFAULT_CONFLICT`);let i=await _findSubCommand(r,n);if(!i)throw new CLIError(`Default sub command ${o(n)} not found in subCommands.`,`E_UNKNOWN_COMMAND`);await runCommand(i,{rawArgs:t.rawArgs})}else if(!e.run)throw new CLIError(`No command specified.`,`E_NO_COMMAND`)}}typeof e.run==`function`&&(s=await e.run(i))}catch(e){c=e}let l=[];if(typeof e.cleanup==`function`)try{await e.cleanup(i)}catch(e){l.push(e)}for(let e of[...a].reverse())try{await e.cleanup?.(i)}catch(e){l.push(e)}if(c)throw c;if(l.length===1)throw l[0];if(l.length>1)throw Error(`Multiple cleanup errors`,{cause:l});return{result:s}}async function resolveSubCommand(e,t,n){let r=await resolveValue(e.subCommands);if(r&&Object.keys(r).length>0){let n=findSubCommandIndex(t,await resolveValue(e.args||{})),i=t[n],a=await _findSubCommand(r,i);if(a)return resolveSubCommand(a,t.slice(n+1),e)}return[e,n]}async function _findSubCommand(e,t){if(t in e)return resolveValue(e[t]);for(let n of Object.values(e)){let e=await resolveValue(n),r=await resolveValue(e?.meta);if(r?.alias&&toArray(r.alias).includes(t))return e}}function findSubCommandIndex(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r===`--`)return-1;if(r.startsWith(`-`))!r.includes(`=`)&&_isValueFlag(r,t)&&n++;else return n}return-1}function _isValueFlag(e,t){let n=e.replace(/^-{1,2}/,``),r=camelCase(n);for(let[e,i]of Object.entries(t))if((i.type===`string`||i.type===`enum`)&&(r===camelCase(e)||(Array.isArray(i.alias)?i.alias:i.alias?[i.alias]:[]).includes(n)))return!0;return!1}async function showUsage(e,t){try{console.log(await renderUsage(e,t)+`
|
|
5
|
+
`)}catch(e){console.error(e)}}const l=/^no[-A-Z]/;async function renderUsage(e,t){let n=await resolveValue(e.meta||{}),r=resolveArgs(await resolveValue(e.args||{})),i=await resolveValue(t?.meta||{}),u=`${i.name?`${i.name} `:``}`+(n.name||process.argv[1]),d=[],f=[],p=[],m=[];for(let e of r)if(e.type===`positional`){let t=e.name.toUpperCase(),n=e.required!==!1&&e.default===void 0;f.push([o(t+renderValueHint(e)),renderDescription(e,n)]),m.push(n?`<${t}>`:`[${t}]`)}else{let t=e.required===!0&&e.default===void 0,n=[...(e.alias||[]).map(e=>`-${e}`),`--${e.name}`].join(`, `)+renderValueHint(e);if(d.push([o(n),renderDescription(e,t)]),e.type===`boolean`&&(e.default===!0||e.negativeDescription)&&!l.test(e.name)){let n=[...(e.alias||[]).map(e=>`--no-${e}`),`--no-${e.name}`].join(`, `);d.push([o(n),[e.negativeDescription,t?s(`(Required)`):``].filter(Boolean).join(` `)])}t&&m.push(`--${e.name}`+renderValueHint(e))}if(e.subCommands){let t=[],n=await resolveValue(e.subCommands);for(let[e,r]of Object.entries(n)){let n=await resolveValue((await resolveValue(r))?.meta);if(n?.hidden)continue;let i=toArray(n?.alias),a=[e,...i].join(`, `);p.push([o(a),n?.description||``]),t.push(e,...i)}m.push(t.join(`|`))}let h=[],g=n.version||i.version;h.push(s(`${n.description} (${u+(g?` v${g}`:``)})`),``);let _=d.length>0||f.length>0;return h.push(`${c(a(`USAGE`))} ${o(`${u}${_?` [OPTIONS]`:``} ${m.join(` `)}`)}`,``),f.length>0&&(h.push(c(a(`ARGUMENTS`)),``),h.push(formatLineColumns(f,` `)),h.push(``)),d.length>0&&(h.push(c(a(`OPTIONS`)),``),h.push(formatLineColumns(d,` `)),h.push(``)),p.length>0&&(h.push(c(a(`COMMANDS`)),``),h.push(formatLineColumns(p,` `)),h.push(``,`Use ${o(`${u} <command> --help`)} for more information about a command.`)),h.filter(e=>typeof e==`string`).join(`
|
|
6
|
+
`)}function renderValueHint(e){let t=e.valueHint?`=<${e.valueHint}>`:``,n=t||`=<${snakeCase(e.name)}>`;return!e.type||e.type===`positional`||e.type===`boolean`?t:e.type===`enum`&&e.options?.length?`=<${e.options.join(`|`)}>`:n}function renderDescription(e,t){let n=t?s(`(Required)`):``,r=e.default===void 0?``:s(`(Default: ${e.default})`);return[e.description,n,r].filter(Boolean).join(` `)}async function runMain(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||showUsage;try{let t=await _resolveBuiltinFlags(e);if(t.help.length>0&&n.some(e=>t.help.includes(e)))await r(...await resolveSubCommand(e,n)),process.exit(0);else if(n.length===1&&t.version.includes(n[0])){let t=typeof e.meta==`function`?await e.meta():await e.meta;if(!t?.version)throw new CLIError(`No version specified`,`E_NO_VERSION`);console.log(t.version)}else await runCommand(e,{rawArgs:n})}catch(t){t instanceof CLIError?(await r(...await resolveSubCommand(e,n)),console.error(t.message)):console.error(t,`
|
|
7
|
+
`),process.exit(1)}}async function _resolveBuiltinFlags(e){let t=await resolveValue(e.args||{}),n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set;for(let[e,i]of Object.entries(t)){n.add(e);for(let e of toArray(i.alias))r.add(e)}return{help:_getBuiltinFlags(`help`,`h`,n,r),version:_getBuiltinFlags(`version`,`v`,n,r)}}function _getBuiltinFlags(e,t,n,r){return n.has(e)||r.has(e)?[]:n.has(t)||r.has(t)?[`--${e}`]:[`--${e}`,`-${t}`]}export{runMain as n,defineCommand as t};
|
|
@@ -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};
|
|
@@ -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{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};
|
|
@@ -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";function formatBytes(e){if(e===0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1),r=e/1024**n;return n===0?`${e} B`:`${r.toFixed(1)} ${t[n]}`}export{formatBytes 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{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};
|