@kaynooo/cli-pkg 0.18.1 → 0.19.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.
@@ -0,0 +1,7 @@
1
+ // @bun
2
+ import{bo,isInteractive,userConfigPath,ok,note,warn,problem,formatDuration,formatElapsed,wholeNumber,duration,Exit,fail,parse}from"./chunk-0eb0ncqy.js";import{runCommand,liveRegion,stateHome,workspaceRoot}from"./chunk-4pzedt0v.js";import{checklist2,confirm2}from"./chunk-p2jx0wx5.js";import{findConsumers,similarDependencies,isLocal,wantedVersion,RANGE_PREFIX,addCommand}from"./chunk-apxff06c.js";import{EXACT_VERSION,isValidName,fetchPackument,registryFor,loadConfigs,loadSettings}from"./chunk-m8t5jkn0.js";import{checkPackage2}from"./chunk-6eg316z7.js";import{existsSync as existsSync2}from"fs";import{basename,dirname as dirname2,join as join2,relative}from"path";import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";function excludedPath(home){let base=home===void 0?stateHome():join(home,".local","state");return join(base,"kaynooo-cli","pkg-excluded.json")}function readExcludedFile(path){try{let raw=Bun.JSONC.parse(readFileSync(path,"utf8"));if(typeof raw!=="object"||raw===null||Array.isArray(raw))return;let excluded={};for(let[name,dirs]of Object.entries(raw))if(Array.isArray(dirs))excluded[name]=dirs.filter((dir)=>typeof dir==="string");return excluded}catch{return}}function loadExcluded(home){let path=excludedPath(home);if(existsSync(path))return readExcludedFile(path);let legacy=userConfigPath("pkg-excluded",{home});return existsSync(legacy)?readExcludedFile(legacy):{}}function saveExcluded(name,dirs,home){let path=excludedPath(home),excluded=loadExcluded(home);if(excluded===void 0)return;if(dirs.length===0)delete excluded[name];else excluded[name]=[...dirs].toSorted();mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,`${JSON.stringify(excluded,null,2)}
3
+ `)}var usage="pkg bump <name> [version]\n\nWaits until the registry serves the version, vets it as `pkg check` does, then runs `bun add --exact --no-cache` in each folder under --root whose package.json depends on the package, the kind of dependency kept; a version the vetting blocks is refused before any folder is touched, unless --force is given.\nA dependency that is not a registry version (`workspace:`, `link:`, `file:`, git, a URL, `catalog:`), a peer range, a folder already on the version and one whose lockfile pins another manager are left as they are, each said so.\nOn a terminal with no --only or --except, a checklist asks which consumers to bump, then the plan is printed and confirmed.\nWith --all-consumers, a folder with uncommitted changes in its package.json or lockfile is left alone, and each folder whose install went through runs its own `check` and is committed with `gc` only when that passes; nothing is ever pushed.",EXITS=[[0,"every install ran or was left as it is (with --all-consumers, and every check passed and every commit landed)"],[1,"the vetting refuses the version, an install, a check or a commit fails or the registry has no such package"],[2,"the version never shows within the timeout (a registry that cannot be reached is retried until then) or a usage error"]],ROOT_OPTION2={type:"string",description:"the folder holding the repositories (the workspace of the user config or KAYNOOO_WORKSPACE, ~/Workspace by default)"},options={root:ROOT_OPTION2,timeout:{type:"string",short:"t",description:"how long to wait for the registry (10m): 30s, 5m, 1h"},"all-consumers":{type:"boolean",description:"after each install run the folder's check and commit it through gc when it passes"},only:{type:"string",multiple:!0,description:"bump only the folders matching this name or glob, repeatable"},except:{type:"string",multiple:!0,description:"leave the folders matching this name or glob alone, repeatable"},"dry-run":{type:"boolean",description:"print what would run, changing nothing"},yes:{type:"boolean",short:"y",description:"on a terminal, bump every consumer without the checklist and the confirmation"},force:{type:"boolean",description:"bump even when the version is blocked by the vetting"},"min-age":{type:"string",description:"days a version must be old (0: a bump adopts a release on purpose, often one just made)"}},POLL=5000;async function lookup(name,registry,fetcher){try{return{packument:await fetchPackument(name,registry,fetcher)}}catch(error){if(error instanceof Exit&&error.code===2)return{error:error.message};throw error}}async function servedVersion(name,version,settings){if(!isValidName(name))fail(`${name} is not a valid npm package name`);if(version!==void 0&&!EXACT_VERSION.test(version))fail(`bump takes an exact version, not ${version}: leave it out for the latest`);let registry=registryFor(name,settings.configs),host=new URL(registry.url).host,started=Date.now(),region=liveRegion((spinner)=>[`${spinner} waiting for ${host} to serve ${name}@${version??"latest"} ${formatElapsed(Date.now()-started)}`]),lastError="";try{for(;;){let looked=await lookup(name,registry,settings.fetcher);if("error"in looked)lastError=looked.error;else{let latest=looked.packument?.["dist-tags"]?.latest;if(looked.packument===void 0)fail(`${host} has no ${name}`,1);if(version===void 0&&latest===void 0)fail(`${host} has no ${name}`,1);if(version===void 0&&latest!==void 0)return latest;if(version!==void 0&&looked.packument.versions?.[version]!==void 0)return version}if(Date.now()-started>=settings.timeout)fail(`${host} does not serve ${name}@${version??"latest"} after ${formatDuration(settings.timeout)}${lastError===""?"":`, last error: ${lastError}`}`);region.redraw(),await Bun.sleep(settings.poll??POLL)}}finally{region.stop()}}async function vet(name,version,settings){if(settings.isForced===!0)return!0;let report=await checkPackage2(`${name}@${version}`,{configs:settings.configs,fetcher:settings.fetcher,minAgeDays:settings.minAgeDays??0,settings:settings.pkgSettings});if(!report.blocked){for(let warning of report.warnings)warn(`${name}@${version}`,warning);return!0}for(let warning of report.warnings)problem(`${name}@${version} is refused`,warning);return problem(`${name}@${version} is refused`,"no consumer was touched, --force bumps it anyway"),!1}function lockfileOf(dir,root){for(let at=dir;;at=dirname2(at)){let found=["bun.lock","bun.lockb","pnpm-lock.yaml","yarn.lock","package-lock.json"].find((file)=>existsSync2(join2(at,file)));if(found!==void 0)return relative(dir,join2(at,found));if(at===root||at===dirname2(at))return}}async function hasUncommittedChanges(where,root,run){let lockfile=lockfileOf(where,root),status=await run(["git","status","--porcelain","--","package.json",...lockfile===void 0?[]:[lockfile]],where);return status.code===0&&status.text.trim()!==""}async function checkAndCommit(name,version,where,root,run){let checked=await run(["check"],where);if(checked.code!==0)return`check exited ${checked.code}: ${checked.text.trim().split(`
4
+ `).at(-1)??""}`;let lockfile=lockfileOf(where,root),committed=await run(["gc",`chore(deps): bump ${name} to ${version}`,"--","package.json",...lockfile===void 0?[]:[lockfile]],where);return committed.code===0?void 0:`gc exited ${committed.code}: ${committed.text.trim().split(`
5
+ `).at(-1)??""}`}function matcher(patterns){let globs=patterns.map((pattern)=>new Bun.Glob(pattern));return(dir)=>globs.some((glob)=>glob.match(dir)||glob.match(basename(dir)))}async function bumpConsumers(name,version,settings){let everyone=findConsumers(name,settings.root),isOnly=matcher(settings.only??[]),isExcept=matcher(settings.except??[]),declined=new Set(settings.declined??[]),found=everyone.filter((each)=>(settings.only===void 0||settings.only.length===0||isOnly(each.dir))&&!isExcept(each.dir)&&!declined.has(each.dir)),consumers=found.filter((each)=>!isLocal(each)),left=everyone.length-found.length-declined.size,local=found.length-consumers.length,run=settings.run??(async(argv,cwd)=>runCommand(argv,{cwd})),committed=[],failing=[],skipped=[],isClean=!0;if(everyone.length===0){let similar=similarDependencies(name,settings.root);note(`nothing under ${settings.root} depends on ${name}`,similar.length===0?void 0:`did you mean ${similar.join(", ")}`)}else if(left>0)note(`${bo(left,"folder")} left out by --only or --except`);if(declined.size>0)note(`${bo(declined.size,"folder")} left out by your choice`);if(local>0)note(`${local} non-registry dependenc${local===1?"y":"ies"} (workspace:, file:, git, URL, alias, catalog:)`,"left as they are");for(let consumer of consumers){let argv=addCommand(consumer,name,version),where=join2(settings.root,consumer.dir);if(consumer.kind==="peerDependencies")skipped.push(consumer.dir),note(consumer.dir,`peer range ${consumer.spec}, left as it is`);else if((consumer.alias===void 0?consumer.spec:wantedVersion(consumer).replace(RANGE_PREFIX,""))===version)skipped.push(consumer.dir),note(consumer.dir,`already on ${version}`);else if(settings.isDryRun===!0)note(consumer.dir,`would run ${[argv.join(" "),...settings.isAll===!0?["check",`gc 'chore(deps): bump ${name} to ${version}'`]:[]].join(", then ")}`);else if(settings.isAll===!0&&await hasUncommittedChanges(where,settings.root,run))isClean=!1,failing.push(consumer.dir),problem(consumer.dir,"package.json or its lockfile has uncommitted changes, left alone so that gc does not commit them");else{let ran=await run(argv,where);if(ran.code!==0)isClean=!1,failing.push(consumer.dir),problem(consumer.dir,`${argv.join(" ")} exited ${ran.code}: ${ran.text.trim().split(`
6
+ `).at(-1)??""}`);else if(settings.isAll!==!0)ok(consumer.dir,`${consumer.spec} -> ${version}`);else{let failure=await checkAndCommit(name,version,where,settings.root,run);if(failure===void 0)committed.push(consumer.dir),ok(consumer.dir,`${consumer.spec} -> ${version}, checked and committed`);else isClean=!1,failing.push(consumer.dir),problem(consumer.dir,`${consumer.spec} -> ${version}, left uncommitted: ${failure}`)}}}if(settings.isAll===!0&&settings.isDryRun!==!0)note("summary",`${committed.length} bumped and committed, ${failing.length} bumped and failing${failing.length>0?` (${failing.join(", ")})`:""}, ${skipped.length+local} skipped`);return isClean}function plannedBumps(name,version,settings){return findConsumers(name,settings.root).filter((each)=>!isLocal(each)&&each.kind!=="peerDependencies"&&(each.alias===void 0?each.spec:wantedVersion(each).replace(RANGE_PREFIX,""))!==version).map((each)=>({dir:each.dir,line:`${each.dir} ${each.spec} -> ${version}`}))}var terminalChooser={pick:async(name,plans,excluded)=>checklist2(`bump ${name} in`,plans.map((plan)=>({value:plan.dir,label:plan.line,hint:excluded.has(plan.dir)?"left out last time":""})),{initial:new Set(plans.filter((plan)=>!excluded.has(plan.dir)).map((plan)=>plan.dir)),hint:"pass --yes to bump every consumer"}),confirm:async(question)=>confirm2(question,{default:!0,hint:"pass --yes to skip confirmation"})};async function choosePlan(name,version,settings,chooser=terminalChooser,home){let plans=plannedBumps(name,version,settings);if(plans.length===0)return;let excluded=new Set(loadExcluded(home)?.[name]??[]),picked=await chooser.pick(name,plans,excluded);if(picked===void 0)return{chosen:[],declined:plans.map((plan)=>plan.dir)};let chosen=plans.filter((plan)=>picked.has(plan.dir));for(let plan of chosen)note("plan",plan.line);if(chosen.length===0||await chooser.confirm(`bump ${name} to ${version} in ${bo(chosen.length,"folder")}?`)!==!0)return{chosen:[],declined:plans.map((plan)=>plan.dir)};let declined=plans.filter((plan)=>!picked.has(plan.dir)).map((plan)=>plan.dir);return saveExcluded(name,[...excluded].filter((dir)=>!plans.some((plan)=>plan.dir===dir)).concat(declined),home),{chosen:chosen.map((plan)=>plan.dir),declined}}async function bump2(args){let{values,positionals:[name,asked]}=parse(args,usage,options,{exits:EXITS,positionals:["<name>","[version]"]}),settings={root:workspaceRoot({given:values.root}),configs:await loadConfigs(),timeout:duration(values.timeout,"timeout",600000),isDryRun:values["dry-run"]===!0,isAll:values["all-consumers"]===!0,isForced:values.force===!0,only:values.only,except:values.except,pkgSettings:await loadSettings(),minAgeDays:wholeNumber(values["min-age"],"min-age",0,0)},version=await servedVersion(name,asked,settings);if(!await vet(name,version,settings))return 1;if(settings.isDryRun!==!0&&values.yes!==!0&&isInteractive()&&(settings.only?.length??0)===0&&(settings.except?.length??0)===0){let plan=await choosePlan(name,version,settings);if(plan?.chosen.length===0)return note("nothing to bump","none chosen or not confirmed"),0;settings.declined=plan?.declined}return await bumpConsumers(name,version,settings)?0:1}
7
+ export{ROOT_OPTION2,bump2};