uptide 0.4.0 → 0.5.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.
@@ -4,4 +4,4 @@ const require = __uptideCreateRequire(import.meta.url);
4
4
  const __filename = __uptideFileURLToPath(import.meta.url);
5
5
  const __dirname = __uptideFileURLToPath(new URL('.', import.meta.url));
6
6
  import{execFileSync}from"child_process";import{readFileSync}from"fs";import{dirname,join,resolve}from"path";import{fileURLToPath}from"url";import{execFileSync as execFileSync2,spawn}from"child_process";import{existsSync,mkdirSync,realpathSync}from"fs";import{tmpdir}from"os";import{dirname as dirname2,join as join2,relative,resolve as resolve2}from"path";var NoTypesError=class extends Error{constructor(packageName,version2){super(`${packageName}@${version2}: no type declarations, cannot analyze`),this.packageName=packageName,this.version=version2}packageName;version;code="NO_TYPES";name="NoTypesError"},PackageNotFoundError=class extends Error{constructor(packageName,registry){super(`${packageName}: not found on ${registry}`),this.packageName=packageName,this.registry=registry}packageName;registry;code="PACKAGE_NOT_FOUND";name="PackageNotFoundError"},RegistryAuthError=class extends Error{constructor(packageName,registry,status){super(`${packageName}: ${registry} answered HTTP ${status} (registry auth)`),this.packageName=packageName,this.registry=registry,this.status=status}packageName;registry;status;code="REGISTRY_AUTH";name="RegistryAuthError"},VersionNotFoundError=class extends Error{constructor(packageName,version2,available){super(`${packageName}@${version2}: version not published (${available.length} versions available)`),this.packageName=packageName,this.version=version2,this.available=available}packageName;version;available;code="VERSION_NOT_FOUND";name="VersionNotFoundError"},IntegrityError=class extends Error{constructor(packageName,version2,expected,actual){super(`${packageName}@${version2}: tarball integrity mismatch (expected ${expected}, got ${actual})`),this.packageName=packageName,this.version=version2,this.expected=expected,this.actual=actual}packageName;version;expected;actual;name="IntegrityError"},AdapterCapabilityError=class extends Error{constructor(adapter,capability){super(`adapter "${adapter}" does not implement ${capability}; cannot check usages`),this.adapter=adapter,this.capability=capability}adapter;capability;name="AdapterCapabilityError"},UptideError=class extends Error{constructor(code,message,options){super(message,options),this.code=code}code;name="UptideError"};function errorCode(error){return error&&typeof error=="object"&&"code"in error&&typeof error.code=="string"?error.code:"ANALYSIS_FAILED"}var version="0.1.0";function dirtyLines(porcelain){return porcelain.split(`
7
- `).filter(line=>line.trim()!=="").filter(line=>!/(?:^|\/)tsup\.config\.bundled_[\w-]+\.[cm]?js$/.test(line.slice(3)))}function uptideVersionInfo(env=process.env){return{uptideVersion:version,uptideCommit:"e6aa05d5c9e57653d6f68588a69807fc84fee8b0",uptideDirty:!1}}function uptideCommand(cliVersion){let tag=/^\d+\.\d+\.\d+-([a-z]+)/.exec(cliVersion)?.[1];return tag?`npx uptide@${tag}`:"npx uptide"}var UPTIDE_COMMAND=uptideCommand("0.4.0");function noHooksDir(){let dir=join2(tmpdir(),"uptide-no-hooks");return mkdirSync(dir,{recursive:!0}),dir}function quietEnv(){return{CI:"true",npm_config_ignore_scripts:"true",npm_config_enable_pre_post_scripts:"false",npm_config_verify_deps_before_run:"false",pnpm_config_ignore_scripts:"true",pnpm_config_enable_pre_post_scripts:"false",pnpm_config_verify_deps_before_run:"false",YARN_ENABLE_SCRIPTS:"false",YARN_ENABLE_TELEMETRY:"0",SKIP_SIMPLE_GIT_HOOKS:"1",HUSKY:"0",LEFTHOOK:"0",GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.hooksPath",GIT_CONFIG_VALUE_0:noHooksDir()}}function git(cwd,...args){return execFileSync2("git",["-c","core.hooksPath=/dev/null",...args],{cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}function command(cwd,bin,args,timeoutMs=12e4,extraEnv={}){return new Promise(resolve3=>{let output="",timeout=!1,child=spawn(bin,args,{cwd,detached:process.platform!=="win32",env:{...Object.fromEntries(Object.entries(process.env).filter(([key])=>!/(?:TOKEN|SECRET|API_KEY|PASSWORD)/i.test(key))),...quietEnv(),...extraEnv},stdio:["ignore","pipe","pipe"]}),append=data=>{output=(output+data.toString()).slice(-2e5)};child.stdout.on("data",append),child.stderr.on("data",append);let timer=setTimeout(()=>{timeout=!0;try{process.platform!=="win32"&&child.pid?process.kill(-child.pid,"SIGKILL"):child.kill("SIGKILL")}catch{}},timeoutMs);child.on("error",e=>{clearTimeout(timer),resolve3({code:1,output:String(e),timeout:!1})}),child.on("close",code=>{clearTimeout(timer),resolve3({code:code??1,output,timeout})})})}function projectRoot(cwd){let root=realpathSync(resolve2(cwd)),top=realpathSync(git(root,"rev-parse","--show-toplevel"));if(!existsSync(join2(root,"package.json")))throw new UptideError("NOT_REPOSITORY_ROOT",`${root}: no package.json; run fix at the project root`);for(let dir=dirname2(root);dir.startsWith(top)&&dir!==root;dir=dirname2(dir)){if(existsSync(join2(dir,"package.json")))throw new UptideError("NOT_REPOSITORY_ROOT",`run fix at the project root, ${dir} (workspace versions are upgraded together)`);if(dir===top)break}return{root,top,project:relative(top,root)||"."}}export{NoTypesError,PackageNotFoundError,RegistryAuthError,VersionNotFoundError,IntegrityError,AdapterCapabilityError,UptideError,errorCode,uptideVersionInfo,uptideCommand,UPTIDE_COMMAND,git,command,projectRoot};
7
+ `).filter(line=>line.trim()!=="").filter(line=>!/(?:^|\/)tsup\.config\.bundled_[\w-]+\.[cm]?js$/.test(line.slice(3)))}function uptideVersionInfo(env=process.env){return{uptideVersion:version,uptideCommit:"7619165baf0164dc59a63c209a69fe9a1abb3f22",uptideDirty:!1}}function uptideCommand(cliVersion){let tag=/^\d+\.\d+\.\d+-([a-z]+)/.exec(cliVersion)?.[1];return tag?`npx uptide@${tag}`:"npx uptide"}var UPTIDE_COMMAND=uptideCommand("0.5.0");function noHooksDir(){let dir=join2(tmpdir(),"uptide-no-hooks");return mkdirSync(dir,{recursive:!0}),dir}function quietEnv(){return{CI:"true",npm_config_ignore_scripts:"true",npm_config_enable_pre_post_scripts:"false",npm_config_verify_deps_before_run:"false",pnpm_config_ignore_scripts:"true",pnpm_config_enable_pre_post_scripts:"false",pnpm_config_verify_deps_before_run:"false",YARN_ENABLE_SCRIPTS:"false",YARN_ENABLE_TELEMETRY:"0",SKIP_SIMPLE_GIT_HOOKS:"1",HUSKY:"0",LEFTHOOK:"0",GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.hooksPath",GIT_CONFIG_VALUE_0:noHooksDir()}}function git(cwd,...args){return execFileSync2("git",["-c","core.hooksPath=/dev/null",...args],{cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}function command(cwd,bin,args,timeoutMs=12e4,extraEnv={}){return new Promise(resolve3=>{let output="",timeout=!1,child=spawn(bin,args,{cwd,detached:process.platform!=="win32",env:{...Object.fromEntries(Object.entries(process.env).filter(([key])=>!/(?:TOKEN|SECRET|API_KEY|PASSWORD)/i.test(key))),...quietEnv(),...extraEnv},stdio:["ignore","pipe","pipe"]}),append=data=>{output=(output+data.toString()).slice(-2e5)};child.stdout.on("data",append),child.stderr.on("data",append);let timer=setTimeout(()=>{timeout=!0;try{process.platform!=="win32"&&child.pid?process.kill(-child.pid,"SIGKILL"):child.kill("SIGKILL")}catch{}},timeoutMs);child.on("error",e=>{clearTimeout(timer),resolve3({code:1,output:String(e),timeout:!1})}),child.on("close",code=>{clearTimeout(timer),resolve3({code:code??1,output,timeout})})})}function projectRoot(cwd){let root=realpathSync(resolve2(cwd)),top=realpathSync(git(root,"rev-parse","--show-toplevel"));if(!existsSync(join2(root,"package.json")))throw new UptideError("NOT_REPOSITORY_ROOT",`${root}: no package.json; run fix at the project root`);for(let dir=dirname2(root);dir.startsWith(top)&&dir!==root;dir=dirname2(dir)){if(existsSync(join2(dir,"package.json")))throw new UptideError("NOT_REPOSITORY_ROOT",`run fix at the project root, ${dir} (workspace versions are upgraded together)`);if(dir===top)break}return{root,top,project:relative(top,root)||"."}}export{NoTypesError,PackageNotFoundError,RegistryAuthError,VersionNotFoundError,IntegrityError,AdapterCapabilityError,UptideError,errorCode,uptideVersionInfo,uptideCommand,UPTIDE_COMMAND,git,command,projectRoot};
@@ -3,4 +3,4 @@ import { fileURLToPath as __uptideFileURLToPath } from 'node:url';
3
3
  const require = __uptideCreateRequire(import.meta.url);
4
4
  const __filename = __uptideFileURLToPath(import.meta.url);
5
5
  const __dirname = __uptideFileURLToPath(new URL('.', import.meta.url));
6
- import{explain,runJob}from"./chunk-AGUD7WFB.js";import"./chunk-2QJIOZA7.js";import"./chunk-GHXBU767.js";import"./chunk-VHIIYAJM.js";import{errorCode}from"./chunk-W74OVIU4.js";import"./chunk-JHZ22Y6X.js";import"./chunk-Z5YHBDVG.js";import{parentPort,workerData}from"worker_threads";runJob(workerData,event=>parentPort?.postMessage({type:"progress",event})).then(value=>parentPort?.postMessage({ok:!0,value}),err=>parentPort?.postMessage({ok:!1,message:explain(err),code:errorCode(err)}));
6
+ import{explain,runJob}from"./chunk-CXWIS6QF.js";import"./chunk-HW7GXSSE.js";import"./chunk-GHXBU767.js";import"./chunk-H55HNL33.js";import{errorCode}from"./chunk-RPK3NKP7.js";import"./chunk-JHZ22Y6X.js";import"./chunk-Z5YHBDVG.js";import{parentPort,workerData}from"worker_threads";runJob(workerData,event=>parentPort?.postMessage({type:"progress",event})).then(value=>parentPort?.postMessage({ok:!0,value}),err=>parentPort?.postMessage({ok:!1,message:explain(err),code:errorCode(err)}));
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import { fileURLToPath as __uptideFileURLToPath } from 'node:url';
4
4
  const require = __uptideCreateRequire(import.meta.url);
5
5
  const __filename = __uptideFileURLToPath(import.meta.url);
6
6
  const __dirname = __uptideFileURLToPath(new URL('.', import.meta.url));
7
- import{BUILD_HOST,BUILD_KEY,COMMANDS,NAME_PATTERN,VERSION_PATTERN,atomicJson,buildEvent,captureUrl,enabled,identity,isCi,readSettings,sanitizeEvent,settingsPath}from"./chunk-S5MVBT7A.js";import{ACCEPTED_KEYS,CliError,EXIT,INVOCATION,PRICE_DATE,VERSION,cleanRuns,depthOf,explain,fixPreflight,foldForDisplay,listDependencies,openPr,priceFor,renderError,require_picocolors,runJob,runnable,selectLlm,updatePrBody}from"./chunk-AGUD7WFB.js";import{BY,TIER_LEGEND,buildToolMajor,compareVersions,createNpmFetcher,defaultCacheDir,diffPackage,formatFix,isFailure,isNativeProbeSkip,majorsBehind,migrationBody,planPackage,summaryCells,typescriptAdapter,verdictOf,workerHeapMb}from"./chunk-2QJIOZA7.js";import"./chunk-GHXBU767.js";import{publishTarget}from"./chunk-VHIIYAJM.js";import{UptideError,errorCode}from"./chunk-W74OVIU4.js";import"./chunk-JHZ22Y6X.js";import{__toESM}from"./chunk-Z5YHBDVG.js";import{readFileSync as readFileSync7}from"fs";import{basename as basename5,resolve as resolve7}from"path";var CommanderError=class extends Error{constructor(exitCode,code,message){super(message),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=code,this.exitCode=exitCode,this.nestedError=void 0}},InvalidArgumentError=class extends CommanderError{constructor(message){super(1,"commander.invalidArgument",message),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Argument=class{constructor(name,description){switch(this.description=description||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,name[0]){case"<":this.required=!0,this._name=name.slice(1,-1);break;case"[":this.required=!1,this._name=name.slice(1,-1);break;default:this.required=!0,this._name=name;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(value,previous){return previous===this.defaultValue||!Array.isArray(previous)?[value]:(previous.push(value),previous)}default(value,description){return this.defaultValue=value,this.defaultValueDescription=description,this}argParser(fn){return this.parseArg=fn,this}choices(values){return this.argChoices=values.slice(),this.parseArg=(arg,previous)=>{if(!this.argChoices.includes(arg))throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(arg,previous):arg},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function humanReadableArgName(arg){let nameOutput=arg.name()+(arg.variadic===!0?"...":"");return arg.required?"<"+nameOutput+">":"["+nameOutput+"]"}import{EventEmitter}from"events";import childProcess from"child_process";import path from"path";import fs from"fs";import process2 from"process";import{stripVTControlCharacters as stripVTControlCharacters2}from"util";import{stripVTControlCharacters}from"util";var Help=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(contextOptions){this.helpWidth=this.helpWidth??contextOptions.helpWidth??80}visibleCommands(cmd){let visibleCommands=cmd.commands.filter(cmd2=>!cmd2._hidden),helpCommand=cmd._getHelpCommand();return helpCommand&&!helpCommand._hidden&&visibleCommands.push(helpCommand),this.sortSubcommands&&visibleCommands.sort((a,b)=>a.name().localeCompare(b.name())),visibleCommands}compareOptions(a,b){let getSortKey=option=>option.short?option.short.replace(/^-/,""):option.long.replace(/^--/,"");return getSortKey(a).localeCompare(getSortKey(b))}visibleOptions(cmd){let visibleOptions=cmd.options.filter(option=>!option.hidden),helpOption=cmd._getHelpOption();if(helpOption&&!helpOption.hidden){let removeShort=helpOption.short&&cmd._findOption(helpOption.short),removeLong=helpOption.long&&cmd._findOption(helpOption.long);!removeShort&&!removeLong?visibleOptions.push(helpOption):helpOption.long&&!removeLong?visibleOptions.push(cmd.createOption(helpOption.long,helpOption.description)):helpOption.short&&!removeShort&&visibleOptions.push(cmd.createOption(helpOption.short,helpOption.description))}return this.sortOptions&&visibleOptions.sort(this.compareOptions),visibleOptions}visibleGlobalOptions(cmd){if(!this.showGlobalOptions)return[];let globalOptions=[];for(let ancestorCmd=cmd.parent;ancestorCmd;ancestorCmd=ancestorCmd.parent){let visibleOptions=ancestorCmd.options.filter(option=>!option.hidden);globalOptions.push(...visibleOptions)}return this.sortOptions&&globalOptions.sort(this.compareOptions),globalOptions}visibleArguments(cmd){return cmd._argsDescription&&cmd.registeredArguments.forEach(argument=>{argument.description=argument.description||cmd._argsDescription[argument.name()]||""}),cmd.registeredArguments.find(argument=>argument.description)?cmd.registeredArguments:[]}subcommandTerm(cmd){let args=cmd.registeredArguments.map(arg=>humanReadableArgName(arg)).join(" ");return cmd._name+(cmd._aliases[0]?"|"+cmd._aliases[0]:"")+(cmd.options.length?" [options]":"")+(args?" "+args:"")}optionTerm(option){return option.flags}argumentTerm(argument){return argument.name()}longestSubcommandTermLength(cmd,helper){return helper.visibleCommands(cmd).reduce((max,command)=>Math.max(max,this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command)))),0)}longestOptionTermLength(cmd,helper){return helper.visibleOptions(cmd).reduce((max,option)=>Math.max(max,this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))),0)}longestGlobalOptionTermLength(cmd,helper){return helper.visibleGlobalOptions(cmd).reduce((max,option)=>Math.max(max,this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))),0)}longestArgumentTermLength(cmd,helper){return helper.visibleArguments(cmd).reduce((max,argument)=>Math.max(max,this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument)))),0)}commandUsage(cmd){let cmdName=cmd._name;cmd._aliases[0]&&(cmdName=cmdName+"|"+cmd._aliases[0]);let ancestorCmdNames="";for(let ancestorCmd=cmd.parent;ancestorCmd;ancestorCmd=ancestorCmd.parent)ancestorCmdNames=ancestorCmd.name()+" "+ancestorCmdNames;return ancestorCmdNames+cmdName+" "+cmd.usage()}commandDescription(cmd){return cmd.description()}subcommandDescription(cmd){return cmd.summary()||cmd.description()}optionDescription(option){let extraInfo=[];if(option.argChoices&&extraInfo.push(`choices: ${option.argChoices.map(choice=>JSON.stringify(choice)).join(", ")}`),option.defaultValue!==void 0&&(option.required||option.optional||option.isBoolean()&&typeof option.defaultValue=="boolean")&&extraInfo.push(`default: ${option.defaultValueDescription||JSON.stringify(option.defaultValue)}`),option.presetArg!==void 0&&option.optional&&extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`),option.envVar!==void 0&&extraInfo.push(`env: ${option.envVar}`),extraInfo.length>0){let extraDescription=`(${extraInfo.join(", ")})`;return option.description?`${option.description} ${extraDescription}`:extraDescription}return option.description}argumentDescription(argument){let extraInfo=[];if(argument.argChoices&&extraInfo.push(`choices: ${argument.argChoices.map(choice=>JSON.stringify(choice)).join(", ")}`),argument.defaultValue!==void 0&&extraInfo.push(`default: ${argument.defaultValueDescription||JSON.stringify(argument.defaultValue)}`),extraInfo.length>0){let extraDescription=`(${extraInfo.join(", ")})`;return argument.description?`${argument.description} ${extraDescription}`:extraDescription}return argument.description}formatItemList(heading,items,helper){return items.length===0?[]:[helper.styleTitle(heading),...items,""]}groupItems(unsortedItems,visibleItems,getGroup){let result=new Map;return unsortedItems.forEach(item=>{let group=getGroup(item);result.has(group)||result.set(group,[])}),visibleItems.forEach(item=>{let group=getGroup(item);result.has(group)||result.set(group,[]),result.get(group).push(item)}),result}formatHelp(cmd,helper){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80;function callFormatItem(term,description){return helper.formatItem(term,termWidth,description,helper)}let output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));if(output=output.concat(this.formatItemList("Arguments:",argumentList,helper)),this.groupItems(cmd.options,helper.visibleOptions(cmd),option=>option.helpGroupHeading??"Options:").forEach((options,group)=>{let optionList=options.map(option=>callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));output=output.concat(this.formatItemList(group,optionList,helper))}),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));output=output.concat(this.formatItemList("Global Options:",globalOptionList,helper))}return this.groupItems(cmd.commands,helper.visibleCommands(cmd),sub=>sub.helpGroup()||"Commands:").forEach((commands,group)=>{let commandList=commands.map(sub=>callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)),helper.styleSubcommandDescription(helper.subcommandDescription(sub))));output=output.concat(this.formatItemList(group,commandList,helper))}),output.join(`
7
+ import{BUILD_HOST,BUILD_KEY,COMMANDS,NAME_PATTERN,VERSION_PATTERN,atomicJson,buildEvent,captureUrl,enabled,identity,isCi,readSettings,sanitizeEvent,settingsPath}from"./chunk-S5MVBT7A.js";import{ACCEPTED_KEYS,CliError,EXIT,INVOCATION,PRICE_DATE,VERSION,cleanRuns,depthOf,explain,fixPreflight,foldForDisplay,listDependencies,openPr,priceFor,renderError,require_picocolors,runJob,runnable,scaffoldPack,selectLlm,testPack,updatePrBody}from"./chunk-CXWIS6QF.js";import{BY,TIER_LEGEND,activePacks,buildToolMajor,compareVersions,createNpmFetcher,defaultCacheDir,diffPackage,formatFix,isFailure,isNativeProbeSkip,majorsBehind,migrationBody,planPackage,registeredPacks,summaryCells,typescriptAdapter,verdictOf,workerHeapMb}from"./chunk-HW7GXSSE.js";import"./chunk-GHXBU767.js";import{publishTarget}from"./chunk-H55HNL33.js";import{UptideError,errorCode}from"./chunk-RPK3NKP7.js";import"./chunk-JHZ22Y6X.js";import{__toESM}from"./chunk-Z5YHBDVG.js";import{readFileSync as readFileSync8}from"fs";import{basename as basename5,resolve as resolve7}from"path";var CommanderError=class extends Error{constructor(exitCode,code,message){super(message),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=code,this.exitCode=exitCode,this.nestedError=void 0}},InvalidArgumentError=class extends CommanderError{constructor(message){super(1,"commander.invalidArgument",message),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Argument=class{constructor(name,description){switch(this.description=description||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,name[0]){case"<":this.required=!0,this._name=name.slice(1,-1);break;case"[":this.required=!1,this._name=name.slice(1,-1);break;default:this.required=!0,this._name=name;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(value,previous){return previous===this.defaultValue||!Array.isArray(previous)?[value]:(previous.push(value),previous)}default(value,description){return this.defaultValue=value,this.defaultValueDescription=description,this}argParser(fn){return this.parseArg=fn,this}choices(values){return this.argChoices=values.slice(),this.parseArg=(arg,previous)=>{if(!this.argChoices.includes(arg))throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(arg,previous):arg},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function humanReadableArgName(arg){let nameOutput=arg.name()+(arg.variadic===!0?"...":"");return arg.required?"<"+nameOutput+">":"["+nameOutput+"]"}import{EventEmitter}from"events";import childProcess from"child_process";import path from"path";import fs from"fs";import process2 from"process";import{stripVTControlCharacters as stripVTControlCharacters2}from"util";import{stripVTControlCharacters}from"util";var Help=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(contextOptions){this.helpWidth=this.helpWidth??contextOptions.helpWidth??80}visibleCommands(cmd){let visibleCommands=cmd.commands.filter(cmd2=>!cmd2._hidden),helpCommand=cmd._getHelpCommand();return helpCommand&&!helpCommand._hidden&&visibleCommands.push(helpCommand),this.sortSubcommands&&visibleCommands.sort((a,b)=>a.name().localeCompare(b.name())),visibleCommands}compareOptions(a,b){let getSortKey=option=>option.short?option.short.replace(/^-/,""):option.long.replace(/^--/,"");return getSortKey(a).localeCompare(getSortKey(b))}visibleOptions(cmd){let visibleOptions=cmd.options.filter(option=>!option.hidden),helpOption=cmd._getHelpOption();if(helpOption&&!helpOption.hidden){let removeShort=helpOption.short&&cmd._findOption(helpOption.short),removeLong=helpOption.long&&cmd._findOption(helpOption.long);!removeShort&&!removeLong?visibleOptions.push(helpOption):helpOption.long&&!removeLong?visibleOptions.push(cmd.createOption(helpOption.long,helpOption.description)):helpOption.short&&!removeShort&&visibleOptions.push(cmd.createOption(helpOption.short,helpOption.description))}return this.sortOptions&&visibleOptions.sort(this.compareOptions),visibleOptions}visibleGlobalOptions(cmd){if(!this.showGlobalOptions)return[];let globalOptions=[];for(let ancestorCmd=cmd.parent;ancestorCmd;ancestorCmd=ancestorCmd.parent){let visibleOptions=ancestorCmd.options.filter(option=>!option.hidden);globalOptions.push(...visibleOptions)}return this.sortOptions&&globalOptions.sort(this.compareOptions),globalOptions}visibleArguments(cmd){return cmd._argsDescription&&cmd.registeredArguments.forEach(argument=>{argument.description=argument.description||cmd._argsDescription[argument.name()]||""}),cmd.registeredArguments.find(argument=>argument.description)?cmd.registeredArguments:[]}subcommandTerm(cmd){let args=cmd.registeredArguments.map(arg=>humanReadableArgName(arg)).join(" ");return cmd._name+(cmd._aliases[0]?"|"+cmd._aliases[0]:"")+(cmd.options.length?" [options]":"")+(args?" "+args:"")}optionTerm(option){return option.flags}argumentTerm(argument){return argument.name()}longestSubcommandTermLength(cmd,helper){return helper.visibleCommands(cmd).reduce((max,command)=>Math.max(max,this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command)))),0)}longestOptionTermLength(cmd,helper){return helper.visibleOptions(cmd).reduce((max,option)=>Math.max(max,this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))),0)}longestGlobalOptionTermLength(cmd,helper){return helper.visibleGlobalOptions(cmd).reduce((max,option)=>Math.max(max,this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))),0)}longestArgumentTermLength(cmd,helper){return helper.visibleArguments(cmd).reduce((max,argument)=>Math.max(max,this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument)))),0)}commandUsage(cmd){let cmdName=cmd._name;cmd._aliases[0]&&(cmdName=cmdName+"|"+cmd._aliases[0]);let ancestorCmdNames="";for(let ancestorCmd=cmd.parent;ancestorCmd;ancestorCmd=ancestorCmd.parent)ancestorCmdNames=ancestorCmd.name()+" "+ancestorCmdNames;return ancestorCmdNames+cmdName+" "+cmd.usage()}commandDescription(cmd){return cmd.description()}subcommandDescription(cmd){return cmd.summary()||cmd.description()}optionDescription(option){let extraInfo=[];if(option.argChoices&&extraInfo.push(`choices: ${option.argChoices.map(choice=>JSON.stringify(choice)).join(", ")}`),option.defaultValue!==void 0&&(option.required||option.optional||option.isBoolean()&&typeof option.defaultValue=="boolean")&&extraInfo.push(`default: ${option.defaultValueDescription||JSON.stringify(option.defaultValue)}`),option.presetArg!==void 0&&option.optional&&extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`),option.envVar!==void 0&&extraInfo.push(`env: ${option.envVar}`),extraInfo.length>0){let extraDescription=`(${extraInfo.join(", ")})`;return option.description?`${option.description} ${extraDescription}`:extraDescription}return option.description}argumentDescription(argument){let extraInfo=[];if(argument.argChoices&&extraInfo.push(`choices: ${argument.argChoices.map(choice=>JSON.stringify(choice)).join(", ")}`),argument.defaultValue!==void 0&&extraInfo.push(`default: ${argument.defaultValueDescription||JSON.stringify(argument.defaultValue)}`),extraInfo.length>0){let extraDescription=`(${extraInfo.join(", ")})`;return argument.description?`${argument.description} ${extraDescription}`:extraDescription}return argument.description}formatItemList(heading,items,helper){return items.length===0?[]:[helper.styleTitle(heading),...items,""]}groupItems(unsortedItems,visibleItems,getGroup){let result=new Map;return unsortedItems.forEach(item=>{let group=getGroup(item);result.has(group)||result.set(group,[])}),visibleItems.forEach(item=>{let group=getGroup(item);result.has(group)||result.set(group,[]),result.get(group).push(item)}),result}formatHelp(cmd,helper){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80;function callFormatItem(term,description){return helper.formatItem(term,termWidth,description,helper)}let output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));if(output=output.concat(this.formatItemList("Arguments:",argumentList,helper)),this.groupItems(cmd.options,helper.visibleOptions(cmd),option=>option.helpGroupHeading??"Options:").forEach((options,group)=>{let optionList=options.map(option=>callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));output=output.concat(this.formatItemList(group,optionList,helper))}),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));output=output.concat(this.formatItemList("Global Options:",globalOptionList,helper))}return this.groupItems(cmd.commands,helper.visibleCommands(cmd),sub=>sub.helpGroup()||"Commands:").forEach((commands,group)=>{let commandList=commands.map(sub=>callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)),helper.styleSubcommandDescription(helper.subcommandDescription(sub))));output=output.concat(this.formatItemList(group,commandList,helper))}),output.join(`
8
8
  `)}displayWidth(str){return stripVTControlCharacters(str).length}styleTitle(str){return str}styleUsage(str){return str.split(" ").map(word=>word==="[options]"?this.styleOptionText(word):word==="[command]"?this.styleSubcommandText(word):word[0]==="["||word[0]==="<"?this.styleArgumentText(word):this.styleCommandText(word)).join(" ")}styleCommandDescription(str){return this.styleDescriptionText(str)}styleOptionDescription(str){return this.styleDescriptionText(str)}styleSubcommandDescription(str){return this.styleDescriptionText(str)}styleArgumentDescription(str){return this.styleDescriptionText(str)}styleDescriptionText(str){return str}styleOptionTerm(str){return this.styleOptionText(str)}styleSubcommandTerm(str){return str.split(" ").map(word=>word==="[options]"?this.styleOptionText(word):word[0]==="["||word[0]==="<"?this.styleArgumentText(word):this.styleSubcommandText(word)).join(" ")}styleArgumentTerm(str){return this.styleArgumentText(str)}styleOptionText(str){return str}styleArgumentText(str){return str}styleSubcommandText(str){return str}styleCommandText(str){return str}padWidth(cmd,helper){return Math.max(helper.longestOptionTermLength(cmd,helper),helper.longestGlobalOptionTermLength(cmd,helper),helper.longestSubcommandTermLength(cmd,helper),helper.longestArgumentTermLength(cmd,helper))}preformatted(str){return/\n[^\S\r\n]/.test(str)}formatItem(term,termWidth,description,helper){let itemIndentStr=" ".repeat(2);if(!description)return itemIndentStr+term;let paddedTerm=term.padEnd(termWidth+term.length-helper.displayWidth(term)),spacerWidth=2,remainingWidth=(this.helpWidth??80)-termWidth-spacerWidth-2,formattedDescription;return remainingWidth<this.minWidthToWrap||helper.preformatted(description)?formattedDescription=description:formattedDescription=helper.boxWrap(description,remainingWidth).replace(/\n/g,`
9
9
  `+" ".repeat(termWidth+spacerWidth)),itemIndentStr+paddedTerm+" ".repeat(spacerWidth)+formattedDescription.replace(/\n/g,`
10
10
  ${itemIndentStr}`)}boxWrap(str,width2){if(width2<this.minWidthToWrap)return str;let rawLines=str.split(/\r\n|\n/),chunkPattern=/[\s]*[^\s]+/g,wrappedLines=[];return rawLines.forEach(line=>{let chunks=line.match(chunkPattern);if(chunks===null){wrappedLines.push("");return}let sumChunks=[chunks.shift()],sumWidth=this.displayWidth(sumChunks[0]);chunks.forEach(chunk=>{let visibleWidth=this.displayWidth(chunk);if(sumWidth+visibleWidth<=width2){sumChunks.push(chunk),sumWidth+=visibleWidth;return}wrappedLines.push(sumChunks.join(""));let nextChunk=chunk.trimStart();sumChunks=[nextChunk],sumWidth=this.displayWidth(nextChunk)}),wrappedLines.push(sumChunks.join(""))}),wrappedLines.join(`
@@ -37,21 +37,21 @@ Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Hel
37
37
  `)[0]??"";return`${c.path}: ${concrete.length>160?`${concrete.slice(0,157)}...`:concrete}`}switch(c.kind){case"removed":return`${c.path} removed${replacement}`;case"moved":return`${c.path} moved to ${c.replacement??"another entry point"}`;case"renamed":return`${c.path} renamed${replacement}`;case"deprecated":return`${c.path} deprecated${f.reason&&f.reason!=="deprecated"?`: ${f.reason}`:""}${replacement}`;default:return f.reason.startsWith(`${c.path},`)?`${f.reason}${replacement}`:`${c.path} ${f.reason}${replacement}`}}var EVIDENCE={compiler:"your code does not compile against the target at this site",runtime:"the runtime probe loaded the target and the export is gone or changed","module-format":"a require() of a package whose target is ESM-only","removed-export":"the import of a name the target no longer exports"};function findingLines(f,mark,colors,tint){let location=`${f.usage.file}:${f.usage.line}`,first=` ${tint(mark)} ${location.padEnd(34)} ${f.usage.snippet}`,description=describeChange(f),confidence=f.confidence<1?colors.dim(` (${Math.round(f.confidence*100)}%)`):"",second=` ${description.padEnd(62)} ${colors.dim(f.fixability)}${confidence}`,lines=[first,second];f.severity==="breaking"&&f.evidence&&f.evidence!=="pack"&&lines.push(colors.dim(` evidence: ${EVIDENCE[f.evidence]}`)),f.usage.compileError&&lines.push(colors.dim(` compiler: ${f.usage.compileError.split(`
38
38
  `)[0]}`));for(let detail of f.details??[])lines.push(colors.dim(` ${detail}`));let others=(f.sites??[]).filter(s=>s.line!==f.usage.line);return others.length>0&&lines.push(colors.dim(` also at line${others.length===1?"":"s"} ${others.map(s=>s.line).join(", ")}`)),lines}function siteLines(findings,mark,colors,tint){return findings.flatMap(f=>{if(f.change.kind!=="cause")return findingLines(f,mark,colors,tint);let sites=f.downstream??[];return[` ${tint(mark)} ${f.reason} (${plural(sites.length,"site")})`,...sites.flatMap(site=>[` ${site.file}:${site.line} ${site.snippet??""}`.trimEnd(),colors.dim(` TS${site.code}: ${site.message}`)]),...(f.details??[]).map(detail=>colors.dim(` ${detail}`))]})}function packageLines(p,opts,colors){let behind=p.majorsBehind>0?` (${plural(p.majorsBehind,"major")} behind)`:"",title=p.members?`${p.name} (${plural(p.members.length,"package")})`:p.name,where=p.workspaces?colors.dim(` \xB7 ${p.source==="catalog"?"catalog \xB7 ":""}${p.workspaces.map(w=>w==="."?"root":w).join(", ")}`):"",via=p.typesVia?colors.dim(` \xB7 types via ${p.typesVia}`):"",tier=p.tier?colors.dim(` \xB7 ${p.tier}`):"",header=`${colors.bold(title)} ${p.installed} \u2192 ${p.target}${behind}${tier}${where}${via}`,lines=[];if(p.status==="no-types"){let typesIn=p.notes.find(n=>n.startsWith("types in ")),reason=typesIn?`${typesIn}, not analyzed`:p.notes.find(n=>/type declarations/.test(n))??"no type declarations, cannot analyze";return[`${colors.bold(p.name)} ${p.installed} \u2192 ${p.target} ${colors.dim(reason)}`]}if(p.status==="not-imported"||p.status==="workspace"||p.status==="private")return[];if(p.notes.includes("up to date"))return[];if(p.skipReason==="TIME_BUDGET")return[];if(p.status==="skipped")return[`${colors.bold(p.name)} ${p.installed} ${colors.dim(`skipped: ${p.notes.join("; ")||"unknown reason"}`)}`];lines.push(header);let analyzed=analyzedImporters(p);analyzed&&(p.importers?.length??0)>1&&lines.push(colors.dim(` analyzed in ${analyzed}`));for(let note of importerNotes(p))lines.push(` ${colors.yellow("\u26A0")} ${note}`);let visible=p.findings.filter(f=>f.severity!=="additive"&&f.severity!=="info"&&(opts.all||f.confidence>=.5)),breaking=visible.filter(f=>f.severity==="breaking"),unverified=visible.filter(f=>f.severity==="unverified"),deprecated=visible.filter(f=>f.severity==="deprecated"),render=siteLines,unanalyzed=p.unanalyzed.length;if(visible.length===0&&(p.status==="unknown"?lines.push(` ${colors.magenta("?")} unknown: ${unanalyzed} of ${plural(p.callSitesChecked+unanalyzed,"site")} not analyzed (require/dynamic import)`):unanalyzed>0?lines.push(` ${colors.green("\u2713")} no impact in ${plural(p.callSitesChecked,"analyzed site")} \xB7 ${colors.yellow("\u26A0")} ${plural(unanalyzed,"site")} not analyzed`):lines.push(` ${colors.green("\u2713")} no impact on your code (${plural(p.callSitesChecked,"call site")} checked)`)),breaking.length>0){let files=new Set(breaking.flatMap(f=>f.change.kind==="cause"?(f.downstream??[]).map(d=>d.file):[f.usage.file])).size,sites=breaking.reduce((n,f)=>n+(f.change.kind==="cause"?f.downstream?.length??0:1),0);lines.push("",` ${colors.red(colors.bold("BREAKING"))} ${plural(sites,"call site")} in ${plural(files,"file")}`),lines.push(...render(breaking,"\u2717",colors,colors.red))}unverified.length>0&&(lines.push("",` ${colors.magenta(colors.bold("UNVERIFIED"))} ${plural(unverified.length,"call site")} ${colors.dim(p.tier==="generic"?"(the declarations changed here; nothing confirmed that the code breaks)":"(verification incomplete)")}`),lines.push(...render(unverified,"?",colors,colors.magenta))),deprecated.length>0&&(lines.push("",` ${colors.yellow(colors.bold("DEPRECATED"))} ${plural(deprecated.length,"call site")}`),lines.push(...render(deprecated,"!",colors,colors.yellow)));let hidden=p.findings.filter(f=>f.severity!=="additive"&&(f.severity==="info"||!opts.all&&f.confidence<.5)).length;hidden>0&&lines.push(colors.dim(` ${plural(hidden,"low-confidence finding")} hidden (use --all)`));for(let r of p.runtime??[]){let who=(p.runtime?.length??0)>1?`${r.package}: `:"",unused=r.changes.filter(c=>c.key&&r.usedKeys&&!r.usedKeys.includes(c.key)),unusedKeys=new Set(unused.map(c=>c.key));for(let c of r.changes)!opts.all&&unused.includes(c)||lines.push(colors.dim(` \u2699 runtime (${r.node}): ${who}${c.detail}`));unusedKeys.size>0&&lines.push(colors.dim(` \u2699 ${who}${unusedKeys.size} unused exports removed${opts.all?"":" (use --all)"}`)),isNativeProbeSkip(r.inconclusive)?lines.push(colors.dim(` \u2699 ${who}native package, runtime probe skipped`)):r.inconclusive&&lines.push(colors.dim(` \u2699 runtime (${r.node}): ${who}inconclusive, ${r.inconclusive}`))}for(let note of p.notes)visible.length===0&&/sites? not analyzed/.test(note)||lines.push(colors.dim(` \u26A0 ${note}`));return lines}function formatCheckDetails(report,opts={}){let colors=import_picocolors2.default.createColors(opts.color??!0),lines=[],grouped=report.workspaces.length>1;for(let workspace of["*",...report.workspaces]){let blocks=report.packages.filter(p=>p.workspace===workspace).map(p=>packageLines(p,opts,colors)).filter(b=>b.length>0);if(blocks.length!==0){if(grouped){let title=workspace==="*"?"(shared across workspaces)":workspace==="."?"(root)":workspace;lines.push(colors.bold(colors.underline(title)),"")}for(let block of blocks)lines.push(...block,"")}}let privates=[...new Set(report.packages.filter(p=>p.status==="private").map(p=>p.name))].sort();privates.length>0&&lines.push(colors.dim(`${plural(privates.length,"private package")} skipped: registry auth or not on the registry (${privates.join(", ")})`),"");let s=report.summary,actionable=s.breaking+s.deprecated;return lines.push(`${colors.bold("Summary:")} ${plural(s.packagesNeedingAttention,"package")} need${s.packagesNeedingAttention===1?"s":""} attention \xB7 ${s.breaking} breaking \xB7 ${s.deprecated} deprecated${s.unverified>0?` \xB7 ${s.unverified} unverified`:""} \xB7 ${s.unaffected} unaffected${s.partiallyAnalyzed>0?` \xB7 ${s.partiallyAnalyzed} partially analyzed`:""}${s.notImported>0?` \xB7 ${s.notImported} not imported`:""}`),actionable>0&&lines.push(` ${s.autoFixable} of ${plural(actionable,"finding")} ${actionable===1?"is":"are"} mechanical`),`${lines.join(`
39
39
  `)}
40
- `}var import_picocolors3=__toESM(require_picocolors(),1);import{stripVTControlCharacters as stripVTControlCharacters3}from"util";var textWidth=text=>Array.from(stripVTControlCharacters3(text)).length,ellipsis=(text,width2)=>{let chars=Array.from(text);return chars.length<=width2?text:`${chars.slice(0,Math.max(0,width2-1)).join("")}\u2026`},NAME_CAP=45;function alignedRows(rows,width2,color,indent=0){let colors=import_picocolors3.default.createColors(color);rows=rows.map(row=>row.map((cell,column)=>{let marker=cell.alignAt;if(!marker||!cell.text.includes(marker))return cell;let before=cell.text.indexOf(marker),widest=Math.max(...rows.map(r=>{let other=r[column];return other&&other.alignAt===marker?Math.max(0,other.text.indexOf(marker)):0}));return{...cell,text:" ".repeat(widest-before)+cell.text}}));let lengths=Array.from({length:Math.max(0,...rows.map(r=>r.length))},(_,i)=>Math.max(0,...rows.map(r=>textWidth(r[i]?.span?"":r[i]?.text??""))));for(;lengths.at(-1)===0;)lengths.pop();let total=()=>lengths.reduce((a,b)=>a+b,0)+Math.max(0,lengths.length-1)*3+indent;for(lengths[0]&&(lengths[0]=Math.min(NAME_CAP,Math.max(12,lengths[0])));total()>width2&&lengths.length>2;)lengths.pop();return total()>width2&&lengths[1]&&(lengths[1]=Math.max(1,lengths[1]-(total()-width2))),rows.map(row=>{let cells=[],consumed=indent,wrapped="";for(let[i,length]of lengths.entries()){let cell=row[i],available=cell?.span?width2-consumed:length;if(i===0&&cell&&textWidth(cell.text)>length){wrapped=`${" ".repeat(indent)}${cell.tone?colors[cell.tone](cell.text):cell.text}
41
- `,cells.push(" ".repeat(length)),consumed+=length+3;continue}let text=ellipsis(cell?.text??"",Math.max(1,available)),styled=cell?.tone?colors[cell.tone](text):text;if(cells.push(styled+(cell?.span||i===lengths.length-1?"":" ".repeat(Math.max(0,length-textWidth(text))))),consumed+=length+3,cell?.span)break}return wrapped+(" ".repeat(indent)+cells.join(" ")).trimEnd()})}var terminalHeader=(command,header,color)=>{let c=import_picocolors3.default.createColors(color);return`${c.bold(`uptide ${command}`)} ${c.dim("\xB7")} ${header.repo} ${c.dim("\xB7")} ${header.manager} ${c.dim("\xB7")} ${header.ms<1e3?`${Math.round(header.ms)}ms`:`${(header.ms/1e3).toFixed(header.ms<1e4?1:0)}s`}`};var NO_IMPACT_ROWS=5,MAX_RULE_LINES=8,FIX_SUGGESTIONS=3,plural2=(n,one,many=`${one}s`)=>`${n} ${n===1?one:many}`;function repoLine(h){let shape=h.packages>0?`${h.manager}, ${plural2(h.packages,"package")}`:h.manager;return`${h.repo} (${shape})`}var planOf=p=>p.plan??planPackage(p);function targetSource(p,opts){return opts.repeat?.targets?.[p.name]!==void 0?"--target":p.target===p.latest?"latest on npm":""}function bump(installed,target){let parts=v=>(v.match(/\d+/g)??[]).slice(0,3).map(Number),[a,b]=[parts(installed),parts(target)];return a.length<3||b.length<3?"":a[0]!==b[0]?(b[0]??0)-(a[0]??0)>1?`${(b[0]??0)-(a[0]??0)} majors behind`:"major":a[1]!==b[1]?"minor":a[2]!==b[2]?"patch":""}function byLine(groups){let total={rule:0,agent:0,manual:0};for(let g of groups)total.rule+=g.by.rule,total.agent+=g.by.agent,total.manual+=g.by.manual;return[total.rule>0?BY.rule(total.rule):"",total.agent>0?BY.agent(total.agent):"",total.manual>0?`${total.manual} manual`:""].filter(Boolean).join(" \xB7 ")}var byLabel=g=>[g.by.rule>0?BY.ruleTag:"",g.by.agent>0?BY.agentTag:"",g.by.manual>0?"manual":""].filter(Boolean).join(" + "),filesOf=groups=>new Set(groups.flatMap(g=>g.locations.map(l=>l.file))).size,sitesOf=groups=>groups.reduce((n,g)=>n+g.sites,0),ANALYZED=["breaking","deprecated","safe","partial","unknown"],verdictLine=p=>p.verdict?.summary??(ANALYZED.includes(p.status)?verdictOf(p).summary:void 0);function rowOf(p,multi,colors){if(["not-imported","workspace","private"].includes(p.status)||p.notes.includes("up to date")||p.installed===p.target&&p.findings.length===0&&p.status==="safe"||p.skipReason==="TIME_BUDGET"||isFailure(p))return;let generic=p.tier==="generic",plan=planOf(p).filter(g=>!(generic&&g.severity==="unverified")),unconfirmed=generic?sitesOf(planOf(p).filter(g=>g.severity==="unverified")):0,aside=unconfirmed>0?colors.dim(` \xB7 ${unconfirmed} unconfirmed in --details`):"",of=severity=>plan.filter(g=>g.severity===severity),[breaking,unverified,deprecated]=[of("breaking"),of("unverified"),of("deprecated")],where=multi&&p.workspace!=="*"&&p.workspace!=="."?colors.dim(` (${p.workspace})`):"",members=p.members?` (${plural2(p.members.length,"package")})`:"",unanalyzed=p.unanalyzed.length,gaps=(p.importers??[]).filter(i=>!i.analyzed).length,verdict3,by="";if(p.status==="no-types"||p.status==="skipped"){let reason=p.notes.find(n=>n.startsWith("types in "))??p.notes.find(n=>/type declarations|not installed/.test(n))??p.notes[0]??"no type declarations";verdict3=colors.dim(`\u2013 not analyzed: ${reason.split(";")[0]}`)}else if(breaking.length>0){let sites=sitesOf(breaking),files=filesOf(breaking),extra=unverified.length>0?`, ${sitesOf(unverified)} unverified`:"";verdict3=`${colors.red("\u2717")} ${sites} breaking${sites>1?` in ${plural2(files,"file")}`:""}${extra}${aside}`,by=byLine([...breaking,...unverified])}else unverified.length>0?(verdict3=`${colors.magenta("?")} ${sitesOf(unverified)} unverified`,by=byLine(unverified)):deprecated.length>0?(verdict3=`${colors.yellow("!")} ${sitesOf(deprecated)} deprecated${aside}`,by=byLine(deprecated)):p.status==="unknown"?verdict3=`${colors.magenta("?")} ${unanalyzed} of ${plural2(p.callSitesChecked+unanalyzed,"site")} not analyzed`:unanalyzed>0?verdict3=`${colors.green("\u2713")} no impact in ${plural2(p.callSitesChecked,"site")}, ${unanalyzed} not analyzed${aside}`:gaps>0?verdict3=`${colors.magenta("?")} no impact in ${plural2(p.callSitesChecked,"site")}, ${plural2(gaps,"workspace")} not analyzed${aside}`:unconfirmed>0?verdict3=`${colors.green("\u2713")} nothing confirmed ${colors.dim(`(${plural2(p.callSitesChecked,"call site")})`)}${aside}`:verdict3=`${colors.green("\u2713")} no impact ${colors.dim(`(${plural2(p.callSitesChecked,"call site")})`)}`;return{p,name:`${p.name}${members}${where}`,versions:`${p.installed} \u2192 ${p.target}`,bump:bump(p.installed,p.target),verdict:verdict3,by,plan,quiet:plan.length===0&&gaps===0&&!["no-types","skipped","unknown"].includes(p.status),...verdictLine(p)?{summary:verdictLine(p)}:{}}}var COLOR=new RegExp("\x1B\\[[0-9;]*m","g");function deprecatedNames(groups){let counts=new Map;for(let g of groups)for(let[name,n]of Object.entries(g.symbols??{}))counts.set(name,(counts.get(name)??0)+n);let names2=[...counts].sort((a,b)=>b[1]-a[1]||a[0].localeCompare(b[0]));return`${names2.slice(0,3).map(([name])=>name).join(", ")}${names2.length>3?", ...":""}`}function sectionLines(row,colors){let acting=row.plan.filter(g=>g.severity!=="deprecated"),deprecated=row.plan.filter(g=>g.severity==="deprecated"),importers=importerNotes(row.p),peers=row.p.notes.flatMap(note=>{let m=/: (\S+)@(\S+) is outside the peer range (.+?) of (\S+);/.exec(note);return m?[`${m[4]} ${row.p.target} needs ${m[1]} ${m[3]} (installed: ${m[2]}): upgrade ${m[1]} first`]:[]}),heading=row.summary?`${colors.bold(row.p.name)} ${colors.dim(row.summary)}`:colors.bold(row.p.name);if(acting.length===0&&deprecated.length===0&&importers.length===0&&peers.length===0)return row.summary?[heading]:[];let scope=g=>{if(g.fixes!==g.sites)return`${plural2(g.fixes,"fix","fixes")}, ${plural2(g.sites,"error")}`;let only=g.locations[0];return g.sites===1&&only?`${basename(only.file)}:${only.line}`:plural2(g.sites,"site")},listed=acting.length>MAX_RULE_LINES?acting.slice(0,MAX_RULE_LINES-1):acting,titleWidth=Math.max(...listed.map(g=>g.title.length),0),scopeWidth=Math.max(...listed.map(g=>scope(g).length),0),lines=[heading];for(let g of listed){let mark=g.severity==="breaking"?colors.red("\u2717"):colors.magenta("?");lines.push(` ${mark} ${pad(g.title,titleWidth)} ${pad(scope(g),scopeWidth)} ${colors.dim(byLabel(g))}`),g.note&&lines.push(colors.dim(` ${g.note}`))}if(listed.length<acting.length){let rest=acting.slice(listed.length);lines.push(colors.dim(` \u2026 ${plural2(rest.length,"more change")}, ${plural2(sitesOf(rest),"site")} (--details)`))}if(deprecated.length>0){let sites=sitesOf(deprecated),byRule=deprecated.reduce((n,g)=>n+g.by.rule,0),who=byRule>0?BY.rule(byRule):byLine(deprecated);lines.push(` ${colors.yellow("!")} ${plural2(sites,"deprecated call")} (${deprecatedNames(deprecated)}) ${colors.dim(who)}`)}for(let note of importers)lines.push(` ${colors.yellow("\u26A0")} ${note}`);for(let note of peers)lines.push(` ${colors.yellow("\u26A0")} peer: ${note}`);return lines}function notAnalyzed(report,opts,colors){let uptide=opts.invocation??"npx uptide",late=report.packages.filter(p=>p.skipReason==="TIME_BUDGET"),failed=report.packages.filter(p=>isFailure(p));if(late.length===0&&failed.length===0)return[];let lines=[colors.bold("Not analyzed")];if(late.length>0){let budget=opts.maxTime?` (--max-time ${opts.maxTime})`:"";lines.push(` ${colors.yellow("\u26A0")} ${late.length} behind, out of time${budget}: ${late.slice(0,6).map(p=>p.name).join(", ")}${late.length>6?`, and ${late.length-6} more`:""}`,colors.dim(` ${uptide} check ${late.slice(0,3).map(p=>p.name).join(" ")} by name, no time limit`),colors.dim(` ${uptide} list discover upgrades, then check named packages`))}let reasonOf=p=>(p.notes[0]??"analysis failed").split(`
40
+ `}var import_picocolors3=__toESM(require_picocolors(),1);import{stripVTControlCharacters as stripVTControlCharacters3}from"util";var textWidth=text=>Array.from(stripVTControlCharacters3(text)).length,ellipsis=(text,width2)=>{let chars=Array.from(text);return chars.length<=width2?text:`${chars.slice(0,Math.max(0,width2-1)).join("")}\u2026`},NAME_CAP=45;function alignedRows(rows,width2,color,indent=0){let colors=import_picocolors3.default.createColors(color);rows=rows.map(row2=>row2.map((cell,column)=>{let marker=cell.alignAt;if(!marker||!cell.text.includes(marker))return cell;let before=cell.text.indexOf(marker),widest=Math.max(...rows.map(r=>{let other=r[column];return other&&other.alignAt===marker?Math.max(0,other.text.indexOf(marker)):0}));return{...cell,text:" ".repeat(widest-before)+cell.text}}));let lengths=Array.from({length:Math.max(0,...rows.map(r=>r.length))},(_,i)=>Math.max(0,...rows.map(r=>textWidth(r[i]?.span?"":r[i]?.text??""))));for(;lengths.at(-1)===0;)lengths.pop();let total=()=>lengths.reduce((a,b)=>a+b,0)+Math.max(0,lengths.length-1)*3+indent;for(lengths[0]&&(lengths[0]=Math.min(NAME_CAP,Math.max(12,lengths[0])));total()>width2&&lengths.length>2;)lengths.pop();return total()>width2&&lengths[1]&&(lengths[1]=Math.max(1,lengths[1]-(total()-width2))),rows.map(row2=>{let cells=[],consumed=indent,wrapped="";for(let[i,length]of lengths.entries()){let cell=row2[i],available=cell?.span?width2-consumed:length;if(i===0&&cell&&textWidth(cell.text)>length){wrapped=`${" ".repeat(indent)}${cell.tone?colors[cell.tone](cell.text):cell.text}
41
+ `,cells.push(" ".repeat(length)),consumed+=length+3;continue}let text=ellipsis(cell?.text??"",Math.max(1,available)),styled=cell?.tone?colors[cell.tone](text):text;if(cells.push(styled+(cell?.span||i===lengths.length-1?"":" ".repeat(Math.max(0,length-textWidth(text))))),consumed+=length+3,cell?.span)break}return wrapped+(" ".repeat(indent)+cells.join(" ")).trimEnd()})}var terminalHeader=(command,header,color)=>{let c=import_picocolors3.default.createColors(color);return`${c.bold(`uptide ${command}`)} ${c.dim("\xB7")} ${header.repo} ${c.dim("\xB7")} ${header.manager} ${c.dim("\xB7")} ${header.ms<1e3?`${Math.round(header.ms)}ms`:`${(header.ms/1e3).toFixed(header.ms<1e4?1:0)}s`}`};var NO_IMPACT_ROWS=5,MAX_RULE_LINES=8,FIX_SUGGESTIONS=3,plural2=(n,one,many=`${one}s`)=>`${n} ${n===1?one:many}`;function repoLine(h){let shape=h.packages>0?`${h.manager}, ${plural2(h.packages,"package")}`:h.manager;return`${h.repo} (${shape})`}var planOf=p=>p.plan??planPackage(p);function targetSource(p,opts){return opts.repeat?.targets?.[p.name]!==void 0?"--target":p.target===p.latest?"latest on npm":""}function bump(installed,target){let parts=v=>(v.match(/\d+/g)??[]).slice(0,3).map(Number),[a,b]=[parts(installed),parts(target)];return a.length<3||b.length<3?"":a[0]!==b[0]?(b[0]??0)-(a[0]??0)>1?`${(b[0]??0)-(a[0]??0)} majors behind`:"major":a[1]!==b[1]?"minor":a[2]!==b[2]?"patch":""}function byLine(groups){let total={rule:0,agent:0,manual:0};for(let g of groups)total.rule+=g.by.rule,total.agent+=g.by.agent,total.manual+=g.by.manual;return[total.rule>0?BY.rule(total.rule):"",total.agent>0?BY.agent(total.agent):"",total.manual>0?`${total.manual} manual`:""].filter(Boolean).join(" \xB7 ")}var byLabel=g=>[g.by.rule>0?BY.ruleTag:"",g.by.agent>0?BY.agentTag:"",g.by.manual>0?"manual":""].filter(Boolean).join(" + "),filesOf=groups=>new Set(groups.flatMap(g=>g.locations.map(l=>l.file))).size,sitesOf=groups=>groups.reduce((n,g)=>n+g.sites,0),ANALYZED=["breaking","deprecated","safe","partial","unknown"],verdictLine=p=>p.verdict?.summary??(ANALYZED.includes(p.status)?verdictOf(p).summary:void 0);function rowOf(p,multi,colors){if(["not-imported","workspace","private"].includes(p.status)||p.notes.includes("up to date")||p.installed===p.target&&p.findings.length===0&&p.status==="safe"||p.skipReason==="TIME_BUDGET"||isFailure(p))return;let generic=p.tier==="generic",plan=planOf(p).filter(g=>!(generic&&g.severity==="unverified")),unconfirmed=generic?sitesOf(planOf(p).filter(g=>g.severity==="unverified")):0,aside=unconfirmed>0?colors.dim(` \xB7 ${unconfirmed} unconfirmed in --details`):"",of=severity=>plan.filter(g=>g.severity===severity),[breaking,unverified,deprecated]=[of("breaking"),of("unverified"),of("deprecated")],where=multi&&p.workspace!=="*"&&p.workspace!=="."?colors.dim(` (${p.workspace})`):"",members=p.members?` (${plural2(p.members.length,"package")})`:"",unanalyzed=p.unanalyzed.length,gaps=(p.importers??[]).filter(i=>!i.analyzed).length,verdict3,by="";if(p.status==="no-types"||p.status==="skipped"){let reason=p.notes.find(n=>n.startsWith("types in "))??p.notes.find(n=>/type declarations|not installed/.test(n))??p.notes[0]??"no type declarations";verdict3=colors.dim(`\u2013 not analyzed: ${reason.split(";")[0]}`)}else if(breaking.length>0){let sites=sitesOf(breaking),files=filesOf(breaking),extra=unverified.length>0?`, ${sitesOf(unverified)} unverified`:"";verdict3=`${colors.red("\u2717")} ${sites} breaking${sites>1?` in ${plural2(files,"file")}`:""}${extra}${aside}`,by=byLine([...breaking,...unverified])}else unverified.length>0?(verdict3=`${colors.magenta("?")} ${sitesOf(unverified)} unverified`,by=byLine(unverified)):deprecated.length>0?(verdict3=`${colors.yellow("!")} ${sitesOf(deprecated)} deprecated${aside}`,by=byLine(deprecated)):p.status==="unknown"?verdict3=`${colors.magenta("?")} ${unanalyzed} of ${plural2(p.callSitesChecked+unanalyzed,"site")} not analyzed`:unanalyzed>0?verdict3=`${colors.green("\u2713")} no impact in ${plural2(p.callSitesChecked,"site")}, ${unanalyzed} not analyzed${aside}`:gaps>0?verdict3=`${colors.magenta("?")} no impact in ${plural2(p.callSitesChecked,"site")}, ${plural2(gaps,"workspace")} not analyzed${aside}`:unconfirmed>0?verdict3=`${colors.green("\u2713")} nothing confirmed ${colors.dim(`(${plural2(p.callSitesChecked,"call site")})`)}${aside}`:verdict3=`${colors.green("\u2713")} no impact ${colors.dim(`(${plural2(p.callSitesChecked,"call site")})`)}`;return{p,name:`${p.name}${members}${where}`,versions:`${p.installed} \u2192 ${p.target}`,bump:bump(p.installed,p.target),verdict:verdict3,by,plan,quiet:plan.length===0&&gaps===0&&!["no-types","skipped","unknown"].includes(p.status),...verdictLine(p)?{summary:verdictLine(p)}:{}}}var COLOR=new RegExp("\x1B\\[[0-9;]*m","g");function deprecatedNames(groups){let counts=new Map;for(let g of groups)for(let[name,n]of Object.entries(g.symbols??{}))counts.set(name,(counts.get(name)??0)+n);let names2=[...counts].sort((a,b)=>b[1]-a[1]||a[0].localeCompare(b[0]));return`${names2.slice(0,3).map(([name])=>name).join(", ")}${names2.length>3?", ...":""}`}function sectionLines(row2,colors){let acting=row2.plan.filter(g=>g.severity!=="deprecated"),deprecated=row2.plan.filter(g=>g.severity==="deprecated"),importers=importerNotes(row2.p),peers=row2.p.notes.flatMap(note=>{let m=/: (\S+)@(\S+) is outside the peer range (.+?) of (\S+);/.exec(note);return m?[`${m[4]} ${row2.p.target} needs ${m[1]} ${m[3]} (installed: ${m[2]}): upgrade ${m[1]} first`]:[]}),heading=row2.summary?`${colors.bold(row2.p.name)} ${colors.dim(row2.summary)}`:colors.bold(row2.p.name);if(acting.length===0&&deprecated.length===0&&importers.length===0&&peers.length===0)return row2.summary?[heading]:[];let scope=g=>{if(g.fixes!==g.sites)return`${plural2(g.fixes,"fix","fixes")}, ${plural2(g.sites,"error")}`;let only=g.locations[0];return g.sites===1&&only?`${basename(only.file)}:${only.line}`:plural2(g.sites,"site")},listed=acting.length>MAX_RULE_LINES?acting.slice(0,MAX_RULE_LINES-1):acting,titleWidth=Math.max(...listed.map(g=>g.title.length),0),scopeWidth=Math.max(...listed.map(g=>scope(g).length),0),lines=[heading];for(let g of listed){let mark=g.severity==="breaking"?colors.red("\u2717"):colors.magenta("?");lines.push(` ${mark} ${pad(g.title,titleWidth)} ${pad(scope(g),scopeWidth)} ${colors.dim(byLabel(g))}`),g.note&&lines.push(colors.dim(` ${g.note}`))}if(listed.length<acting.length){let rest=acting.slice(listed.length);lines.push(colors.dim(` \u2026 ${plural2(rest.length,"more change")}, ${plural2(sitesOf(rest),"site")} (--details)`))}if(deprecated.length>0){let sites=sitesOf(deprecated),byRule=deprecated.reduce((n,g)=>n+g.by.rule,0),who=byRule>0?BY.rule(byRule):byLine(deprecated);lines.push(` ${colors.yellow("!")} ${plural2(sites,"deprecated call")} (${deprecatedNames(deprecated)}) ${colors.dim(who)}`)}let companions=row2.p.companions??[];companions.length>0&&lines.push(` ${colors.cyan("\u2191")} upgrades with ${companions.map(c=>`${c.name} ${c.from} \u2192 ${c.to}`).join(", ")} ${colors.dim(companions.map(c=>c.reason).join("; "))}`);for(let conflict of row2.p.companionConflicts??[])lines.push(` ${colors.red("\u2717")} ${conflict}: no consistent upgrade`);for(let note of importers)lines.push(` ${colors.yellow("\u26A0")} ${note}`);for(let note of peers)lines.push(` ${colors.yellow("\u26A0")} peer: ${note}`);return lines}function notAnalyzed(report,opts,colors){let uptide=opts.invocation??"npx uptide",late=report.packages.filter(p=>p.skipReason==="TIME_BUDGET"),failed=report.packages.filter(p=>isFailure(p));if(late.length===0&&failed.length===0)return[];let lines=[colors.bold("Not analyzed")];if(late.length>0){let budget=opts.maxTime?` (--max-time ${opts.maxTime})`:"";lines.push(` ${colors.yellow("\u26A0")} ${late.length} behind, out of time${budget}: ${late.slice(0,6).map(p=>p.name).join(", ")}${late.length>6?`, and ${late.length-6} more`:""}`,colors.dim(` ${uptide} check ${late.slice(0,3).map(p=>p.name).join(" ")} by name, no time limit`),colors.dim(` ${uptide} list discover upgrades, then check named packages`))}let reasonOf=p=>(p.notes[0]??"analysis failed").split(`
42
42
  `)[0]?.replace(/ \(check it alone with --only \S+,/," (check one alone with --only,")??"",byReason=new Map;for(let p of failed)byReason.set(reasonOf(p),[...byReason.get(reasonOf(p))??[],p]);for(let[reason,group]of byReason){let only=group[0];lines.push(group.length===1?` ${colors.red("\u2717")} ${only.name} ${only.installed}: ${(only.notes[0]??"analysis failed").split(`
43
- `)[0]}`:` ${colors.red("\u2717")} ${group.length} failed: ${reason}: ${group.slice(0,6).map(p=>p.name).join(", ")}${group.length>6?`, and ${group.length-6} more`:""}`)}return lines}function nextCommands(rows,opts){let uptide=opts.invocation??"npx uptide",quote2=s=>/^[\w./@:=+-]+$/.test(s)?s:`'${s.replaceAll("'",`'"'"'`)}'`,cwd=opts.repeat?.cwd?` --cwd ${quote2(opts.repeat.cwd)}`:"",commands=[],fixable=name=>opts.fixable===!0||Array.isArray(opts.fixable)&&opts.fixable.includes(name);for(let row of rows){let name=row.p.name;if(!fixable(name)||row.p.members)continue;if(commands.length>=FIX_SUGGESTIONS)break;let target=opts.repeat?.targets?.[name],pinned=target?` --target ${quote2(target)}`:"";row.plan.some(g=>g.severity!=="deprecated")?commands.push([`${uptide} fix ${name}${pinned}${cwd}`,row.p.tier==="generic"?"migrate with the agent on a new branch, verify, no push":"migrate on a new branch, verify, no push"]):row.p.tier!=="generic"&&row.plan.some(g=>g.by.rule>0)&&commands.push([`${uptide} fix ${name}${pinned} --include-deprecated${cwd}`,"migrate the deprecated calls on a new branch, no push"])}let names2=opts.repeat?.only?.split(",")??[...new Set(rows.flatMap(r=>(r.p.members??[r.p]).map(p=>p.name)))],only=names2.length?` ${names2.map(quote2).join(" ")}`:" <package>",planOnly=opts.repeat?.only?` --only ${quote2(opts.repeat.only)}`:"",targets=Object.entries(opts.repeat?.targets??{}).map(([name,version])=>` --target ${quote2(`${name}@${version}`)}`).join("");return rows.filter(r=>r.plan.length>0).length>1&&commands.push([`${uptide} plan${planOnly}${cwd}`,"the order to upgrade in, with the effort"]),commands.push(opts.details?[`${uptide} check${only}${targets}${cwd}`,"the summary, one line per change"]:[`${uptide} check${only}${targets} --details${cwd}`,"every site and reason"]),commands}function nextLines(rows,opts,colors){let commands=nextCommands(rows,opts),widest=Math.max(...commands.map(([command])=>command.length));return[colors.bold("Next"),...commands.map(([command,what])=>` ${pad(command,widest)} ${colors.dim(what)}`)]}function checkRows(report,colors=import_picocolors4.default.createColors(!1)){let multi=report.workspaces.length>1,weight=(row,severity)=>sitesOf(row.plan.filter(g=>g.severity===severity));return report.packages.map(p=>rowOf(p,multi,colors)).filter(row=>row!==void 0).sort((a,b)=>weight(b,"breaking")-weight(a,"breaking")||weight(b,"unverified")-weight(a,"unverified")||weight(b,"deprecated")-weight(a,"deprecated"))}var width=text=>text.replace(COLOR,"").length,pad=(text,to)=>text+" ".repeat(Math.max(0,to-width(text)));function formatCheck(report,opts={}){let colors=import_picocolors4.default.createColors(opts.color??!0),lines=[];opts.header&&lines.push(terminalHeader("check",opts.header,opts.color??!0),"");let rows=checkRows(report,colors);if(opts.details)lines.push(formatCheckDetails(report,{color:opts.color,all:opts.all}).trimEnd(),"");else{let move=row=>[row.bump,targetSource(row.p,opts)].filter(Boolean).join(" \xB7 "),quiet=rows.filter(r=>r.quiet),folded=quiet.length>NO_IMPACT_ROWS?quiet:[],shown=rows.filter(r=>!folded.includes(r));if(lines.push(...alignedRows(shown.map(row=>[{text:row.name,tone:"bold"},{text:row.versions,alignAt:"\u2192"},{text:move(row),tone:row.bump.startsWith("major")?"yellow":"dim"},{text:row.p.tier==="verified"?"verified":"",tone:"green"},{text:row.verdict.replace(COLOR,"")},{text:row.by,tone:"dim"}]),opts.width??160,opts.color??!0)),folded.length>0){let named=folded.slice(0,6).map(r=>r.p.name),unverified=folded.filter(r=>r.p.verdict?.notVerified??!r.p.compile).length,counted=folded.every(r=>r.p.compile?.newErrors===0),how=unverified>0?`${unverified} not verified by the compiler (--details)`:`compiled against their targets${counted?": 0 new type errors":""}`;lines.push(`${colors.green("\u2713")} ${folded.length} more with no impact on your code: ${named.join(", ")}${folded.length>named.length?`, and ${folded.length-named.length} more`:""} ${colors.dim(`\xB7 0 breaking \xB7 ${how}`)}`)}let missing=notAnalyzed(report,opts,colors);rows.length===0&&missing.length===0&&lines.push(colors.dim("Nothing to upgrade: every checked dependency is up to date.")),rows.some(r=>r.p.tier==="generic")&&lines.push("",colors.dim(TIER_LEGEND)),lines.push(""),missing.length>0&&lines.push(...missing,"");for(let row of rows.filter(r=>!folded.includes(r))){let section=sectionLines(row,colors);section.length>0&&lines.push(...section,"")}}return lines.push(...nextLines(rows,opts,colors)),`${lines.join(`
43
+ `)[0]}`:` ${colors.red("\u2717")} ${group.length} failed: ${reason}: ${group.slice(0,6).map(p=>p.name).join(", ")}${group.length>6?`, and ${group.length-6} more`:""}`)}return lines}function nextCommands(rows,opts){let uptide=opts.invocation??"npx uptide",quote2=s=>/^[\w./@:=+-]+$/.test(s)?s:`'${s.replaceAll("'",`'"'"'`)}'`,cwd=opts.repeat?.cwd?` --cwd ${quote2(opts.repeat.cwd)}`:"",commands=[],fixable=name=>opts.fixable===!0||Array.isArray(opts.fixable)&&opts.fixable.includes(name);for(let row2 of rows){let name=row2.p.name;if(!fixable(name)||row2.p.members&&!row2.p.companions)continue;if(commands.length>=FIX_SUGGESTIONS)break;let target=opts.repeat?.targets?.[name],pinned=target?` --target ${quote2(target)}`:"";row2.plan.some(g=>g.severity!=="deprecated")?commands.push([`${uptide} fix ${name}${pinned}${cwd}`,row2.p.tier==="generic"?"migrate with the agent on a new branch, verify, no push":"migrate on a new branch, verify, no push"]):row2.p.tier!=="generic"&&row2.plan.some(g=>g.by.rule>0)&&commands.push([`${uptide} fix ${name}${pinned} --include-deprecated${cwd}`,"migrate the deprecated calls on a new branch, no push"])}let names2=opts.repeat?.only?.split(",")??[...new Set(rows.flatMap(r=>(r.p.members??[r.p]).map(p=>p.name)))],only=names2.length?` ${names2.map(quote2).join(" ")}`:" <package>",planOnly=opts.repeat?.only?` --only ${quote2(opts.repeat.only)}`:"",targets=Object.entries(opts.repeat?.targets??{}).map(([name,version])=>` --target ${quote2(`${name}@${version}`)}`).join("");return rows.filter(r=>r.plan.length>0).length>1&&commands.push([`${uptide} plan${planOnly}${cwd}`,"the order to upgrade in, with the effort"]),commands.push(opts.details?[`${uptide} check${only}${targets}${cwd}`,"the summary, one line per change"]:[`${uptide} check${only}${targets} --details${cwd}`,"every site and reason"]),commands}function nextLines(rows,opts,colors){let commands=nextCommands(rows,opts),widest=Math.max(...commands.map(([command])=>command.length));return[colors.bold("Next"),...commands.map(([command,what])=>` ${pad(command,widest)} ${colors.dim(what)}`)]}function checkRows(report,colors=import_picocolors4.default.createColors(!1)){let multi=report.workspaces.length>1,weight=(row2,severity)=>sitesOf(row2.plan.filter(g=>g.severity===severity));return report.packages.map(p=>rowOf(p,multi,colors)).filter(row2=>row2!==void 0).sort((a,b)=>weight(b,"breaking")-weight(a,"breaking")||weight(b,"unverified")-weight(a,"unverified")||weight(b,"deprecated")-weight(a,"deprecated"))}var width=text=>text.replace(COLOR,"").length,pad=(text,to)=>text+" ".repeat(Math.max(0,to-width(text)));function formatCheck(report,opts={}){let colors=import_picocolors4.default.createColors(opts.color??!0),lines=[];opts.header&&lines.push(terminalHeader("check",opts.header,opts.color??!0),"");let rows=checkRows(report,colors);if(opts.details)lines.push(formatCheckDetails(report,{color:opts.color,all:opts.all}).trimEnd(),"");else{let move=row2=>[row2.bump,targetSource(row2.p,opts)].filter(Boolean).join(" \xB7 "),quiet=rows.filter(r=>r.quiet),folded=quiet.length>NO_IMPACT_ROWS?quiet:[],shown=rows.filter(r=>!folded.includes(r));if(lines.push(...alignedRows(shown.map(row2=>[{text:row2.name,tone:"bold"},{text:row2.versions,alignAt:"\u2192"},{text:move(row2),tone:row2.bump.startsWith("major")?"yellow":"dim"},{text:row2.p.tier==="verified"?"verified":"",tone:"green"},{text:row2.verdict.replace(COLOR,"")},{text:row2.by,tone:"dim"}]),opts.width??160,opts.color??!0)),folded.length>0){let named=folded.slice(0,6).map(r=>r.p.name),unverified=folded.filter(r=>r.p.verdict?.notVerified??!r.p.compile).length,counted=folded.every(r=>r.p.compile?.newErrors===0),how=unverified>0?`${unverified} not verified by the compiler (--details)`:`compiled against their targets${counted?": 0 new type errors":""}`;lines.push(`${colors.green("\u2713")} ${folded.length} more with no impact on your code: ${named.join(", ")}${folded.length>named.length?`, and ${folded.length-named.length} more`:""} ${colors.dim(`\xB7 0 breaking \xB7 ${how}`)}`)}let missing=notAnalyzed(report,opts,colors);rows.length===0&&missing.length===0&&lines.push(colors.dim("Nothing to upgrade: every checked dependency is up to date.")),rows.some(r=>r.p.tier==="generic")&&lines.push("",colors.dim(TIER_LEGEND)),lines.push(""),missing.length>0&&lines.push(...missing,"");for(let row2 of rows.filter(r=>!folded.includes(r))){let section=sectionLines(row2,colors);section.length>0&&lines.push(...section,"")}}return lines.push(...nextLines(rows,opts,colors)),`${lines.join(`
44
44
  `)}
45
45
  `}import{isAbsolute,relative}from"path";var import_picocolors6=__toESM(require_picocolors(),1);var import_picocolors5=__toESM(require_picocolors(),1);function elapsed(ms){if(ms<1e3)return`${Math.round(ms)}ms`;if(ms<1e4)return`${(ms/1e3).toFixed(1)}s`;let s=Math.round(ms/1e3);return s<60?`${s}s`:`${Math.floor(s/60)}m ${String(s%60).padStart(2,"0")}s`}var FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],HEARTBEAT_MS=1e4;function createProgress(io2,ui,options={}){let colors=import_picocolors5.default.createColors(ui.color),quiet=options.quiet===!0,activity="";return{event(event){let label=[event.phase,event.detail??event.package,event.workspace].filter(Boolean).join(" \xB7 ");event.state==="start"?activity=label:(quiet||(ui.interactive&&io2.err("\r\x1B[2K"),io2.err(` ${label} (${elapsed(event.ms??0)})
46
46
  `)),activity="")},async phase(label,work,detail){let started=io2.now(),since=()=>elapsed(io2.now()-started),frame=0,tick=ui.interactive?setInterval(()=>{frame=(frame+1)%FRAMES.length,io2.err(`\r\x1B[2K${colors.cyan(FRAMES[frame]??"")} ${activity||label} ${colors.dim(since())}`)},80):quiet?void 0:setInterval(()=>io2.err(`\u2026 ${activity||label}, still working (${since()})
47
47
  `),HEARTBEAT_MS);tick?.unref?.(),ui.interactive&&io2.err(`${colors.cyan(FRAMES[0]??"")} ${label}`);let clear=()=>{clearInterval(tick),ui.interactive&&io2.err("\r\x1B[2K")};try{let result=await work();if(clear(),quiet)return result;let text=detail?.(result);return io2.err(`${colors.green("\u2714")} ${label}${text?` ${text}`:""} ${colors.dim(`(${since()})`)}
48
48
  `),result}catch(err){throw clear(),io2.err(`${colors.red("\u2716")} ${label} ${colors.dim(`(${since()})`)}
49
49
  `),err}},note(text){quiet||io2.err(` ${colors.dim(text)}
50
- `)}}}function formatFixSummary(report,opts={}){let colors=import_picocolors6.default.createColors(opts.color??!0),uptide=opts.invocation??"npx uptide",cells=summaryCells(report),dot=colors.dim("\xB7"),title=report.mode==="pin"?`pin ${report.package} API version ${report.apiVersion??""}`:`${report.package} ${report.from??"?"} \u2192 ${report.target}${report.targetSource?` ${colors.dim(`(${report.targetSource})`)}`:""}`,verdict3=report.verification.passed?colors.green("verification passed"):colors.red("verification failed"),lines=[`${colors.bold("uptide fix")} ${dot} ${title} ${dot} ${verdict3} ${dot} ${elapsed(opts.ms??report.timingMs)}`,"",...[["Risk",cells.risk],["Changes",cells.changes],["Types",cells.types],["Behavior",cells.behavior],["Tests",cells.tests]].map(([label,text])=>` ${pad2(label,9)} ${plain(text)}`),...report.tier==="generic"&&report.sites.some(s=>s.outcome==="agent")?[` ${pad2("Tier",9)} generic: no migration pack; every edit is the agent's, kept on the compiler's word. Review each one.`]:[],...report.llm.costLimit?[` ${pad2("Agent",9)} stopped at $${report.llm.costLimit.limitUsd.toFixed(2)} (--max-cost): ${report.llm.costLimit.notAttempted} site${report.llm.costLimit.notAttempted===1?"":"s"} not completed`]:[],""],from=opts.cwd??report.source??report.repo,where=report.source?"in your repository, not checked out":`in ${report.repo}`;lines.push(`${colors.bold("Branch")} ${report.branch} ${colors.dim(`(${where})`)}`);let base=report.base??"main";lines.push(` git diff ${base}..${report.branch} --stat`),report.clone?.kept&&lines.push(colors.dim(` temporary clone kept at ${report.clone.path}: ${report.clone.reason}`)),lines.push("",colors.bold("Next"));let next=[];report.prUrl?next.push([report.prUrl,"the pull request"]):report.verification.passed?next.push([`${uptide} pr --branch ${report.branch}`,`push the branch and open ${report.publication?.refused.length?"":"a draft "}PR${report.remote?` on ${report.remote.replace(/^https:\/\/github\.com\//,"")}`:""}`]):next.push([`${uptide} verify --branch ${report.branch}`,"verify again after fixing what failed"]);let local=file=>{let rel=relative(from,file);return rel.startsWith("..")||isAbsolute(rel)?file:rel};report.html&&next.push([`open ${local(report.html)}`,"the migration report"]),next.push([local(report.prBody),"the PR description"]);let width2=Math.max(...next.map(([c])=>c.length));for(let[cmd,what]of next)lines.push(` ${pad2(cmd,width2)} ${colors.dim(what)}`);return`${lines.join(`
50
+ `)}}}function formatFixSummary(report,opts={}){let colors=import_picocolors6.default.createColors(opts.color??!0),uptide=opts.invocation??"npx uptide",cells=summaryCells(report),dot=colors.dim("\xB7"),title=report.mode==="pin"?`pin ${report.package} API version ${report.apiVersion??""}`:`${report.package} ${report.from??"?"} \u2192 ${report.target}${report.targetSource?` ${colors.dim(`(${report.targetSource})`)}`:""}`,verdict3=report.verification.passed?colors.green("verification passed"):colors.red("verification failed"),lines=[`${colors.bold("uptide fix")} ${dot} ${title} ${dot} ${verdict3} ${dot} ${elapsed(opts.ms??report.timingMs)}`,"",...[["Risk",cells.risk],["Changes",cells.changes],["Types",cells.types],["Behavior",cells.behavior],["Tests",cells.tests]].map(([label,text])=>` ${pad2(label,9)} ${plain(text)}`),...report.companions?.length?[` ${pad2("With",9)} ${report.companions.map(c=>`${c.name} ${c.from} \u2192 ${c.to}`).join(", ")}`]:[],...report.tier==="generic"&&report.sites.some(s=>s.outcome==="agent")?[` ${pad2("Tier",9)} generic: no migration pack; every edit is the agent's, kept on the compiler's word. Review each one.`]:[],...report.llm.costLimit?[` ${pad2("Agent",9)} stopped at $${report.llm.costLimit.limitUsd.toFixed(2)} (--max-cost): ${report.llm.costLimit.notAttempted} site${report.llm.costLimit.notAttempted===1?"":"s"} not completed`]:[],""],from=opts.cwd??report.source??report.repo,where=report.source?"in your repository, not checked out":`in ${report.repo}`;lines.push(`${colors.bold("Branch")} ${report.branch} ${colors.dim(`(${where})`)}`);let base=report.base??"main";lines.push(` git diff ${base}..${report.branch} --stat`),report.clone?.kept&&lines.push(colors.dim(` temporary clone kept at ${report.clone.path}: ${report.clone.reason}`)),lines.push("",colors.bold("Next"));let next=[];report.prUrl?next.push([report.prUrl,"the pull request"]):report.verification.passed?next.push([`${uptide} pr --branch ${report.branch}`,`push the branch and open ${report.publication?.refused.length?"":"a draft "}PR${report.remote?` on ${report.remote.replace(/^https:\/\/github\.com\//,"")}`:""}`]):next.push([`${uptide} verify --branch ${report.branch}`,"verify again after fixing what failed"]);let local=file=>{let rel=relative(from,file);return rel.startsWith("..")||isAbsolute(rel)?file:rel};report.html&&next.push([`open ${local(report.html)}`,"the migration report"]),next.push([local(report.prBody),"the PR description"]);let width2=Math.max(...next.map(([c])=>c.length));for(let[cmd,what]of next)lines.push(` ${pad2(cmd,width2)} ${colors.dim(what)}`);return`${lines.join(`
51
51
  `)}
52
52
  `}function plain(text){return text.replaceAll("`","").replace(/\*\*([^*]+)\*\*/g,"$1")}var pad2=(text,to)=>text+" ".repeat(Math.max(0,to-text.length));var import_picocolors7=__toESM(require_picocolors(),1);var plural3=(count,noun,multiple=`${noun}s`)=>`${count} ${count===1?noun:multiple}`,quote=s=>/^[\w./@:=+-]+$/.test(s)?s:`'${s.replaceAll("'",`'"'"'`)}'`,dependencyKey=p=>JSON.stringify([p.name,p.registryName??p.name,p.current]),listCommand=(packages,opts)=>`${opts.invocation??INVOCATION} check ${[...new Set(packages.map(p=>p.name))].map(quote).join(" ")}${opts.cwd?` --cwd ${quote(opts.cwd)}`:""}`,listChange=p=>p.majorGap>1?`${p.majorGap} majors behind`:p.change,listVersions=p=>{let outdated=p.versions?.map(v=>v.version).filter(v=>v!==p.latest)??[p.current];return`${outdated.length>2?`${outdated[0]} \u2026 ${outdated.at(-1)}`:outdated.join(", ")} \u2192 ${p.latest}`},listSpread=p=>p.versions?`${p.versions.length} versions in ${plural3(new Set(p.versions.flatMap(v=>v.workspaces)).size,"workspace")}`:"",groupCommand=(group,opts)=>`${opts.invocation??INVOCATION} check --group ${quote(group.id)}${opts.cwd?` --cwd ${quote(opts.cwd)}`:""}`,priorityCommand=(p,opts)=>`${opts.invocation??INVOCATION} check ${p.group?`--group ${quote(p.group)}`:p.packages.map(quote).join(" ")}${p.target?` --target ${quote(p.target)}`:""}${opts.cwd?` --cwd ${quote(opts.cwd)}`:""}`,cheapBatchCommand=(names2,opts)=>`${opts.invocation??INVOCATION} check ${names2.map(quote).join(" ")}${opts.cwd?` --cwd ${quote(opts.cwd)}`:""}`;function advisoryStatus(report){let a=report.advisories;return a?a.status==="checked"?`advisories checked for ${plural3(a.packages,"package")}`:`advisories not checked${a.reason?` (${a.reason})`:""}`:"advisories not checked"}function cheapBatchLabel(names2,shown=4){return`${names2.slice(0,shown).join(", ")}${names2.length>shown?` +${names2.length-shown}`:""}`}var PRIORITY_ROWS=5;function listUsage(p){return[plural3(p.usage.files,"file"),p.usage.callSites?plural3(p.usage.callSites,"call"):"",p.usage.references?plural3(p.usage.references,"reference"):""].filter(Boolean).join(" \xB7 ")}function groupCount(group){let total=group.totalMembers??group.members.length;return`${plural3(total,"package")}${total===group.members.length?"":` (${group.members.length} in this section)`}`}function groupVersions(group){let main=group.members.filter(p=>!p.peerOf),byMajor=new Map;for(let p of main){let major=Number(p.latest.split(".")[0]);byMajor.set(major,[...new Set([...byMajor.get(major)??[],p.name])])}if(byMajor.size<=1)return`\u2192 ${[...byMajor.keys()][0]}.x`;let label=names2=>{let scopes=new Set(names2.map(n=>n.startsWith("@")?n.split("/")[0]:n)),[scope]=scopes;return names2.length>1&&scopes.size===1&&scope?.startsWith("@")?`${scope}/*`:names2.join(", ")},majors=[...byMajor].sort(([a],[b])=>b-a),labels=majors.map(([,names2])=>label(names2)),named=majors.map(([major],i)=>`${labels[i]} ${major}`).join(" \xB7 ");return new Set(labels).size===labels.length&&named.length<=64?`\u2192 ${named}`:`\u2192 ${majors.map(([major])=>`${major}.x`).join(" \xB7 ")}`}var UNUSED_HINT="no usage found by Uptide's scan; verify before removing",listReasons=p=>p.reasons.filter(reason=>!p.peerOf?.some(name=>reason===`required by ${name}`||reason===`peer dependency of ${name}`)),listSymbols=p=>p.usage.topSymbols.filter(s=>s.count>0).map(s=>`${s.name} (${s.count})`).join(", ");function listSections(report){let groups=report.groups.filter(g=>groupLead(g)?.classification==="used"),grouped=new Set(groups.flatMap(g=>g.members.map(dependencyKey))),remaining=report.packages.filter(p=>!grouped.has(dependencyKey(p))),isTooling=p=>p.classification==="tooling"||p.classification==="peer"&&report.groups.some(g=>g.members.some(m=>dependencyKey(m)===dependencyKey(p))&&groupLead(g)?.classification==="tooling");return{groups,used:remaining.filter(p=>p.classification==="used"),tooling:remaining.filter(isTooling),unused:remaining.filter(p=>p.classification==="possibly-unused"||p.classification==="peer"&&!isTooling(p))}}var groupLead=group=>group.members.find(p=>p.name===group.lead)??group.members.find(p=>!p.peerOf)??group.members[0];function listBlocks(packages,report){let keys=new Set(packages.map(p=>dependencyKey(p))),groups=report.groups.filter(g=>{let lead=groupLead(g);return lead&&keys.has(dependencyKey(lead))}).map(g=>({...g,totalMembers:g.members.length,members:g.members.filter(p=>keys.has(dependencyKey(p)))})),grouped=new Set(groups.flatMap(g=>g.members.map(p=>dependencyKey(p))));return[...groups,...packages.filter(p=>!grouped.has(dependencyKey(p))).map(p=>({members:[p]}))]}function listFailureLines(report,details=!1){let failures=[...new Map(report.failures.map(f=>[f.name,f])).values()],buckets=new Map;for(let failure of failures){let key=failure.host&&failure.summary?JSON.stringify([failure.host,failure.status,failure.summary]):failure.name;buckets.set(key,[...buckets.get(key)??[],failure])}return[...buckets.values()].flatMap(members=>{let first=members[0];if(!first)return[];let denied=[401,403,405].includes(first.status??0);return first.host&&first.summary&&members.length>(denied?1:5)?[`? ${members.length} packages on ${first.host}: ${first.summary}, skipped`,...details?members.map(f=>` ${f.name}`):[]]:members.map(f=>`? ${f.name}: ${f.reason}`)})}function skippedSources(report){let groups=new Map;for(let item of report.skipped??[])groups.set(item.reason,[...groups.get(item.reason)??[],item]);return[...groups].sort(([a],[b])=>a.localeCompare(b)).map(([reason,members])=>({reason,members}))}function notCheckedLabel(report){let reasons=new Set((report.unknown??[]).map(unknown=>{let failure=report.failures.find(f=>f.name===unknown.name);if(failure?.status===403)return"access denied";if(failure?.status===401)return"auth required";if(failure?.status===404)return"not found";if(failure?.summary)return failure.summary.replace(/ \(\d{3}\)$/,"");let reason2=failure?.reason??unknown.reason;return["access denied","auth required","timed out","not found","network request failed"].find(label=>reason2.toLowerCase().includes(label))})),reason=reasons.size===1?[...reasons][0]:void 0;return`not checked${reason?` (${reason})`:""}`}function formatListTimings(report,renderMs){let phases=report.timing.phases,files=report.timing.files;return!phases||!files?[...report.scanWarnings??[],`render ${Math.max(0,renderMs).toFixed(1)} ms`,""].join(`
53
53
  `):[`manifest read ${phases.manifestReadMs.toFixed(1)} ms \xB7 ${plural3(files.manifests,"package manifest")} \xB7 ${plural3(files.installedManifests,"installed manifest")}`,`registry ${phases.registryMs.toFixed(1)} ms`,`source scan ${phases.sourceScanMs.toFixed(1)} ms \xB7 ${plural3(files.source,"source file")} \xB7 ${plural3(files.assets,"asset file")}${files.parsed===void 0?"":` \xB7 ${files.parsed} parsed \xB7 ${files.workers||0} workers`}`,`config scan ${phases.configScanMs.toFixed(1)} ms \xB7 ${plural3(files.config,"config file")}`,`render ${Math.max(0,renderMs).toFixed(1)} ms`,`files ${files.visited} visited (built-in excluded directories not enumerated)`,...files.candidateSources===void 0?[]:[`source scope ${files.candidateSources} candidates \xB7 ${files.ignoredSources??0} excluded by .gitignore`],...report.scanWarnings??[],...Object.entries(files.skipped??{}).sort(([a],[b])=>a.localeCompare(b)).map(([reason,count])=>`skipped ${reason}: ${plural3(count.files,"file")} \xB7 ${plural3(count.directories,"directory","directories")}`),""].join(`
54
- `)}function formatList(report,opts={}){let color=opts.color??!1,c=import_picocolors7.default.createColors(color),width2=Math.max(24,opts.width??120),{groups,used,tooling,unused}=listSections(report),lines=[opts.header?terminalHeader("list",opts.header,color):c.bold("uptide list"),""],stat=(n,label)=>`${c.bold(String(n))} ${label}`;lines.push([stat(report.packages.length,"outdated"),...report.unknown?.length?[stat(report.unknown.length,notCheckedLabel(report))]:[],stat(report.packages.filter(p=>p.change==="major").length,"major"),stat(report.packages.filter(p=>p.change==="minor").length,"minor"),...report.packages.some(p=>p.change==="patch")?[stat(report.packages.filter(p=>p.change==="patch").length,"patch")]:[],stat(groups.length,groups.length===1?"group":"groups"),stat(tooling.length,"tooling")].join(" "),"");for(let warning of report.scanWarnings??[]){let rest=warning;for(;rest.length>width2;){let space=rest.lastIndexOf(" ",width2),end=space>0?space:width2;lines.push(c.yellow(rest.slice(0,end))),rest=rest.slice(end).trimStart()}lines.push(c.yellow(rest),"")}let priorities=report.priorities??[];if(report.packages.length){lines.push(`${c.bold("PRIORITIES")} ${c.dim(`most urgent first \xB7 ${advisoryStatus(report)}`)}`);let tone=signal=>signal==="security"?"red":signal==="deprecated"||signal==="unsupported"?"yellow":void 0,urgent=priorities.filter(p=>p.tier==="urgent"),planning=priorities.filter(p=>p.tier!=="urgent"),top=urgent.slice(0,opts.all?urgent.length:PRIORITY_ROWS),shownRows=[...top,...opts.all?planning:[]],longest=texts=>Math.max(0,...texts.map(t=>t.length)),oneLine=4+longest(shownRows.map(p=>p.name))+3+longest(shownRows.map(p=>p.reason))+3+longest(shownRows.map(p=>priorityCommand(p,opts)))<=width2,formatted2=alignedRows(shownRows.map(p=>[{text:p.name,tone:"bold"},{text:p.reason,...tone(p.signal)?{tone:tone(p.signal)}:{}},...oneLine?[{text:priorityCommand(p,opts),tone:"dim"}]:[]]),width2,color,4),tierRows=(rows2,offset)=>rows2.forEach((p,i)=>{lines.push(formatted2[offset+i]),oneLine||lines.push(c.dim(` ${priorityCommand(p,opts)}`))});priorities.length&&(lines.push(` ${c.bold("Urgent")} ${urgent.length}${c.dim(urgent.length?" \xB7 advisories, deprecations":" \xB7 no advisories or deprecations")}`),tierRows(top,0),top.length<urgent.length&&lines.push(c.dim(` + ${urgent.length-top.length} more \xB7 --all`)),lines.push(` ${c.bold("Worth planning")} ${planning.length}${c.dim(` \xB7 unsupported, drift, blocking, majors behind${opts.all||!planning.length?"":" \xB7 --all"}`)}`),opts.all&&tierRows(planning,top.length)),priorities.length||(lines.push(" Nothing urgent: no advisories, deprecations, unsupported lines or blocking peers."),report.cheapBatch?.length&&lines.push(...alignedRows([[{text:"cheap batch",tone:"bold"},{text:`${cheapBatchLabel(report.cheapBatch)}: minor/patch, few files, one PR`},{text:cheapBatchCommand(report.cheapBatch,opts),tone:"dim"}]],width2,color,2))),lines.push("")}let showWorkspaces=report.workspaces.some(w=>w!=="."),cells=p=>[{text:p.name,tone:"bold"},{text:listVersions(p),alignAt:"\u2192"},{text:listChange(p),tone:p.change==="major"?"yellow":"dim"},{text:p.peerOf?`peer of ${p.peerOf.join(", ")}`:plural3(p.usage.files,"file"),...p.peerOf?{tone:"dim",span:"rest"}:{}},{text:!p.peerOf&&p.usage.callSites?plural3(p.usage.callSites,"call"):""},{text:!p.peerOf&&p.usage.references?plural3(p.usage.references,"ref"):""},{text:p.tier==="verified"?"verified":"",tone:"green"},...showWorkspaces?[{text:p.versions?listSpread(p):p.workspaces.join(", "),tone:"dim"}]:[]],buildMajors=tooling.filter(p=>buildToolMajor(p)),shown=[...groups.flatMap(g=>g.members),...used.filter(p=>opts.all||p.change==="major"),...opts.all?[...tooling,...unused]:buildMajors],formatted=alignedRows(shown.map(cells),width2,color,2),rows=new Map(shown.map((p,i)=>[dependencyKey(p),formatted[i]])),row=p=>{let rendered=rows.get(dependencyKey(p))??"";lines.push(rendered),p.versions&&!rendered.includes(listSpread(p))&&lines.push(c.dim(` ${listSpread(p)}`));let build=buildToolMajor(p);if(build)lines.push(c.yellow(` ${build}`));else if(p.classification==="tooling"||p.classification==="possibly-unused")for(let reason of listReasons(p))lines.push(c.dim(ellipsis(` ${reason}`,width2)));if(opts.details&&listSymbols(p)&&lines.push(c.dim(ellipsis(` symbols ${listSymbols(p)}`,width2))),opts.details&&p.usage.fileList?.length)for(let file of p.usage.fileList)lines.push(c.dim(ellipsis(` ${file}`,width2)))},group=g=>{let command=groupCommand(g,opts),head=`${c.bold(g.name)}${" ".repeat(Math.max(0,12-g.name.length))} ${groupCount(g)} ${groupVersions(g)}`,fits=textWidth(head)+3+command.length<=width2;lines.push(fits?`${head} ${c.dim(command)}`:head),fits||lines.push(c.dim(` ${command}`));for(let p of g.members)row(p)};if(groups.length){lines.push(`${c.bold("GROUPS")} ${c.dim("upgrade together")}`);for(let g of groups)group(g);lines.push("")}if(used.length){lines.push(c.bold("PACKAGES"));for(let p of used.filter(p2=>opts.all||p2.change==="major"))row(p);let count=used.filter(p=>p.change!=="major").length;!opts.all&&count&&lines.push(c.dim(` + ${count} minor/patch \xB7 --all`)),lines.push("")}for(let[label,packages,hint]of[["TOOLING",tooling,"used by scripts and config"],["POSSIBLY UNUSED",unused,UNUSED_HINT]])if(packages.length){if(lines.push(`${c.bold(label)} ${c.dim(`${plural3(packages.length,"package")}, ${hint}${opts.all?"":" \xB7 --all"}`)}`),!opts.all&&label==="TOOLING")for(let p of buildMajors)row(p);if(opts.all)for(let block of listBlocks(packages,report))if(block.name)group(block);else for(let p of block.members)row(p);lines.push("")}for(let group2 of skippedSources(report))if(lines.push(c.dim(`${plural3(group2.members.length,"package")} ${group2.reason}${opts.all||opts.details?"":" \xB7 --all"}`)),opts.all||opts.details)for(let item of group2.members)lines.push(` ${c.bold(item.name)}${showWorkspaces&&opts.details?c.dim(` \xB7 ${item.workspaces.join(", ")}`):""}`);report.skipped?.length&&lines.push(""),!report.packages.length&&!report.failures.length&&!report.unknown?.length&&!report.skipped?.length&&lines.push("Every direct dependency is up to date.",""),lines.push(...listFailureLines(report,opts.details)),lines.push(c.dim("Usage is a syntax scan, no type analysis."),c.dim("Generic analysis is the default; verified means a migration pack is available."));let first=used[0]??tooling[0]??unused[0],next=groups[0]??report.groups.find(g=>g.members.some(p=>p.name===first?.name)),nextCommand=priorities[0]?priorityCommand(priorities[0],opts):report.cheapBatch?.length?cheapBatchCommand(report.cheapBatch,opts):next?groupCommand(next,opts):first?listCommand([first],opts):void 0;return nextCommand&&lines.push(`${c.bold("Next")} ${nextCommand}`),`${lines.join(`
54
+ `)}function formatList(report,opts={}){let color=opts.color??!1,c=import_picocolors7.default.createColors(color),width2=Math.max(24,opts.width??120),{groups,used,tooling,unused}=listSections(report),lines=[opts.header?terminalHeader("list",opts.header,color):c.bold("uptide list"),""],stat=(n,label)=>`${c.bold(String(n))} ${label}`;lines.push([stat(report.packages.length,"outdated"),...report.unknown?.length?[stat(report.unknown.length,notCheckedLabel(report))]:[],stat(report.packages.filter(p=>p.change==="major").length,"major"),stat(report.packages.filter(p=>p.change==="minor").length,"minor"),...report.packages.some(p=>p.change==="patch")?[stat(report.packages.filter(p=>p.change==="patch").length,"patch")]:[],stat(groups.length,groups.length===1?"group":"groups"),stat(tooling.length,"tooling")].join(" "),"");for(let warning of report.scanWarnings??[]){let rest=warning;for(;rest.length>width2;){let space=rest.lastIndexOf(" ",width2),end=space>0?space:width2;lines.push(c.yellow(rest.slice(0,end))),rest=rest.slice(end).trimStart()}lines.push(c.yellow(rest),"")}let priorities=report.priorities??[];if(report.packages.length){lines.push(`${c.bold("PRIORITIES")} ${c.dim(`most urgent first \xB7 ${advisoryStatus(report)}`)}`);let tone=signal=>signal==="security"?"red":signal==="deprecated"||signal==="unsupported"?"yellow":void 0,urgent=priorities.filter(p=>p.tier==="urgent"),planning=priorities.filter(p=>p.tier!=="urgent"),top=urgent.slice(0,opts.all?urgent.length:PRIORITY_ROWS),shownRows=[...top,...opts.all?planning:[]],longest=texts=>Math.max(0,...texts.map(t=>t.length)),oneLine=4+longest(shownRows.map(p=>p.name))+3+longest(shownRows.map(p=>p.reason))+3+longest(shownRows.map(p=>priorityCommand(p,opts)))<=width2,formatted2=alignedRows(shownRows.map(p=>[{text:p.name,tone:"bold"},{text:p.reason,...tone(p.signal)?{tone:tone(p.signal)}:{}},...oneLine?[{text:priorityCommand(p,opts),tone:"dim"}]:[]]),width2,color,4),tierRows=(rows2,offset)=>rows2.forEach((p,i)=>{lines.push(formatted2[offset+i]),oneLine||lines.push(c.dim(` ${priorityCommand(p,opts)}`))});priorities.length&&(lines.push(` ${c.bold("Urgent")} ${urgent.length}${c.dim(urgent.length?" \xB7 advisories, deprecations":" \xB7 no advisories or deprecations")}`),tierRows(top,0),top.length<urgent.length&&lines.push(c.dim(` + ${urgent.length-top.length} more \xB7 --all`)),lines.push(` ${c.bold("Worth planning")} ${planning.length}${c.dim(` \xB7 unsupported, drift, blocking, majors behind${opts.all||!planning.length?"":" \xB7 --all"}`)}`),opts.all&&tierRows(planning,top.length)),priorities.length||(lines.push(" Nothing urgent: no advisories, deprecations, unsupported lines or blocking peers."),report.cheapBatch?.length&&lines.push(...alignedRows([[{text:"cheap batch",tone:"bold"},{text:`${cheapBatchLabel(report.cheapBatch)}: minor/patch, few files, one PR`},{text:cheapBatchCommand(report.cheapBatch,opts),tone:"dim"}]],width2,color,2))),lines.push("")}let showWorkspaces=report.workspaces.some(w=>w!=="."),cells=p=>[{text:p.name,tone:"bold"},{text:listVersions(p),alignAt:"\u2192"},{text:listChange(p),tone:p.change==="major"?"yellow":"dim"},{text:p.peerOf?`peer of ${p.peerOf.join(", ")}`:plural3(p.usage.files,"file"),...p.peerOf?{tone:"dim",span:"rest"}:{}},{text:!p.peerOf&&p.usage.callSites?plural3(p.usage.callSites,"call"):""},{text:!p.peerOf&&p.usage.references?plural3(p.usage.references,"ref"):""},{text:p.tier==="verified"?"verified":"",tone:"green"},...showWorkspaces?[{text:p.versions?listSpread(p):p.workspaces.join(", "),tone:"dim"}]:[]],buildMajors=tooling.filter(p=>buildToolMajor(p)),shown=[...groups.flatMap(g=>g.members),...used.filter(p=>opts.all||p.change==="major"),...opts.all?[...tooling,...unused]:buildMajors],formatted=alignedRows(shown.map(cells),width2,color,2),rows=new Map(shown.map((p,i)=>[dependencyKey(p),formatted[i]])),row2=p=>{let rendered=rows.get(dependencyKey(p))??"";lines.push(rendered),p.versions&&!rendered.includes(listSpread(p))&&lines.push(c.dim(` ${listSpread(p)}`));let build=buildToolMajor(p);if(build)lines.push(c.yellow(` ${build}`));else if(p.classification==="tooling"||p.classification==="possibly-unused")for(let reason of listReasons(p))lines.push(c.dim(ellipsis(` ${reason}`,width2)));if(opts.details&&listSymbols(p)&&lines.push(c.dim(ellipsis(` symbols ${listSymbols(p)}`,width2))),opts.details&&p.usage.fileList?.length)for(let file of p.usage.fileList)lines.push(c.dim(ellipsis(` ${file}`,width2)))},group=g=>{let command=groupCommand(g,opts),head=`${c.bold(g.name)}${" ".repeat(Math.max(0,12-g.name.length))} ${groupCount(g)} ${groupVersions(g)}`,fits=textWidth(head)+3+command.length<=width2;lines.push(fits?`${head} ${c.dim(command)}`:head),fits||lines.push(c.dim(` ${command}`));for(let p of g.members)row2(p)};if(groups.length){lines.push(`${c.bold("GROUPS")} ${c.dim("upgrade together")}`);for(let g of groups)group(g);lines.push("")}if(used.length){lines.push(c.bold("PACKAGES"));for(let p of used.filter(p2=>opts.all||p2.change==="major"))row2(p);let count=used.filter(p=>p.change!=="major").length;!opts.all&&count&&lines.push(c.dim(` + ${count} minor/patch \xB7 --all`)),lines.push("")}for(let[label,packages,hint]of[["TOOLING",tooling,"used by scripts and config"],["POSSIBLY UNUSED",unused,UNUSED_HINT]])if(packages.length){if(lines.push(`${c.bold(label)} ${c.dim(`${plural3(packages.length,"package")}, ${hint}${opts.all?"":" \xB7 --all"}`)}`),!opts.all&&label==="TOOLING")for(let p of buildMajors)row2(p);if(opts.all)for(let block of listBlocks(packages,report))if(block.name)group(block);else for(let p of block.members)row2(p);lines.push("")}for(let group2 of skippedSources(report))if(lines.push(c.dim(`${plural3(group2.members.length,"package")} ${group2.reason}${opts.all||opts.details?"":" \xB7 --all"}`)),opts.all||opts.details)for(let item of group2.members)lines.push(` ${c.bold(item.name)}${showWorkspaces&&opts.details?c.dim(` \xB7 ${item.workspaces.join(", ")}`):""}`);report.skipped?.length&&lines.push(""),!report.packages.length&&!report.failures.length&&!report.unknown?.length&&!report.skipped?.length&&lines.push("Every direct dependency is up to date.",""),lines.push(...listFailureLines(report,opts.details)),lines.push(c.dim("Usage is a syntax scan, no type analysis."),c.dim("Generic analysis is the default; verified means a migration pack is available."));let first=used[0]??tooling[0]??unused[0],next=groups[0]??report.groups.find(g=>g.members.some(p=>p.name===first?.name)),nextCommand=priorities[0]?priorityCommand(priorities[0],opts):report.cheapBatch?.length?cheapBatchCommand(report.cheapBatch,opts):next?groupCommand(next,opts):first?listCommand([first],opts):void 0;return nextCommand&&lines.push(`${c.bold("Next")} ${nextCommand}`),`${lines.join(`
55
55
  `).split(`
56
56
  `).map(line=>{let visible=0,parts=line.split(new RegExp("(\x1B\\[[0-9;]*m)"));return parts.filter(p=>!p.startsWith("\x1B")).join("").length<=width2?line:`${parts.map(part=>{if(part.startsWith("\x1B"))return part;let left=Math.max(0,width2-1-visible),result=Array.from(part).slice(0,left).join("");return visible+=Array.from(part).length,result}).join("")}\u2026`}).join(`
57
57
  `)}
@@ -117,7 +117,7 @@ let opened=[];addEventListener('beforeprint',()=>{opened=[...document.querySelec
117
117
  ${compact?'<p class="notice">Compact report: excerpts and additional sites omitted to stay under 300 KB. Use uptide check &lt;package&gt; --details for the full report.</p>':""}${sectionLabel("02","Findings","What reaches your code")}${dependencies}${missing}
118
118
  <details class="notes"><summary>Analysis notes \xB7 ${notes.length} notes</summary><ul>${notes.slice(0,compact?30:300).map(n=>`<li>${e(n)}</li>`).join("")||`<li>${opts.details?"No analysis gaps reported.":"Use --details for analysis notes, locations and source excerpts."}</li>`}${notes.length>(compact?30:300)?"<li>Additional notes omitted; see JSON output.</li>":""}</ul></details>
119
119
  <section class="next"><h2>03 / Next</h2>${commands.map(([cmd,why])=>`<p class="muted">${e(why)}</p>${reportCommand(cmd)}`).join("")}</section>
120
- <footer>Generic analysis is the default; verified means a migration pack is available.<br>Local report \xB7 No network requests \xB7 ${opts.details?"Contains file paths and source excerpts. Review before sharing.":"No file paths or source code. Use --details for locations and excerpts."}</footer>`)}let html=render(145e3,50,1e3,!1);if(Buffer.byteLength(html)>=MAX_HTML_BYTES&&(html=render(0,10,80,!0)),Buffer.byteLength(html)>=MAX_HTML_BYTES)throw new Error("HTML report exceeds 300 KB even without excerpts; check fewer named packages.");return html}function writeHtml(report,opts,path2,cwd){let html=renderHtml(report,{...opts,readExcerpt:opts.readExcerpt??excerptReader(opts.root)});return writeReportHtml(html,opts.header?.repo??basename3(opts.root),"",path2,cwd)}function writeReportHtml(html,repo,kind,path2,cwd){let slug=repo.replace(/[^a-zA-Z0-9_-]+/g,"-").slice(0,80)||"repo",target=typeof path2=="string"?resolve4(cwd,path2):join3(tmpdir(),"uptide",`${slug}${kind?`-${kind}`:""}-${Date.now()}.html`);return mkdirSync(dirname3(target),{recursive:!0}),writeFileSync(target,html,{mode:384,flag:typeof path2=="string"?"w":"wx"}),target}function browserCommand(path2,platform=process.platform){if(platform==="darwin")return["open",[path2]];if(platform==="win32"){if(/["%&|<>^!\r\n]/.test(path2))throw new Error("Open this report manually: its path contains Windows shell metacharacters.");return["cmd.exe",["/d","/s","/c","start",'""',`"${path2}"`]]}return["xdg-open",[path2]]}async function openHtml(path2){let[bin,args]=browserCommand(path2);await new Promise((resolve8,reject)=>{let child=spawn(bin,args,{stdio:"ignore",windowsVerbatimArguments:process.platform==="win32"});child.once("error",reject),child.once("close",code=>code===0?resolve8():reject(new Error(`${bin} exited ${code}`)))})}function renderListHtml(report,opts){let{groups,used,tooling,unused}=listSections(report),failures=[...new Map(report.failures.map(f=>[f.name,f])).values()],section=0,nextSection=()=>String(++section).padStart(2,"0"),commands={...opts,cwd:opts.details?opts.cwd:void 0},priorities=report.priorities??[],urgent=new Set(priorities.flatMap(p=>p.packages)),row=(p,where,command)=>`<article class="member-grid${command?" has-command":""}" data-change="${p.change}" data-section="${where}"${urgent.has(p.name)?" data-priority":""}${p.tier==="verified"?" data-verified":""}><div class="pkg-name">${escapeHtml(p.name)}${p.tier==="verified"?'<span class="verified">verified</span>':""}</div><div class="versions">${escapeHtml(listVersions(p))}${p.versions?`<div class="muted">${escapeHtml(listSpread(p))}</div>`:""}</div><div class="gap">${escapeHtml(listChange(p))}</div><div class="usage${p.peerOf?" muted":""}">${p.peerOf?`peer of ${escapeHtml(p.peerOf.join(", "))}`:escapeHtml(listUsage(p))}</div>${command?reportCopyButton(command):""}${buildToolMajor(p)?`<div class="details-line deprecated">${escapeHtml(buildToolMajor(p))}</div>`:""}${(p.classification==="tooling"||p.classification==="possibly-unused")&&listReasons(p).length?`<div class="details-line">${listReasons(p).map(escapeHtml).join(" \xB7 ")}</div>`:""}${opts.details&&listSymbols(p)?`<div class="details-line">Top symbols: ${escapeHtml(listSymbols(p))}</div>`:""}${opts.details&&p.usage.fileList?.length?`<details class="details-line"><summary>Files</summary><ul>${p.usage.fileList.map(file=>`<li>${escapeHtml(file)}</li>`).join("")}</ul></details>`:""}</article>`,group=(g,where)=>`<section class="package"${where==="group"?" data-group":""}><header><h2>${escapeHtml(g.name)}</h2><div class="meta"><span>${escapeHtml(groupCount(g))}</span><span>${escapeHtml(groupVersions(g))}</span>${g.reason?`<span>${escapeHtml(g.reason)}</span>`:""}</div>${reportCommand(groupCommand(g,commands))}</header>${g.members.map(p=>row(p,where)).join("")}</section>`,standalone=(p,where)=>row(p,where,listCommand([p],commands)),collapsed=(label,packages,where)=>packages.length?`<details class="notes" data-block><summary>${nextSection()} / ${label} / ${packages.length} package${packages.length===1?"":"s"}${packages.some(p=>buildToolMajor(p))?` \xB7 <span class="deprecated">${escapeHtml(packages.filter(p=>buildToolMajor(p)).map(p=>p.name).join(", "))}: build tool major</span>`:""}</summary>${label==="Possibly unused"?`<p class="more">${escapeHtml(UNUSED_HINT)}</p>`:""}${listBlocks(packages,report).map(block=>block.name?group(block,where):block.members.map(p=>standalone(p,where)).join("")).join("")}</details>`:"",priorityBlock=()=>{if(!report.packages.length)return"";let list2=rows2=>`<ol class="priority-list">${rows2.map(p=>`<li class="priority-row signal-${p.signal}"><div class="pkg-name">${escapeHtml(p.name)}</div><div class="reason">${escapeHtml(p.reason)}</div>${reportCommand(priorityCommand(p,commands))}</li>`).join("")}</ol>`,urgentRows=priorities.filter(p=>p.tier==="urgent"),planning=priorities.filter(p=>p.tier!=="urgent"),rows=priorities.length?`<p class="more"><strong>Urgent \xB7 ${urgentRows.length}</strong> <span class="muted">advisories, deprecations</span></p>${urgentRows.length?list2(urgentRows):""}${planning.length?`<details class="notes"><summary>Worth planning \xB7 ${planning.length} <span class="muted">unsupported, drift, blocking, majors behind</span></summary>${list2(planning)}</details>`:""}`:`<p class="more">Nothing urgent: no advisories, deprecations, unsupported lines or blocking peers.</p>${report.cheapBatch?.length?`<ol class="priority-list"><li class="priority-row"><div class="pkg-name">Cheap batch</div><div class="reason">${escapeHtml(cheapBatchLabel(report.cheapBatch,8))}: minor/patch, few files, one PR</div>${reportCommand(cheapBatchCommand(report.cheapBatch,commands))}</li></ol>`:""}`;return`<section class="priorities">${sectionLabel(nextSection(),"Priorities",`Most urgent first \xB7 ${advisoryStatus(report)}`)}${rows}</section>`},repo=opts.header?.repo??basename4(report.repo),count=change=>report.packages.filter(p=>p.change===change).length;return reportDocument(`Uptide list \xB7 ${repo}`,`${reportHeader({kind:"list",repo,manager:opts.header?.manager??"Package manager unavailable",...opts})}${reportStats([{label:"Outdated",value:report.packages.length,filter:"all"},...report.unknown?.length?[{label:"Unknown",value:report.unknown.length,tone:"warn"}]:[],{label:"Major",value:count("major"),tone:"warn",filter:"major"},{label:"Minor",value:count("minor"),filter:"minor"},{label:"Patch",value:count("patch"),filter:"patch"},{label:"Groups",value:groups.length,filter:"groups"},{label:"Tooling",value:tooling.length,filter:"tooling"},{label:"Priority",value:report.packages.filter(p=>urgent.has(p.name)).length,tone:priorities.length?"warn":"safe",filter:"priority"},{label:"Verified",value:report.packages.filter(p=>p.tier==="verified").length,filter:"verified"},{label:"Possibly unused",value:unused.length,filter:"unused"}])}
120
+ <footer>Generic analysis is the default; verified means a migration pack is available.<br>Local report \xB7 No network requests \xB7 ${opts.details?"Contains file paths and source excerpts. Review before sharing.":"No file paths or source code. Use --details for locations and excerpts."}</footer>`)}let html=render(145e3,50,1e3,!1);if(Buffer.byteLength(html)>=MAX_HTML_BYTES&&(html=render(0,10,80,!0)),Buffer.byteLength(html)>=MAX_HTML_BYTES)throw new Error("HTML report exceeds 300 KB even without excerpts; check fewer named packages.");return html}function writeHtml(report,opts,path2,cwd){let html=renderHtml(report,{...opts,readExcerpt:opts.readExcerpt??excerptReader(opts.root)});return writeReportHtml(html,opts.header?.repo??basename3(opts.root),"",path2,cwd)}function writeReportHtml(html,repo,kind,path2,cwd){let slug=repo.replace(/[^a-zA-Z0-9_-]+/g,"-").slice(0,80)||"repo",target=typeof path2=="string"?resolve4(cwd,path2):join3(tmpdir(),"uptide",`${slug}${kind?`-${kind}`:""}-${Date.now()}.html`);return mkdirSync(dirname3(target),{recursive:!0}),writeFileSync(target,html,{mode:384,flag:typeof path2=="string"?"w":"wx"}),target}function browserCommand(path2,platform=process.platform){if(platform==="darwin")return["open",[path2]];if(platform==="win32"){if(/["%&|<>^!\r\n]/.test(path2))throw new Error("Open this report manually: its path contains Windows shell metacharacters.");return["cmd.exe",["/d","/s","/c","start",'""',`"${path2}"`]]}return["xdg-open",[path2]]}async function openHtml(path2){let[bin,args]=browserCommand(path2);await new Promise((resolve8,reject)=>{let child=spawn(bin,args,{stdio:"ignore",windowsVerbatimArguments:process.platform==="win32"});child.once("error",reject),child.once("close",code=>code===0?resolve8():reject(new Error(`${bin} exited ${code}`)))})}function renderListHtml(report,opts){let{groups,used,tooling,unused}=listSections(report),failures=[...new Map(report.failures.map(f=>[f.name,f])).values()],section=0,nextSection=()=>String(++section).padStart(2,"0"),commands={...opts,cwd:opts.details?opts.cwd:void 0},priorities=report.priorities??[],urgent=new Set(priorities.flatMap(p=>p.packages)),row2=(p,where,command)=>`<article class="member-grid${command?" has-command":""}" data-change="${p.change}" data-section="${where}"${urgent.has(p.name)?" data-priority":""}${p.tier==="verified"?" data-verified":""}><div class="pkg-name">${escapeHtml(p.name)}${p.tier==="verified"?'<span class="verified">verified</span>':""}</div><div class="versions">${escapeHtml(listVersions(p))}${p.versions?`<div class="muted">${escapeHtml(listSpread(p))}</div>`:""}</div><div class="gap">${escapeHtml(listChange(p))}</div><div class="usage${p.peerOf?" muted":""}">${p.peerOf?`peer of ${escapeHtml(p.peerOf.join(", "))}`:escapeHtml(listUsage(p))}</div>${command?reportCopyButton(command):""}${buildToolMajor(p)?`<div class="details-line deprecated">${escapeHtml(buildToolMajor(p))}</div>`:""}${(p.classification==="tooling"||p.classification==="possibly-unused")&&listReasons(p).length?`<div class="details-line">${listReasons(p).map(escapeHtml).join(" \xB7 ")}</div>`:""}${opts.details&&listSymbols(p)?`<div class="details-line">Top symbols: ${escapeHtml(listSymbols(p))}</div>`:""}${opts.details&&p.usage.fileList?.length?`<details class="details-line"><summary>Files</summary><ul>${p.usage.fileList.map(file=>`<li>${escapeHtml(file)}</li>`).join("")}</ul></details>`:""}</article>`,group=(g,where)=>`<section class="package"${where==="group"?" data-group":""}><header><h2>${escapeHtml(g.name)}</h2><div class="meta"><span>${escapeHtml(groupCount(g))}</span><span>${escapeHtml(groupVersions(g))}</span>${g.reason?`<span>${escapeHtml(g.reason)}</span>`:""}</div>${reportCommand(groupCommand(g,commands))}</header>${g.members.map(p=>row2(p,where)).join("")}</section>`,standalone=(p,where)=>row2(p,where,listCommand([p],commands)),collapsed=(label,packages,where)=>packages.length?`<details class="notes" data-block><summary>${nextSection()} / ${label} / ${packages.length} package${packages.length===1?"":"s"}${packages.some(p=>buildToolMajor(p))?` \xB7 <span class="deprecated">${escapeHtml(packages.filter(p=>buildToolMajor(p)).map(p=>p.name).join(", "))}: build tool major</span>`:""}</summary>${label==="Possibly unused"?`<p class="more">${escapeHtml(UNUSED_HINT)}</p>`:""}${listBlocks(packages,report).map(block=>block.name?group(block,where):block.members.map(p=>standalone(p,where)).join("")).join("")}</details>`:"",priorityBlock=()=>{if(!report.packages.length)return"";let list2=rows2=>`<ol class="priority-list">${rows2.map(p=>`<li class="priority-row signal-${p.signal}"><div class="pkg-name">${escapeHtml(p.name)}</div><div class="reason">${escapeHtml(p.reason)}</div>${reportCommand(priorityCommand(p,commands))}</li>`).join("")}</ol>`,urgentRows=priorities.filter(p=>p.tier==="urgent"),planning=priorities.filter(p=>p.tier!=="urgent"),rows=priorities.length?`<p class="more"><strong>Urgent \xB7 ${urgentRows.length}</strong> <span class="muted">advisories, deprecations</span></p>${urgentRows.length?list2(urgentRows):""}${planning.length?`<details class="notes"><summary>Worth planning \xB7 ${planning.length} <span class="muted">unsupported, drift, blocking, majors behind</span></summary>${list2(planning)}</details>`:""}`:`<p class="more">Nothing urgent: no advisories, deprecations, unsupported lines or blocking peers.</p>${report.cheapBatch?.length?`<ol class="priority-list"><li class="priority-row"><div class="pkg-name">Cheap batch</div><div class="reason">${escapeHtml(cheapBatchLabel(report.cheapBatch,8))}: minor/patch, few files, one PR</div>${reportCommand(cheapBatchCommand(report.cheapBatch,commands))}</li></ol>`:""}`;return`<section class="priorities">${sectionLabel(nextSection(),"Priorities",`Most urgent first \xB7 ${advisoryStatus(report)}`)}${rows}</section>`},repo=opts.header?.repo??basename4(report.repo),count=change=>report.packages.filter(p=>p.change===change).length;return reportDocument(`Uptide list \xB7 ${repo}`,`${reportHeader({kind:"list",repo,manager:opts.header?.manager??"Package manager unavailable",...opts})}${reportStats([{label:"Outdated",value:report.packages.length,filter:"all"},...report.unknown?.length?[{label:"Unknown",value:report.unknown.length,tone:"warn"}]:[],{label:"Major",value:count("major"),tone:"warn",filter:"major"},{label:"Minor",value:count("minor"),filter:"minor"},{label:"Patch",value:count("patch"),filter:"patch"},{label:"Groups",value:groups.length,filter:"groups"},{label:"Tooling",value:tooling.length,filter:"tooling"},{label:"Priority",value:report.packages.filter(p=>urgent.has(p.name)).length,tone:priorities.length?"warn":"safe",filter:"priority"},{label:"Verified",value:report.packages.filter(p=>p.tier==="verified").length,filter:"verified"},{label:"Possibly unused",value:unused.length,filter:"unused"}])}
121
121
  <div class="filter-status" role="status" hidden><span data-filter-label></span><button type="button" data-filter-clear>Clear</button></div>
122
122
  <p class="more" data-filter-empty hidden>No packages match this filter.</p>
123
123
  <div data-list>
@@ -142,7 +142,7 @@ ${failures.length?`<section class="notes">${sectionLabel(nextSection(),"Incomple
142
142
  `}function writeMigrationHtml(report,opts){let dir=dirname4(report.prBody),path2=join4(dir,"report.html");mkdirSync2(dir,{recursive:!0}),writeFileSync2(path2,renderMigrationHtml(report,opts),{mode:384});let stored=join4(dir,"report.json");if(existsSync3(stored))try{let saved=JSON.parse(readFileSync4(stored,"utf8"));writeFileSync2(stored,JSON.stringify({...saved,html:path2},null,2))}catch{}return path2}function inline(text){let parts=[],pattern=/`([^`]+)`|\*\*([^*]+)\*\*|\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g,last=0;for(let m of text.matchAll(pattern))parts.push(escapeHtml(text.slice(last,m.index))),m[1]!==void 0?parts.push(`<code>${escapeHtml(m[1])}</code>`):m[2]!==void 0?parts.push(`<strong>${inline(m[2])}</strong>`):parts.push(`<a href="${escapeHtml(m[4])}">${inline(m[3])}</a>`),last=(m.index??0)+m[0].length;return parts.push(escapeHtml(text.slice(last))),parts.join("")}function markdownToHtml(markdown){let lines=markdown.split(`
143
143
  `),out=[],i=0,list2=!1,closeList=()=>{list2&&out.push("</ul>"),list2=!1};for(;i<lines.length;){let line=lines[i];if(line.startsWith("```")){closeList();let lang=line.slice(3).trim(),body=[];for(i++;i<lines.length&&!lines[i].startsWith("```");)body.push(lines[i]),i++;i++;let rendered=lang==="diff"?body.map(l=>l.startsWith("+")&&!l.startsWith("+++")?`<span class="diff-add">${escapeHtml(l)}</span>`:l.startsWith("-")&&!l.startsWith("---")?`<span class="diff-del">${escapeHtml(l)}</span>`:escapeHtml(l)).join(`
144
144
  `):escapeHtml(body.join(`
145
- `));out.push(`<pre><code>${rendered}</code></pre>`);continue}let heading=/^(#{1,6})\s+(.*)$/.exec(line);if(heading){closeList();let level=heading[1].length;out.push(`<h${level}>${inline(heading[2])}</h${level}>`),i++;continue}if(/^(?:<details>)?(?:<summary>|<\/details>)|^<details>$/.test(line)){closeList(),out.push(line.replace(/<summary>(.*)<\/summary>/,(_,t)=>`<summary>${inline(t)}</summary>`)),i++;continue}if(line.startsWith("|")){closeList();let rows=[];for(;i<lines.length&&lines[i].startsWith("|");){let row=lines[i];if(i++,/^\|[\s-|]*\|$/.test(row))continue;let cells=row.slice(1,row.endsWith("|")?-1:void 0).split("|");rows.push(`<tr>${cells.map(c=>`<td>${inline(c.trim())}</td>`).join("")}</tr>`)}out.push(`<table>${rows.join("")}</table>`);continue}if(/^- /.test(line)){list2||out.push("<ul>"),list2=!0,out.push(`<li>${inline(line.slice(2))}</li>`),i++;continue}if(line.trim()===""){closeList(),i++;continue}if(line==="---"){closeList(),out.push("<hr>"),i++;continue}closeList(),out.push(`<p>${inline(line)}</p>`),i++}return closeList(),out.join(`
145
+ `));out.push(`<pre><code>${rendered}</code></pre>`);continue}let heading=/^(#{1,6})\s+(.*)$/.exec(line);if(heading){closeList();let level=heading[1].length;out.push(`<h${level}>${inline(heading[2])}</h${level}>`),i++;continue}if(/^(?:<details>)?(?:<summary>|<\/details>)|^<details>$/.test(line)){closeList(),out.push(line.replace(/<summary>(.*)<\/summary>/,(_,t)=>`<summary>${inline(t)}</summary>`)),i++;continue}if(line.startsWith("|")){closeList();let rows=[];for(;i<lines.length&&lines[i].startsWith("|");){let row2=lines[i];if(i++,/^\|[\s-|]*\|$/.test(row2))continue;let cells=row2.slice(1,row2.endsWith("|")?-1:void 0).split("|");rows.push(`<tr>${cells.map(c=>`<td>${inline(c.trim())}</td>`).join("")}</tr>`)}out.push(`<table>${rows.join("")}</table>`);continue}if(/^- /.test(line)){list2||out.push("<ul>"),list2=!0,out.push(`<li>${inline(line.slice(2))}</li>`),i++;continue}if(line.trim()===""){closeList(),i++;continue}if(line==="---"){closeList(),out.push("<hr>"),i++;continue}closeList(),out.push(`<p>${inline(line)}</p>`),i++}return closeList(),out.join(`
146
146
  `)}import{mkdirSync as mkdirSync3,writeFileSync as writeFileSync3}from"fs";import{tmpdir as tmpdir2}from"os";import{dirname as dirname5,join as join5,resolve as resolve5}from"path";function renderPlanHtml(plan,opts){let e=escapeHtml,uptide=opts.invocation??"npx uptide",tone={unknown:"unverified",none:"safe",small:"deprecated",medium:"unverified",large:"breaking"},steps=plan.steps.map(step=>{let packages=step.packages.map(p=>`<article class="site"><div class="mono">${e(p.name)} ${e(p.installed)} \u2192 ${e(p.target)} \xB7 ${e(p.tier)}</div><p class="muted">${e(effortLine(p.effort))}</p>${opts.fixable&&p.effort.level!=="none"?`<div class="command"><code>${e(`${uptide} ${p.effort.level==="unknown"?"check":"fix"} ${p.name}`)}</code></div>`:""}</article>`).join(""),constraints=step.constraints.map(c=>`<p class="more ${c.effect==="blocked"?"breaking":"unverified"}">${c.effect==="blocked"?"Blocked: ":"Peer: "}${e(c.reason)}</p>`).join("");return`<section class="package" id="step-${step.order}"><header><h2>${step.order}. ${e(stepTitle(step))}</h2><span class="mono ${tone[step.effort]}">effort: ${e(step.effort)}</span></header>${constraints}${packages}</section>`}).join(""),notPlanned=plan.notPlanned.length?`<section class="package" id="not-planned"><header><h2>Not planned</h2></header>${plan.notPlanned.map(p=>`<p class="more">${e(p.name)} ${e(p.installed)}: ${e(p.reason)}</p>`).join("")}</section>`:"",when=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short",timeZone:opts.timeZone}).format(new Date(opts.date));return`<!doctype html>
147
147
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; connect-src 'none'; base-uri 'none'; form-action 'none'"><meta name="referrer" content="no-referrer"><title>Uptide plan \xB7 ${e(opts.header?.repo??"repository")}</title><style>${css}</style></head>
148
148
  <body><main><header><div class="brand">UPTIDE / PLAN</div><h1>${e(opts.header?.repo??"Upgrade plan")}</h1><div class="meta"><span>${e(opts.header?.manager??"")}</span><time datetime="${e(opts.date)}">${e(when)}</time><span>Uptide CLI ${e(opts.version)}</span><span>${elapsed(opts.header?.ms??0)}</span></div><p class="muted">${plan.steps.length} ${plan.steps.length===1?"step":"steps"}, in the order to take them.${plan.notPlanned.length?` ${plan.notPlanned.length} not planned.`:""}</p><p class="muted">${e(TIER_LEGEND)}</p></header>
@@ -151,9 +151,11 @@ ${steps||'<p class="more safe">\u2713 Nothing to plan: every analyzed dependency
151
151
  <footer>Effort is an estimate from the findings: none (nothing affected), small (rules, or up to 5 sites by hand or agent), medium (up to 25), large (more). Local page \xB7 No network requests.</footer></main></body></html>`}function writePlanHtml(plan,opts,path2,cwd){let slug=(opts.header?.repo??"repo").replace(/[^a-zA-Z0-9_-]+/g,"-").slice(0,80)||"repo",target=typeof path2=="string"?resolve5(cwd,path2):join5(tmpdir2(),"uptide",`${slug}-plan-${Date.now()}.html`);return mkdirSync3(dirname5(target),{recursive:!0}),writeFileSync3(target,renderPlanHtml(plan,opts),{mode:384,flag:typeof path2=="string"?"w":"wx"}),target}import{createInterface}from"readline";function processIo(){return{out:text=>{process.stdout.write(text)},err:text=>{process.stderr.write(text)},env:process.env,cwd:process.cwd(),outTty:process.stdout.isTTY===!0,columns:process.stdout.columns,errTty:process.stderr.isTTY===!0,now:()=>Date.now(),inTty:process.stdin.isTTY===!0,confirmTelemetry:()=>new Promise(resolve8=>{let rl=createInterface({input:process.stdin,output:process.stderr,terminal:!0}),settled=!1,done=yes=>{settled||(settled=!0,rl.close(),resolve8(yes))};rl.on("SIGINT",()=>done(!1)),rl.on("close",()=>done(!1)),rl.question(`Share anonymous CLI usage with Uptide (PostHog EU, 90-day retention)?
152
152
  Random IDs, public package versions and aggregate counts only; no IP, code, paths or repo names.
153
153
  Details: https://github.com/uptide-dev/uptide/blob/main/docs/telemetry.md
154
- Enable telemetry? [y/N] `,answer=>done(/^y(?:es)?$/i.test(answer.trim())))})}}function uiOf(io2,flags){let ci=flags.ci===!0||io2.env.CI!==void 0&&io2.env.CI!==""&&io2.env.CI!=="0",noColor=io2.env.NO_COLOR!==void 0&&io2.env.NO_COLOR!=="",forced=io2.env.FORCE_COLOR!==void 0&&io2.env.FORCE_COLOR!=="0";return{color:!ci&&flags.color!==!1&&!noColor&&(io2.outTty||forced),interactive:!ci&&io2.errTty&&io2.env.TERM!=="dumb"}}var PRIVACY="Privacy:\n Analysis runs locally. Code snippets go to your chosen LLM provider (Anthropic, OpenAI or Gemini), only\n for assisted fixes in `uptide fix`, and only with your own API key from ANTHROPIC_API_KEY,\n OPENAI_API_KEY or GEMINI_API_KEY: for each\n site the rules cannot migrate, the finding, the enclosing function and the compiler\n error. `uptide fix --no-llm` turns assisted fixes off. No account.\n Anonymous telemetry is off by default and asks for consent in an interactive terminal.\n Set UPTIDE_TELEMETRY=0 to disable it. No IP, code, paths or repo names are collected.\n Other network use: your npm registry for package metadata and tarballs, npm's advisory\n endpoint from `list` (public package names and installed versions; `--no-advisories` turns\n it off), PostHog EU only\n after telemetry opt-in, and GitHub when you pass `fix --pr` or run `pr` / `pr-body`.\n";import{join as join6}from"path";var import_picocolors9=__toESM(require_picocolors(),1);var SUPPORTED=["zod","stripe"];async function locateDependencies(repo,engine,names2=SUPPORTED){let dependencies=names2.map(name=>({name,workspaces:[],catalog:!1}));for(let workspace of repo.workspaces){let dir=join6(repo.root,workspace),[installed,declared]=await Promise.all([engine.installed(dir),engine.declared(dir)]);for(let dep of dependencies){let spec=declared.get(dep.name);if(spec===void 0)continue;dep.workspaces.push(workspace),spec.startsWith("catalog:")&&(dep.catalog=!0);let version=installed.get(dep.name);version&&(!dep.installed||compareVersions(version,dep.installed)<0)&&(dep.installed=version)}}return dependencies}async function declaredDependencies(repo,engine){let names2=new Set;for(let workspace of repo.workspaces){let declared=await engine.declared(join6(repo.root,workspace));for(let[name,spec]of declared)/^(workspace|link|file):/.test(spec)||names2.add(name)}return[...names2].sort()}async function collectStatus(repo,engine,names2=SUPPORTED){let dependencies=await locateDependencies(repo,engine,names2),registryError;return await Promise.all(dependencies.filter(dep=>dep.workspaces.length>0).map(async dep=>{try{dep.latest=await engine.latest(dep.name),dep.installed&&(dep.majorsBehind=majorsBehind(dep.installed,dep.latest))}catch(err){registryError=err instanceof Error?err.message:String(err)}})),{repo:repo.root,name:repo.name,packageManager:repo.manager,lockfile:repo.lockfile,workspaces:repo.workspaces,dependencies,...registryError?{registryError}:{}}}function verdict2(dep){if(dep.workspaces.length===0)return"not a dependency";if(!dep.installed)return"declared, not in the lockfile";if(!dep.latest)return`${dep.installed} installed, latest unknown`;if(compareVersions(dep.installed,dep.latest)>=0)return`${dep.installed} installed, up to date`;let majors=dep.majorsBehind??0,behind=majors===0?"same major":`${majors} major${majors===1?"":"s"} behind`;return`${dep.installed} installed, latest ${dep.latest}, ${behind}`}function formatStatus(report,opts={}){let colors=import_picocolors9.default.createColors(opts.color??!0),packages=report.workspaces.filter(w=>w!==".").length,lines=[`${colors.dim("Repository")} ${report.name?`${report.name} ${colors.dim(report.repo)}`:report.repo}`,`${colors.dim("Manager")} ${report.packageManager}${packages>0?`, ${packages} workspace package${packages===1?"":"s"}`:""}`,""],width2=Math.max(...report.dependencies.map(d=>d.name.length));for(let dep of report.dependencies){let where=packages>0&&dep.workspaces.length>0?colors.dim(` ${dep.workspaces.join(", ")}${dep.catalog?" (catalog)":""}`):"",text=verdict2(dep),behind=(dep.majorsBehind??0)>0;lines.push(`${colors.bold(dep.name.padEnd(width2))} ${behind?colors.yellow(text):text}${where}`)}lines.push("");let used=report.dependencies.filter(d=>d.workspaces.length>0);return report.registryError&&lines.push(`Could not reach the npm registry (${report.registryError}), so latest versions are unknown.`,` ${colors.bold("Next:")} npm ping`),used.length===0?lines.push(`Neither ${report.dependencies.map(d=>d.name).join(" nor ")} is a dependency here; those are the upgrades uptide covers today.`):used.some(d=>!d.latest||!d.installed||compareVersions(d.installed,d.latest)<0)?lines.push(`Run ${colors.bold(runnable("`uptide list`, then `uptide check <package>`"))} for impact.`):lines.push("Nothing to upgrade."),`${lines.join(`
154
+ Enable telemetry? [y/N] `,answer=>done(/^y(?:es)?$/i.test(answer.trim())))})}}function uiOf(io2,flags){let ci=flags.ci===!0||io2.env.CI!==void 0&&io2.env.CI!==""&&io2.env.CI!=="0",noColor=io2.env.NO_COLOR!==void 0&&io2.env.NO_COLOR!=="",forced=io2.env.FORCE_COLOR!==void 0&&io2.env.FORCE_COLOR!=="0";return{color:!ci&&flags.color!==!1&&!noColor&&(io2.outTty||forced),interactive:!ci&&io2.errTty&&io2.env.TERM!=="dumb"}}var import_picocolors9=__toESM(require_picocolors(),1);import{existsSync as existsSync4,readFileSync as readFileSync5}from"fs";import{dirname as dirname6,join as join6}from"path";function packRoot(cwd){let dir=cwd;for(;;){if(existsSync4(join6(dir,"packages","core","src","packs","registry.ts")))return dir;let parent=dirname6(dir);if(parent===dir)throw new CliError("uptide pack works inside an uptide checkout",{why:"packs live in packages/core/src/packs of https://github.com/uptide-dev/uptide",next:"git clone https://github.com/uptide-dev/uptide && cd uptide && pnpm install"});dir=parent}}function packsToTest(root,registered,name){let missing=[...readFileSync5(join6(root,"packages","core","src","packs","registry.ts"),"utf8").matchAll(/\{ dir: '([^']+)'/g)].map(m=>m[1]).filter(dir=>!registered.some(e=>e.dir===dir));if(missing.length>0)throw new CliError(`this build of uptide does not include the pack in ${missing.join(", ")}`,{why:"pack test runs the packs compiled into the CLI; `pnpm uptide` runs them from source",next:`pnpm uptide pack test${name?` ${name}`:""}`});if(!name)return[...registered];let entry=registered.find(e=>e.pack.name===name||e.dir===name);if(!entry)throw new CliError(`no pack for ${name}`,{next:`uptide pack new ${name} --from <range> --to <range>`});return[entry]}var pct=n=>`${Math.round(n*100)}%`;function row(name,t){return` ${name.padEnd(28)} ${pct(t.precision).padStart(9)} ${pct(t.recall).padStart(7)} ${String(t.truePositives).padStart(5)} ${String(t.falsePositives).padStart(4)} ${String(t.falseNegatives).padStart(4)}`}function formatPackTest(report,color=!1){let c=import_picocolors9.default.createColors(color),out=[],recorded=report.recorded===report.status?"":`, recorded ${report.recorded}`;out.push(c.bold(`uptide pack test ${report.package} \xB7 ${report.status}${recorded}`));for(let problem of report.problems)out.push(` ${c.red("\u2717")} ${problem}`);let f=report.fixtures,fixtureSites=Object.values(f.rules).reduce((n,t)=>n+t.truePositives+t.falseNegatives,0),fixturesOk=f.rewriteFailures.length+f.falsePositives.length+f.falseNegatives.length===0&&f.unknown.length===0;out.push(`fixtures ${f.cases.length} case${f.cases.length===1?"":"s"}, ${fixtureSites} site${fixtureSites===1?"":"s"} \xB7 ${fixturesOk?c.green("pass"):c.red("fail")}`);for(let u of f.unknown)out.push(` ${c.red("\u2717")} ${u.file}:${u.line} names no rule: ${u.rule}`);for(let r of f.rewriteFailures)out.push(` ${c.red("\u2717")} ${r.file}${r.line?`:${r.line}`:""} ${r.message}`);for(let s of f.falsePositives)out.push(` ${c.red("\u2717")} ${s.file}:${s.line} ${s.rule} detected, not marked`);for(let s of f.falseNegatives)out.push(` ${c.red("\u2717")} ${s.file}:${s.line} ${s.rule} marked, not detected`);if(report.fixturesOnly)out.push("ground truth skipped (--fixtures-only)");else if(report.repos.length===0)out.push("ground truth no repository yet: the pack ships as a candidate");else{out.push("ground truth");for(let r of report.repos){let head=` ${r.label.padEnd(44)} ${report.package} ${r.from} \u2192 ${r.to}`;if(r.error){out.push(`${head} ${c.red(`error: ${r.error}`)}`);continue}out.push(`${head} predicted ${r.predicted.length}, expected ${r.expected.length}, false positives ${r.falsePositives.length}, false negatives ${r.falseNegatives.length}`),r.installedMismatch&&out.push(` ${c.yellow("!")} ${r.installedMismatch}`),r.companions?.length&&out.push(` with ${r.companions.map(m=>`${m.name} ${m.from} \u2192 ${m.to}`).join(", ")}`);for(let left of r.leftBehind??[])out.push(` ${c.red("\u2717")} ${left}`)}out.push(""),out.push(` ${"rule".padEnd(28)} ${"precision".padStart(9)} ${"recall".padStart(7)} ${"tp".padStart(5)} ${"fp".padStart(4)} ${"fn".padStart(4)}`);for(let[rule,t]of Object.entries(report.rules).sort(([a],[b])=>a.localeCompare(b)))out.push(row(rule,t));out.push(row("overall (sites)",report.overall)),out.push(c.bold(row("breaking (sites)",report.breaking)));let listed=(title,sites)=>{if(sites.length!==0){out.push(""),out.push(`${title} (${sites.length})`);for(let s of sites)out.push(` ${s.label} ${s.file}:${s.line} ${s.text}`)}};listed("false positives",report.repos.flatMap(r=>r.falsePositives.map(s=>({label:r.label,file:s.file,line:s.line,text:`${s.rule} (${s.severity??"breaking"})`})))),listed("false negatives",report.repos.flatMap(r=>r.falseNegatives.map(s=>({label:r.label,file:s.file,line:s.line,text:s.rule})))),listed("reported under another rule",report.repos.flatMap(r=>r.wrongRule.map(s=>({label:r.label,file:s.file,line:s.line,text:`${s.rule}, expected ${s.expected}`}))))}out.push(""),report.stale&&out.push(`${c.red("\u2717")} verification.json does not match this run: \`uptide pack test ${report.package} --write\` records it`);let breakingFp=report.breaking.falsePositives;return out.push(report.passed?c.green(`PASS ${report.package}: ${report.status}`):c.red(`FAIL ${report.package}${breakingFp?`: ${breakingFp} false positive${breakingFp===1?"":"s"} among breaking findings`:""}`)),`${out.join(`
155
155
  `)}
156
- `}import{readFileSync as readFileSync6,rmSync}from"fs";import{dirname as dirname6,join as join8,resolve as resolve6}from"path";import{readFileSync as readFileSync5,statSync}from"fs";import{join as join7}from"path";function cachedPublicVersion(env){return(name,version)=>{if(!NAME_PATTERN.test(name)||name.length>214||!VERSION_PATTERN.test(version)||version.length>128)return!1;for(let key of[`resolve-${version}`,"resolve-latest"])try{let path2=join7(defaultCacheDir(env),"registry",...name.split("/"),`${key}.json`);if(statSync(path2).size>1024*1024)continue;let{value}=JSON.parse(readFileSync5(path2,"utf8"));if(value.publicRegistry===!0&&value.name===name&&value.version===version)return!0}catch{}return!1}}import{spawn as spawn2}from"child_process";import{fileURLToPath}from"url";var MAX_BYTES=32*1024;function dispatch(delivery){let message=JSON.stringify(delivery);if(Buffer.byteLength(message)>MAX_BYTES)return;let child=spawn2(process.execPath,[fileURLToPath(new URL("./telemetry-sender.js",import.meta.url))],{detached:!0,windowsHide:!0,stdio:["pipe","ignore","ignore"],env:{...process.platform==="win32"?{SystemRoot:process.env.SystemRoot}:{},...process.env.NODE_EXTRA_CA_CERTS?{NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS}:{}}});child.on("error",()=>{}),child.stdin.on("error",()=>{}),child.stdin.end(message),child.stdin.unref?.(),child.unref()}function createTelemetry(io2,options){let path2=options.path??settingsPath(io2.env),last=join8(dirname6(path2),"telemetry-last.json"),publicVersion=options.publicVersion??cachedPublicVersion(io2.env),key=options.key??BUILD_KEY,url=captureUrl(io2.env.UPTIDE_TELEMETRY_HOST??options.host??BUILD_HOST),configured=/^phc_[A-Za-z0-9_-]+$/.test(key)&&url!==void 0,settings,command,metrics={},started=0,status=(ci=!1)=>{let saved=readSettings(path2),active=enabled(saved,io2.env,isCi(io2.env,ci));return{preference:saved===void 0?"unset":saved.consent?"on":"off",enabled:active,transport:configured?"configured":"disabled: no capture key or invalid HTTPS host",sending:active&&configured,override:io2.env.UPTIDE_TELEMETRY==="0"?"environment: off":io2.env.UPTIDE_TELEMETRY==="1"?"environment: on":isCi(io2.env,ci)?"CI: off (set UPTIDE_TELEMETRY=1 to opt in)":"none"}};return{async begin(name,flags){settings=void 0,command=void 0,metrics={};try{let known=name==="uptide"?"status":name;if(!COMMANDS.includes(known))return;let saved=readSettings(path2),ci=isCi(io2.env,flags.ci);if(saved===void 0&&io2.env.UPTIDE_TELEMETRY===void 0&&!ci&&!flags.json&&io2.inTty&&io2.outTty&&io2.errTty&&io2.confirmTelemetry&&(saved={consent:await io2.confirmTelemetry()===!0},atomicJson(path2,saved)),!enabled(saved,io2.env,ci))return;settings=identity(saved??{consent:!1}),atomicJson(path2,settings),command=known,metrics={repo:resolve6(io2.cwd,flags.cwd??".")},started=io2.now()}catch{settings=void 0,command=void 0}},record(value){if(command)try{metrics={...metrics,...value()}}catch{}},finish(code){try{if(!settings||!command||!enabled(readSettings(path2),io2.env,isCi(io2.env)))return;let event=buildEvent(settings,command,options.version,metrics,io2.now()-started,code,publicVersion);if(!event||(atomicJson(last,event),!configured||!url))return;(options.dispatch??dispatch)({url,key,event})}catch{}},control(action,ci){if(action==="status")return status(ci);if(action==="show")try{return sanitizeEvent(JSON.parse(readFileSync6(last,"utf8")),publicVersion)??null}catch{return null}if(action==="on")atomicJson(path2,identity({...readSettings(path2),consent:!0}));else if(action==="off")atomicJson(path2,{consent:!1}),rmSync(last,{force:!0});else throw new Error("Expected telemetry on, off, status or show.");return status(ci)}}}function checkMetrics(report){return{repo:report.repo,packages:report.packages.map(p=>({name:p.name,versions:[p.installed,p.target]})),counts:{packages:report.packages.length,workspaces:report.workspaces.length,breaking:report.summary.breaking,deprecated:report.summary.deprecated,unverified:report.summary.unverified,failed:report.summary.failed,partial:report.summary.partiallyAnalyzed},durations:{fetch:report.packages.reduce((n,p)=>n+p.timing.fetchMs,0),diff:report.packages.reduce((n,p)=>n+p.timing.diffMs,0),usages:report.packages.reduce((n,p)=>n+p.timing.usagesMs,0),compile:report.packages.reduce((n,p)=>n+p.timing.compileMs,0),runtime:report.packages.reduce((n,p)=>n+(p.timing.runtimeMs??0),0)}}}function listMetrics(report){return{repo:report.repo,packages:report.packages.map(p=>({name:p.name,versions:[p.current,p.latest]})),counts:{packages:report.packages.length,workspaces:report.workspaces.length,failed:report.failures.length},durations:{engine:report.timing.totalMs}}}function fixMetrics(report,cwd){return{repo:cwd,packages:[{name:report.package,versions:[report.from??"",report.target]}],counts:{sites:report.sites.length,files:new Set(report.sites.map(s=>s.finding.usage.file)).size,new_errors:report.verification.newErrors.length,tests:report.verification.tests.length},durations:{engine:report.timingMs,verification:report.verificationTimingMs??0},verification:report.verificationPending?"not_run":report.verification.passed?"passed":"failed",cost:report.llm.costUsd,provider:report.llm.provider,model:report.llm.model}}var EXIT_CODES=(zero,one,two="")=>`
156
+ `}var PRIVACY="Privacy:\n Analysis runs locally. Code snippets go to your chosen LLM provider (Anthropic, OpenAI or Gemini), only\n for assisted fixes in `uptide fix`, and only with your own API key from ANTHROPIC_API_KEY,\n OPENAI_API_KEY or GEMINI_API_KEY: for each\n site the rules cannot migrate, the finding, the enclosing function and the compiler\n error. `uptide fix --no-llm` turns assisted fixes off. No account.\n Anonymous telemetry is off by default and asks for consent in an interactive terminal.\n Set UPTIDE_TELEMETRY=0 to disable it. No IP, code, paths or repo names are collected.\n Other network use: your npm registry for package metadata and tarballs, npm's advisory\n endpoint from `list` (public package names and installed versions; `--no-advisories` turns\n it off), PostHog EU only\n after telemetry opt-in, and GitHub when you pass `fix --pr` or run `pr` / `pr-body`.\n";import{join as join7}from"path";var import_picocolors10=__toESM(require_picocolors(),1);var SUPPORTED=["zod","stripe"];async function locateDependencies(repo,engine,names2=SUPPORTED){let dependencies=names2.map(name=>({name,workspaces:[],catalog:!1}));for(let workspace of repo.workspaces){let dir=join7(repo.root,workspace),[installed,declared]=await Promise.all([engine.installed(dir),engine.declared(dir)]);for(let dep of dependencies){let spec=declared.get(dep.name);if(spec===void 0)continue;dep.workspaces.push(workspace),spec.startsWith("catalog:")&&(dep.catalog=!0);let version=installed.get(dep.name);version&&(!dep.installed||compareVersions(version,dep.installed)<0)&&(dep.installed=version)}}return dependencies}async function declaredDependencies(repo,engine){let names2=new Set;for(let workspace of repo.workspaces){let declared=await engine.declared(join7(repo.root,workspace));for(let[name,spec]of declared)/^(workspace|link|file):/.test(spec)||names2.add(name)}return[...names2].sort()}async function collectStatus(repo,engine,names2=SUPPORTED){let dependencies=await locateDependencies(repo,engine,names2),registryError;return await Promise.all(dependencies.filter(dep=>dep.workspaces.length>0).map(async dep=>{try{dep.latest=await engine.latest(dep.name),dep.installed&&(dep.majorsBehind=majorsBehind(dep.installed,dep.latest))}catch(err){registryError=err instanceof Error?err.message:String(err)}})),{repo:repo.root,name:repo.name,packageManager:repo.manager,lockfile:repo.lockfile,workspaces:repo.workspaces,dependencies,...registryError?{registryError}:{}}}function verdict2(dep){if(dep.workspaces.length===0)return"not a dependency";if(!dep.installed)return"declared, not in the lockfile";if(!dep.latest)return`${dep.installed} installed, latest unknown`;if(compareVersions(dep.installed,dep.latest)>=0)return`${dep.installed} installed, up to date`;let majors=dep.majorsBehind??0,behind=majors===0?"same major":`${majors} major${majors===1?"":"s"} behind`;return`${dep.installed} installed, latest ${dep.latest}, ${behind}`}function formatStatus(report,opts={}){let colors=import_picocolors10.default.createColors(opts.color??!0),packages=report.workspaces.filter(w=>w!==".").length,lines=[`${colors.dim("Repository")} ${report.name?`${report.name} ${colors.dim(report.repo)}`:report.repo}`,`${colors.dim("Manager")} ${report.packageManager}${packages>0?`, ${packages} workspace package${packages===1?"":"s"}`:""}`,""],width2=Math.max(...report.dependencies.map(d=>d.name.length));for(let dep of report.dependencies){let where=packages>0&&dep.workspaces.length>0?colors.dim(` ${dep.workspaces.join(", ")}${dep.catalog?" (catalog)":""}`):"",text=verdict2(dep),behind=(dep.majorsBehind??0)>0;lines.push(`${colors.bold(dep.name.padEnd(width2))} ${behind?colors.yellow(text):text}${where}`)}lines.push("");let used=report.dependencies.filter(d=>d.workspaces.length>0);return report.registryError&&lines.push(`Could not reach the npm registry (${report.registryError}), so latest versions are unknown.`,` ${colors.bold("Next:")} npm ping`),used.length===0?lines.push(`Neither ${report.dependencies.map(d=>d.name).join(" nor ")} is a dependency here; those are the upgrades uptide covers today.`):used.some(d=>!d.latest||!d.installed||compareVersions(d.installed,d.latest)<0)?lines.push(`Run ${colors.bold(runnable("`uptide list`, then `uptide check <package>`"))} for impact.`):lines.push("Nothing to upgrade."),`${lines.join(`
157
+ `)}
158
+ `}import{readFileSync as readFileSync7,rmSync}from"fs";import{dirname as dirname7,join as join9,resolve as resolve6}from"path";import{readFileSync as readFileSync6,statSync}from"fs";import{join as join8}from"path";function cachedPublicVersion(env){return(name,version)=>{if(!NAME_PATTERN.test(name)||name.length>214||!VERSION_PATTERN.test(version)||version.length>128)return!1;for(let key of[`resolve-${version}`,"resolve-latest"])try{let path2=join8(defaultCacheDir(env),"registry",...name.split("/"),`${key}.json`);if(statSync(path2).size>1024*1024)continue;let{value}=JSON.parse(readFileSync6(path2,"utf8"));if(value.publicRegistry===!0&&value.name===name&&value.version===version)return!0}catch{}return!1}}import{spawn as spawn2}from"child_process";import{fileURLToPath}from"url";var MAX_BYTES=32*1024;function dispatch(delivery){let message=JSON.stringify(delivery);if(Buffer.byteLength(message)>MAX_BYTES)return;let child=spawn2(process.execPath,[fileURLToPath(new URL("./telemetry-sender.js",import.meta.url))],{detached:!0,windowsHide:!0,stdio:["pipe","ignore","ignore"],env:{...process.platform==="win32"?{SystemRoot:process.env.SystemRoot}:{},...process.env.NODE_EXTRA_CA_CERTS?{NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS}:{}}});child.on("error",()=>{}),child.stdin.on("error",()=>{}),child.stdin.end(message),child.stdin.unref?.(),child.unref()}function createTelemetry(io2,options){let path2=options.path??settingsPath(io2.env),last=join9(dirname7(path2),"telemetry-last.json"),publicVersion=options.publicVersion??cachedPublicVersion(io2.env),key=options.key??BUILD_KEY,url=captureUrl(io2.env.UPTIDE_TELEMETRY_HOST??options.host??BUILD_HOST),configured=/^phc_[A-Za-z0-9_-]+$/.test(key)&&url!==void 0,settings,command,metrics={},started=0,status=(ci=!1)=>{let saved=readSettings(path2),active=enabled(saved,io2.env,isCi(io2.env,ci));return{preference:saved===void 0?"unset":saved.consent?"on":"off",enabled:active,transport:configured?"configured":"disabled: no capture key or invalid HTTPS host",sending:active&&configured,override:io2.env.UPTIDE_TELEMETRY==="0"?"environment: off":io2.env.UPTIDE_TELEMETRY==="1"?"environment: on":isCi(io2.env,ci)?"CI: off (set UPTIDE_TELEMETRY=1 to opt in)":"none"}};return{async begin(name,flags){settings=void 0,command=void 0,metrics={};try{let known=name==="uptide"?"status":name;if(!COMMANDS.includes(known))return;let saved=readSettings(path2),ci=isCi(io2.env,flags.ci);if(saved===void 0&&io2.env.UPTIDE_TELEMETRY===void 0&&!ci&&!flags.json&&io2.inTty&&io2.outTty&&io2.errTty&&io2.confirmTelemetry&&(saved={consent:await io2.confirmTelemetry()===!0},atomicJson(path2,saved)),!enabled(saved,io2.env,ci))return;settings=identity(saved??{consent:!1}),atomicJson(path2,settings),command=known,metrics={repo:resolve6(io2.cwd,flags.cwd??".")},started=io2.now()}catch{settings=void 0,command=void 0}},record(value){if(command)try{metrics={...metrics,...value()}}catch{}},finish(code){try{if(!settings||!command||!enabled(readSettings(path2),io2.env,isCi(io2.env)))return;let event=buildEvent(settings,command,options.version,metrics,io2.now()-started,code,publicVersion);if(!event||(atomicJson(last,event),!configured||!url))return;(options.dispatch??dispatch)({url,key,event})}catch{}},control(action,ci){if(action==="status")return status(ci);if(action==="show")try{return sanitizeEvent(JSON.parse(readFileSync7(last,"utf8")),publicVersion)??null}catch{return null}if(action==="on")atomicJson(path2,identity({...readSettings(path2),consent:!0}));else if(action==="off")atomicJson(path2,{consent:!1}),rmSync(last,{force:!0});else throw new Error("Expected telemetry on, off, status or show.");return status(ci)}}}function checkMetrics(report){return{repo:report.repo,packages:report.packages.map(p=>({name:p.name,versions:[p.installed,p.target]})),counts:{packages:report.packages.length,workspaces:report.workspaces.length,breaking:report.summary.breaking,deprecated:report.summary.deprecated,unverified:report.summary.unverified,failed:report.summary.failed,partial:report.summary.partiallyAnalyzed},durations:{fetch:report.packages.reduce((n,p)=>n+p.timing.fetchMs,0),diff:report.packages.reduce((n,p)=>n+p.timing.diffMs,0),usages:report.packages.reduce((n,p)=>n+p.timing.usagesMs,0),compile:report.packages.reduce((n,p)=>n+p.timing.compileMs,0),runtime:report.packages.reduce((n,p)=>n+(p.timing.runtimeMs??0),0)}}}function listMetrics(report){return{repo:report.repo,packages:report.packages.map(p=>({name:p.name,versions:[p.current,p.latest]})),counts:{packages:report.packages.length,workspaces:report.workspaces.length,failed:report.failures.length},durations:{engine:report.timing.totalMs}}}function fixMetrics(report,cwd){return{repo:cwd,packages:[{name:report.package,versions:[report.from??"",report.target]}],counts:{sites:report.sites.length,files:new Set(report.sites.map(s=>s.finding.usage.file)).size,new_errors:report.verification.newErrors.length,tests:report.verification.tests.length},durations:{engine:report.timingMs,verification:report.verificationTimingMs??0},verification:report.verificationPending?"not_run":report.verification.passed?"passed":"failed",cost:report.llm.costUsd,provider:report.llm.provider,model:report.llm.model}}var EXIT_CODES=(zero,one,two="")=>`
157
159
  Exit codes:
158
160
  0 ${zero}
159
161
  1 ${one}
@@ -217,10 +219,10 @@ Examples:
217
219
  $ uptide plan --only react,react-dom,next
218
220
  $ uptide plan --json --ci > plan.json
219
221
  ${EXIT_CODES("a plan was made","not used",`;
220
- or a dependency failed to analyze (the plan still orders the others)`)}`).action(flags=>act(flags,async({ui,progress,cwd})=>{let started=io2.now(),only=list(flags.only),checkResults=flags.results?JSON.parse(readFileSync7(resolve7(io2.cwd,flags.results),"utf8")):void 0,repo=await progress.phase("Repository",()=>detectRepo(cwd,engine.workspaces),describeRepo);if(!flags.verbose&&!ui.interactive&&io2.err(`uptide plan \xB7 ${repoLine(headerOf(repo,0))}
222
+ or a dependency failed to analyze (the plan still orders the others)`)}`).action(flags=>act(flags,async({ui,progress,cwd})=>{let started=io2.now(),only=list(flags.only),checkResults=flags.results?JSON.parse(readFileSync8(resolve7(io2.cwd,flags.results),"utf8")):void 0,repo=await progress.phase("Repository",()=>detectRepo(cwd,engine.workspaces),describeRepo);if(!flags.verbose&&!ui.interactive&&io2.err(`uptide plan \xB7 ${repoLine(headerOf(repo,0))}
221
223
  `),!engine.plan)throw new CliError("this build cannot plan upgrades");let plan=engine.plan,result=await progress.phase(only?`Plan for ${only.join(", ")}`:"Plan for every dependency that is behind",async()=>{let planned=await plan({cwd:repo.root,only,checkResults},progress.event).catch(err=>{let message=err instanceof Error?err.message:String(err);throw isNetworkError(err)?noNetwork(message):err}),offline=networkFailure(planned.report);if(offline)throw offline;return planned},r=>`${r.plan.steps.length} steps`),ms=io2.now()-started;!flags.verbose&&!ui.interactive&&io2.err(`done in ${elapsed(ms)}
222
224
  `),telemetry?.record(()=>{let metrics=checkMetrics(result.report);return{...metrics,counts:{...metrics.counts,steps:result.plan.steps.length}}});let fixable=FIX_MANAGERS.includes(repo.manager),planOptions={header:headerOf(repo,ms),invocation:INVOCATION,fixable,...flags.cwd?{cwd:flags.cwd}:{}};if(flags.json?emit(result.plan):io2.out(formatPlan(result.plan,{color:ui.color,...planOptions})),flags.html){let path2=writePlanHtml(result.plan,{...planOptions,version:VERSION,date:new Date(io2.now()).toISOString()},flags.html,io2.cwd);io2.err(`HTML plan: ${path2}
223
- `)}return result.report.packages.some(p=>isFailure(p))?EXIT.error:EXIT.ok},{quiet:!flags.verbose})),shared(program2.command("fix [package]").allowExcessArguments(!1).description("Upgrade one dependency on a new branch and migrate your code, verified").option("--only <package>","the dependency to upgrade: zod or stripe (verified), or any other (generic, agent only)").option("--target <spec>","exact version, optionally `<package>@<version>` (default: latest on npm, as check uses)").option("--include-deprecated","migrate reported deprecated sites too").option("--pin-current-api","stripe only: no upgrade; write the installed SDK's default apiVersion on every client that omits it").option("--provider <name>","LLM provider: anthropic, openai or gemini (also UPTIDE_PROVIDER)").option("--model <id>","LLM model ID (also UPTIDE_MODEL)").option("--no-llm","rule-based fixes only: never send code to the LLM provider").option("--max-cost <usd>","reserve the worst-case cost before each LLM call, including retries (default: 1 USD for every package)").option("--with-services","also run tests that need a database, cache or queue; prints the targets, requires --yes").option("--keep","keep the temporary clone after the run (it is kept anyway when the run fails)").option("--pr","open a draft PR after verification passes; requires --yes").option("--base <branch>","with --pr: the branch on origin the PR is opened against (default: its default branch)").option("--allow-dirty","with --pr: proceed although the working tree has uncommitted changes; they are left out").option("--yes","approve what was printed: the publication plan (--pr), the services (--with-services)").option("--verbose","one progress line per phase, with timings")).addHelpText("after",`
225
+ `)}return result.report.packages.some(p=>isFailure(p))?EXIT.error:EXIT.ok},{quiet:!flags.verbose})),shared(program2.command("fix [package]").allowExcessArguments(!1).description("Upgrade one dependency on a new branch and migrate your code, verified").option("--only <package>",`the dependency to upgrade: ${activePacks().map(pack=>pack.name).join(", ")} (verified), or any other (generic, agent only)`).option("--target <spec>","exact version, optionally `<package>@<version>` (default: latest on npm, as check uses)").option("--include-deprecated","migrate reported deprecated sites too").option("--pin-current-api","stripe only: no upgrade; write the installed SDK's default apiVersion on every client that omits it").option("--provider <name>","LLM provider: anthropic, openai or gemini (experimental) (also UPTIDE_PROVIDER)").option("--model <id>","LLM model ID (also UPTIDE_MODEL)").option("--no-llm","rule-based fixes only: never send code to the LLM provider").option("--max-cost <usd>","reserve the worst-case cost before each LLM call, including retries (default: 1 USD for every package)").option("--with-services","also run tests that need a database, cache or queue; prints the targets, requires --yes").option("--keep","keep the temporary clone after the run (it is kept anyway when the run fails)").option("--pr","open a draft PR after verification passes; requires --yes").option("--base <branch>","with --pr: the branch on origin the PR is opened against (default: its default branch)").option("--allow-dirty","with --pr: proceed although the working tree has uncommitted changes; they are left out").option("--yes","approve what was printed: the publication plan (--pr), the services (--with-services)").option("--verbose","one progress line per phase, with timings")).addHelpText("after",`
224
226
  What it does:
225
227
  Works in a temporary clone of your local repository at the commit you have checked out, never
226
228
  in your checkout: your branch, files, git hooks and git config stay as they are. Uncommitted
@@ -245,12 +247,12 @@ Examples:
245
247
  $ uptide fix stripe --pin-current-api the small PR: same SDK, apiVersion made explicit
246
248
  $ uptide fix zod --no-llm no code leaves this machine
247
249
  ${EXIT_CODES("migration verified: no new type errors, tests pass","verification failed or sites remain for manual work")}
248
- ${PRIVACY}`).action((packageName,flags)=>act(flags,async({ui,progress,cwd})=>{let started=io2.now(),quiet=!flags.verbose;if(packageName&&flags.only&&packageName!==flags.only)throw new CliError("choose one package for fix");let only=packageName??flags.only;if(!only)throw new CliError("fix requires a package name. Start with uptide list.",{next:"uptide list"});if(only.includes(","))throw new CliError(`--only ${only}: fix upgrades one dependency at a time`,{next:`uptide fix ${only.split(",")[0]}`});let maxCost=flags.maxCost!==void 0?Number(flags.maxCost):1,selection=selectLlm(cwd,flags,io2.env);if(maxCost!==void 0&&(!Number.isFinite(maxCost)||maxCost<=0))throw new CliError(`--max-cost ${flags.maxCost}: expected an amount in USD`,{next:`uptide fix ${only} --max-cost 2`});let hasPack=SUPPORTED.includes(only);if(!hasPack&&(flags.llm===!1||!selection.available))throw noAgentForGeneric(only,flags.llm===!1);if(flags.pinCurrentApi&&only!=="stripe")throw new CliError("--pin-current-api applies to stripe only",{next:"uptide fix stripe --pin-current-api"});if(flags.pinCurrentApi&&flags.target)throw new CliError("--pin-current-api keeps the installed version; drop --target",{next:"uptide fix stripe --pin-current-api"});flags.target&&parseTargets([flags.target],[only]),flags.pr&&!flags.yes&&io2.err(`--pr without --yes: the publication plan is printed, nothing is pushed.
250
+ ${PRIVACY}`).action((packageName,flags)=>act(flags,async({ui,progress,cwd})=>{let started=io2.now(),quiet=!flags.verbose;if(packageName&&flags.only&&packageName!==flags.only)throw new CliError("choose one package for fix");let only=packageName??flags.only;if(!only)throw new CliError("fix requires a package name. Start with uptide list.",{next:"uptide list"});if(only.includes(","))throw new CliError(`--only ${only}: fix upgrades one dependency at a time`,{next:`uptide fix ${only.split(",")[0]}`});let maxCost=flags.maxCost!==void 0?Number(flags.maxCost):1,selection=selectLlm(cwd,flags,io2.env);if(maxCost!==void 0&&(!Number.isFinite(maxCost)||maxCost<=0))throw new CliError(`--max-cost ${flags.maxCost}: expected an amount in USD`,{next:`uptide fix ${only} --max-cost 2`});let hasPack=activePacks().some(pack=>pack.name===only);if(!hasPack&&(flags.llm===!1||!selection.available))throw noAgentForGeneric(only,flags.llm===!1);if(flags.pinCurrentApi&&only!=="stripe")throw new CliError("--pin-current-api applies to stripe only",{next:"uptide fix stripe --pin-current-api"});if(flags.pinCurrentApi&&flags.target)throw new CliError("--pin-current-api keeps the installed version; drop --target",{next:"uptide fix stripe --pin-current-api"});flags.target&&parseTargets([flags.target],[only]),flags.pr&&!flags.yes&&io2.err(`--pr without --yes: the publication plan is printed, nothing is pushed.
249
251
  `);let repo=await progress.phase("Repository",async()=>{let found=await detectRepo(cwd,engine.workspaces);requireFixable(found,only);let deps=await locateDependencies(found,engine,[only]);if(deps.every(d=>d.workspaces.length===0))throw notADependency(found,[only]);return requireInstalled(found,deps),found},describeRepo);quiet&&!ui.interactive&&io2.err(`uptide fix \xB7 ${only} \xB7 ${repoLine(headerOf(repo,0))}
250
252
  `);let preflightShown=engine.preflight!==void 0;if(engine.preflight){let notes;try{({notes}=engine.preflight(repo.root,{...flags.pr?{pr:!0}:{},...flags.base?{base:flags.base}:{},...flags.allowDirty?{allowDirty:!0}:{}}))}catch(error){throw new CliError(explain(error),{exitCode:EXIT.breaking})}for(let note of notes)io2.err(`${note}
251
253
  `)}if(flags.pr&&engine.publishTarget){let target=await engine.publishTarget(repo.root);io2.err(`PR will be opened on ${target.nameWithOwner} (base ${flags.base??target.base})${target.parent?`, a fork of ${target.parent}; use \`uptide pr --repo ${target.parent}\` afterwards to open it there`:""}
252
254
  `)}let llm=flags.llm!==!1&&!flags.pinCurrentApi;flags.pinCurrentApi?io2.err(`pin run: the SDK stays, apiVersion is written on each client; no code leaves this machine
253
- `):llm?selection.available?(io2.err(`LLM: ${selection.provider} / ${selection.model} \xB7 budget $${maxCost.toFixed(2)}
255
+ `):llm?selection.available?(io2.err(`LLM: ${selection.provider}${selection.provider==="gemini"?" (experimental)":""} / ${selection.model} \xB7 budget $${maxCost.toFixed(2)}
254
256
  `),io2.err(assistedNote(selection.provider)),priceFor(selection.provider,selection.model).fallback&&io2.err(`Unknown model pricing: using ${selection.provider}'s highest listed rates (${PRICE_DATE}) for cost and budget.
255
257
  `),selection.baseUrl&&io2.err(`OPENAI_BASE_URL override: compatible, not verified; endpoint pricing may differ.
256
258
  `)):io2.err(noApiKeyNote(only)):io2.err(`assisted fixes off (--no-llm): no code leaves this machine
@@ -300,7 +302,24 @@ Examples:
300
302
  $ uptide pr-body --pr 82 --preview review the proposal first
301
303
  $ uptide pr-body --pr 82 update only the description
302
304
  ${EXIT_CODES("description rendered (and updated unless --preview)","not used")}`).action(flags=>act(flags,async({cwd})=>{if(!engine.updatePrBody)throw new CliError("pr-body is not available in this build of uptide");let result=await engine.updatePrBody({pr:flags.pr,cwd,run:flags.run,preview:flags.preview});return flags.json?emit(result):(io2.out(result.body),io2.err(`${result.updated?"Updated description:":"Preview only; PR unchanged:"} ${result.url}
303
- `)),EXIT.ok})),program2.command("diff").description("Diff the public API of an npm package between two versions").argument("<package>","npm package name").argument("<from>","version A (exact version or dist-tag)").argument("<to>","version B (exact version or dist-tag)").option("--json","print the full Change[] as JSON").option("--all","also show protected/@internal symbols, alias duplicates and members of removed symbols").option("--ci","plain output for logs: no color, no spinner").option("--no-color","no color (NO_COLOR is respected too)").action((name,from,to,flags)=>act(flags,async({ui,progress})=>{let changes=await progress.phase(`Diff of ${name} ${from} \u2192 ${to}`,()=>engine.diff(name,from,to),c=>`${c.length} changes`);return telemetry?.record(()=>({packages:[{name,versions:[changes[0]?.from??from,changes[0]?.to??to]}],counts:{changes:changes.length}})),flags.json?emit(changes):io2.out(formatHuman(changes,{all:flags.all,color:ui.color})),EXIT.ok}));try{await program2.parseAsync(argv,{from:"user"})}catch(err){if(!(err instanceof CommanderError))throw err;return err.exitCode===0?EXIT.ok:EXIT.error}return fixing&&io2.err(fixSpend&&(fixSpend.costUsd||fixSpend.unreportedCostUsd||fixSpend.inputTokens||fixSpend.outputTokens)?`LLM spend: $${fixSpend.costUsd.toFixed(2)}${fixSpend.unreportedCostUsd?`; up to $${fixSpend.unreportedCostUsd.toFixed(2)} reserved for calls without usage`:""}
305
+ `)),EXIT.ok}));let packs=program2.command("pack").description("Write and score migration packs (inside an uptide checkout; docs/packs.md)");packs.command("new").description("Scaffold a pack: one example rule, a fixture pair, a test, empty ground truth").argument("<package>","the npm package the pack migrates").requiredOption("--from <range>",'installed versions it migrates from, a semver range (">=6 <7")').requiredOption("--to <range>",'target versions, a semver range (">=7 <8")').option("--maintainer <handle>","who answers for the pack: a GitHub handle").option("--cwd <dir>","a directory inside the uptide checkout").option("--json","machine-readable output").addHelpText("after",`
306
+ Example:
307
+ $ uptide pack new ai --from ">=6 <7" --to ">=7 <8" --maintainer @octocat
308
+ ${EXIT_CODES("scaffolded","not used")}`).action((name,flags)=>act(flags,async({cwd})=>{let root=packRoot(cwd),result=scaffoldPack({root,package:name,from:flags.from,to:flags.to,...flags.maintainer?{maintainer:flags.maintainer}:{}});if(flags.json)emit(result);else{io2.out(`Scaffolded the ${name} pack (${result.constant}), registered as a candidate:
309
+ `);for(let file of result.files)io2.out(` ${file}
310
+ `);io2.out(`
311
+ Next: replace the example rule, add fixtures and ground truth (docs/packs.md), then
312
+ pnpm uptide pack test ${name}
313
+ `)}return EXIT.ok})),packs.command("test").description("Score packs against their fixtures and ground truth: precision and recall per rule").argument("[package]","one pack; every registered pack when omitted").option("--offline","never fetch: use only ground-truth repositories already cached").option("--fixtures-only","run the fixtures, skip the ground-truth repositories").option("--write","record this run's result in the pack's verification.json").option("--update-fixtures","write each fixture's after.ts from what the rules produce; review the diff before committing").option("--cwd <dir>","a directory inside the uptide checkout").option("--json","machine-readable output for CI").option("--no-color","no color (NO_COLOR is respected too)").addHelpText("after",`
314
+ Ground-truth repositories are fetched once (shallow, the pinned commit only) and installed with
315
+ lifecycle scripts off into ~/.cache/uptide/ground-truth (UPTIDE_GROUND_TRUTH_CACHE overrides it).
316
+
317
+ Examples:
318
+ $ uptide pack test zod
319
+ $ uptide pack test --json > pack-test.json
320
+ $ uptide pack test ai --write record the status verification.json claims
321
+ ${EXIT_CODES("every pack passed","a false positive among breaking findings, a failing fixture, or a stale verification.json")}`).action((name,flags)=>act(flags,async({ui,cwd})=>{let root=packRoot(cwd),reports=[];for(let entry of packsToTest(root,registeredPacks(),name)){let report=await testPack(entry,{root,...flags.offline?{offline:!0}:{},...flags.fixturesOnly?{fixturesOnly:!0}:{},...flags.write?{write:!0}:{},...flags.updateFixtures?{updateFixtures:!0}:{},log:line=>io2.err(`${line}
322
+ `)});reports.push(report),flags.json||io2.out(formatPackTest(report,ui.color))}let passed=reports.every(r=>r.passed);return flags.json&&emit({passed,packs:reports}),passed?EXIT.ok:EXIT.breaking})),program2.command("diff").description("Diff the public API of an npm package between two versions").argument("<package>","npm package name").argument("<from>","version A (exact version or dist-tag)").argument("<to>","version B (exact version or dist-tag)").option("--json","print the full Change[] as JSON").option("--all","also show protected/@internal symbols, alias duplicates and members of removed symbols").option("--ci","plain output for logs: no color, no spinner").option("--no-color","no color (NO_COLOR is respected too)").action((name,from,to,flags)=>act(flags,async({ui,progress})=>{let changes=await progress.phase(`Diff of ${name} ${from} \u2192 ${to}`,()=>engine.diff(name,from,to),c=>`${c.length} changes`);return telemetry?.record(()=>({packages:[{name,versions:[changes[0]?.from??from,changes[0]?.to??to]}],counts:{changes:changes.length}})),flags.json?emit(changes):io2.out(formatHuman(changes,{all:flags.all,color:ui.color})),EXIT.ok}));try{await program2.parseAsync(argv,{from:"user"})}catch(err){if(!(err instanceof CommanderError))throw err;return err.exitCode===0?EXIT.ok:EXIT.error}return fixing&&io2.err(fixSpend&&(fixSpend.costUsd||fixSpend.unreportedCostUsd||fixSpend.inputTokens||fixSpend.outputTokens)?`LLM spend: $${fixSpend.costUsd.toFixed(2)}${fixSpend.unreportedCostUsd?`; up to $${fixSpend.unreportedCostUsd.toFixed(2)} reserved for calls without usage`:""}
304
323
  `:fixEngineStarted&&!fixSpend?`LLM spend: unavailable (the run ended before returning a usage report).
305
324
  `:`LLM spend: no LLM calls.
306
325
  `),telemetry?.finish(code),code}var io=processIo();run(process.argv.slice(2),io,void 0,createTelemetry(io,{version:VERSION})).then(code=>{process.exitCode=code},err=>{process.stderr.write(renderError(err,!1)),process.exitCode=2});
@@ -3,4 +3,4 @@ import { fileURLToPath as __uptideFileURLToPath } from 'node:url';
3
3
  const require = __uptideCreateRequire(import.meta.url);
4
4
  const __filename = __uptideFileURLToPath(import.meta.url);
5
5
  const __dirname = __uptideFileURLToPath(new URL('.', import.meta.url));
6
- import{GITHUB_BODY_LIMIT,publicationBlockers,publish,publishTarget}from"./chunk-VHIIYAJM.js";import"./chunk-W74OVIU4.js";import"./chunk-JHZ22Y6X.js";import"./chunk-Z5YHBDVG.js";export{GITHUB_BODY_LIMIT,publicationBlockers,publish,publishTarget};
6
+ import{GITHUB_BODY_LIMIT,publicationBlockers,publish,publishTarget}from"./chunk-H55HNL33.js";import"./chunk-RPK3NKP7.js";import"./chunk-JHZ22Y6X.js";import"./chunk-Z5YHBDVG.js";export{GITHUB_BODY_LIMIT,publicationBlockers,publish,publishTarget};