@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
5 lines (4 loc) • 24.9 kB
JavaScript
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb,mod)=>function(){try{return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e){throw mod=0,e}};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod));var require_windows=__commonJS({"node_modules/isexe/windows.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs=__require("fs");function checkPathExt(path,options){var pathext=options.pathExt!==void 0?options.pathExt:process.env.PATHEXT;if(!pathext||(pathext=pathext.split(";"),pathext.indexOf("")!==-1))return!0;for(var i=0;i<pathext.length;i++){var p=pathext[i].toLowerCase();if(p&&path.substr(-p.length).toLowerCase()===p)return!0}return!1}function checkStat(stat,path,options){return!stat.isSymbolicLink()&&!stat.isFile()?!1:checkPathExt(path,options)}function isexe(path,options,cb){fs.stat(path,function(er,stat){cb(er,er?!1:checkStat(stat,path,options))})}function sync(path,options){return checkStat(fs.statSync(path),path,options)}}});var require_mode=__commonJS({"node_modules/isexe/mode.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs=__require("fs");function isexe(path,options,cb){fs.stat(path,function(er,stat){cb(er,er?!1:checkStat(stat,options))})}function sync(path,options){return checkStat(fs.statSync(path),options)}function checkStat(stat,options){return stat.isFile()&&checkMode(stat,options)}function checkMode(stat,options){var mod=stat.mode,uid=stat.uid,gid=stat.gid,myUid=options.uid!==void 0?options.uid:process.getuid&&process.getuid(),myGid=options.gid!==void 0?options.gid:process.getgid&&process.getgid(),u=parseInt("100",8),g=parseInt("010",8),o=parseInt("001",8),ug=u|g,ret=mod&o||mod&g&&gid===myGid||mod&u&&uid===myUid||mod&ug&&myUid===0;return ret}}});var require_isexe=__commonJS({"node_modules/isexe/index.js"(exports,module){var fs=__require("fs"),core;process.platform==="win32"||global.TESTING_WINDOWS?core=require_windows():core=require_mode();module.exports=isexe;isexe.sync=sync;function isexe(path,options,cb){if(typeof options=="function"&&(cb=options,options={}),!cb){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(resolve,reject){isexe(path,options||{},function(er,is){er?reject(er):resolve(is)})})}core(path,options||{},function(er,is){er&&(er.code==="EACCES"||options&&options.ignoreErrors)&&(er=null,is=!1),cb(er,is)})}function sync(path,options){try{return core.sync(path,options||{})}catch(er){if(options&&options.ignoreErrors||er.code==="EACCES")return!1;throw er}}}});var require_which=__commonJS({"node_modules/which/which.js"(exports,module){var isWindows=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",path=__require("path"),COLON=isWindows?";":":",isexe=require_isexe(),getNotFoundError=cmd=>Object.assign(new Error(`not found: ${cmd}`),{code:"ENOENT"}),getPathInfo=(cmd,opt)=>{let colon=opt.colon||COLON,pathEnv=cmd.match(/\//)||isWindows&&cmd.match(/\\/)?[""]:[...isWindows?[process.cwd()]:[],...(opt.path||process.env.PATH||"").split(colon)],pathExtExe=isWindows?opt.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",pathExt=isWindows?pathExtExe.split(colon):[""];return isWindows&&cmd.indexOf(".")!==-1&&pathExt[0]!==""&&pathExt.unshift(""),{pathEnv,pathExt,pathExtExe}},which=(cmd,opt,cb)=>{typeof opt=="function"&&(cb=opt,opt={}),opt||(opt={});let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[],step=i=>new Promise((resolve,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve(found):reject(getNotFoundError(cmd));let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;resolve(subStep(p,i,0))}),subStep=(p,i,ii)=>new Promise((resolve,reject)=>{if(ii===pathExt.length)return resolve(step(i+1));let ext=pathExt[ii];isexe(p+ext,{pathExt:pathExtExe},(er,is)=>{if(!er&&is)if(opt.all)found.push(p+ext);else return resolve(p+ext);return resolve(subStep(p,i,ii+1))})});return cb?step(0).then(res=>cb(null,res),cb):step(0)},whichSync=(cmd,opt)=>{opt=opt||{};let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[];for(let i=0;i<pathEnv.length;i++){let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;for(let j=0;j<pathExt.length;j++){let cur=p+pathExt[j];try{if(isexe.sync(cur,{pathExt:pathExtExe}))if(opt.all)found.push(cur);else return cur}catch{}}}if(opt.all&&found.length)return found;if(opt.nothrow)return null;throw getNotFoundError(cmd)};module.exports=which;which.sync=whichSync}});var require_path_key=__commonJS({"node_modules/path-key/index.js"(exports,module){"use strict";var pathKey=(options={})=>{let environment=options.env||process.env;return(options.platform||process.platform)!=="win32"?"PATH":Object.keys(environment).reverse().find(key=>key.toUpperCase()==="PATH")||"Path"};module.exports=pathKey;module.exports.default=pathKey}});var require_resolveCommand=__commonJS({"node_modules/cross-spawn/lib/util/resolveCommand.js"(exports,module){"use strict";var path=__require("path"),which=require_which(),getPathKey=require_path_key();function resolveCommandAttempt(parsed,withoutPathExt){let env=parsed.options.env||process.env,cwd=process.cwd(),hasCustomCwd=parsed.options.cwd!=null,shouldSwitchCwd=hasCustomCwd&&process.chdir!==void 0&&!process.chdir.disabled;if(shouldSwitchCwd)try{process.chdir(parsed.options.cwd)}catch{}let resolved;try{resolved=which.sync(parsed.command,{path:env[getPathKey({env})],pathExt:withoutPathExt?path.delimiter:void 0})}catch{}finally{shouldSwitchCwd&&process.chdir(cwd)}return resolved&&(resolved=path.resolve(hasCustomCwd?parsed.options.cwd:"",resolved)),resolved}function resolveCommand(parsed){return resolveCommandAttempt(parsed)||resolveCommandAttempt(parsed,!0)}module.exports=resolveCommand}});var require_escape=__commonJS({"node_modules/cross-spawn/lib/util/escape.js"(exports,module){"use strict";var metaCharsRegExp=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(arg){return arg=arg.replace(metaCharsRegExp,"^$1"),arg}function escapeArgument(arg,doubleEscapeMetaChars){return arg=`${arg}`,arg=arg.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1"),arg=`"${arg}"`,arg=arg.replace(metaCharsRegExp,"^$1"),doubleEscapeMetaChars&&(arg=arg.replace(metaCharsRegExp,"^$1")),arg}module.exports.command=escapeCommand;module.exports.argument=escapeArgument}});var require_shebang_regex=__commonJS({"node_modules/shebang-regex/index.js"(exports,module){"use strict";module.exports=/^#!(.*)/}});var require_shebang_command=__commonJS({"node_modules/shebang-command/index.js"(exports,module){"use strict";var shebangRegex=require_shebang_regex();module.exports=(string="")=>{let match=string.match(shebangRegex);if(!match)return null;let[path,argument]=match[0].replace(/#! ?/,"").split(" "),binary=path.split("/").pop();return binary==="env"?argument:argument?`${binary} ${argument}`:binary}}});var require_readShebang=__commonJS({"node_modules/cross-spawn/lib/util/readShebang.js"(exports,module){"use strict";var fs=__require("fs"),shebangCommand=require_shebang_command();function readShebang(command){let buffer=Buffer.alloc(150),fd;try{fd=fs.openSync(command,"r"),fs.readSync(fd,buffer,0,150,0),fs.closeSync(fd)}catch{}return shebangCommand(buffer.toString())}module.exports=readShebang}});var require_parse=__commonJS({"node_modules/cross-spawn/lib/parse.js"(exports,module){"use strict";var path=__require("path"),resolveCommand=require_resolveCommand(),escape=require_escape(),readShebang=require_readShebang(),isWin=process.platform==="win32",isExecutableRegExp=/\.(?:com|exe)$/i,isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(parsed){parsed.file=resolveCommand(parsed);let shebang=parsed.file&&readShebang(parsed.file);return shebang?(parsed.args.unshift(parsed.file),parsed.command=shebang,resolveCommand(parsed)):parsed.file}function parseNonShell(parsed){if(!isWin)return parsed;let commandFile=detectShebang(parsed),needsShell=!isExecutableRegExp.test(commandFile);if(parsed.options.forceShell||needsShell){let needsDoubleEscapeMetaChars=isCmdShimRegExp.test(commandFile);parsed.command=path.normalize(parsed.command),parsed.command=escape.command(parsed.command),parsed.args=parsed.args.map(arg=>escape.argument(arg,needsDoubleEscapeMetaChars));let shellCommand=[parsed.command].concat(parsed.args).join(" ");parsed.args=["/d","/s","/c",`"${shellCommand}"`],parsed.command=process.env.comspec||"cmd.exe",parsed.options.windowsVerbatimArguments=!0}return parsed}function parse3(command,args,options){args&&!Array.isArray(args)&&(options=args,args=null),args=args?args.slice(0):[],options=Object.assign({},options);let parsed={command,args,options,file:void 0,original:{command,args}};return options.shell?parsed:parseNonShell(parsed)}module.exports=parse3}});var require_enoent=__commonJS({"node_modules/cross-spawn/lib/enoent.js"(exports,module){"use strict";var isWin=process.platform==="win32";function notFoundError(original,syscall){return Object.assign(new Error(`${syscall} ${original.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${syscall} ${original.command}`,path:original.command,spawnargs:original.args})}function hookChildProcess(cp,parsed){if(!isWin)return;let originalEmit=cp.emit;cp.emit=function(name,arg1){if(name==="exit"){let err=verifyENOENT(arg1,parsed);if(err)return originalEmit.call(cp,"error",err)}return originalEmit.apply(cp,arguments)}}function verifyENOENT(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawn"):null}function verifyENOENTSync(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawnSync"):null}module.exports={hookChildProcess,verifyENOENT,verifyENOENTSync,notFoundError}}});var require_cross_spawn=__commonJS({"node_modules/cross-spawn/index.js"(exports,module){"use strict";var cp=__require("child_process"),parse3=require_parse(),enoent=require_enoent();function spawn(command,args,options){let parsed=parse3(command,args,options),spawned=cp.spawn(parsed.command,parsed.args,parsed.options);return enoent.hookChildProcess(spawned,parsed),spawned}function spawnSync2(command,args,options){let parsed=parse3(command,args,options),result=cp.spawnSync(parsed.command,parsed.args,parsed.options);return result.error=result.error||enoent.verifyENOENTSync(result.status,parsed),result}module.exports=spawn;module.exports.spawn=spawn;module.exports.sync=spawnSync2;module.exports._parse=parse3;module.exports._enoent=enoent}});import{lstatSync as lstatSync3,readlinkSync as readlinkSync3,realpathSync as realpathSync3}from"node:fs";import{basename as basename2,dirname as dirname2,isAbsolute as isAbsolute4,join as join3,sep as sep3,win32}from"node:path";import{parentPort}from"node:worker_threads";import{lstatSync,readFileSync,readlinkSync,realpathSync,statSync}from"node:fs";import{isAbsolute,join,resolve as nodeResolvePath,parse,relative,sep}from"node:path";var import_cross_spawn=__toESM(require_cross_spawn(),1);var MAX_SYMLINK_HOPS=40,MISSING_PATH_CODES=new Set(["ENOENT","ENOTDIR"]);function splitParts(pathSegment){return pathSegment.split(sep).filter(part=>part.length>0)}function resolveWithoutOpen(inputPath){let absolutePath=isAbsolute(inputPath)?inputPath:nodeResolvePath(inputPath),{root}=parse(absolutePath),pending=splitParts(absolutePath.slice(root.length)),resolved=[],hops=0;for(;pending.length>0;){let part=pending.shift();if(part===void 0)break;if(part===".")continue;if(part===".."){resolved.pop();continue}let candidate=join(root,...resolved,part),link;try{if(!lstatSync(candidate).isSymbolicLink()){resolved.push(part);continue}if(hops+=1,hops>MAX_SYMLINK_HOPS)return{path:join(candidate,...pending),errorCode:"ELOOP"};link=readlinkSync(candidate)}catch(error){let code=error?.code??"UNKNOWN";return{path:join(candidate,...pending),errorCode:code}}isAbsolute(link)?(resolved.length=0,pending.unshift(...splitParts(link.slice(parse(link).root.length)))):pending.unshift(...splitParts(link))}return{path:join(root,...resolved)}}function realpathWithoutOpenStrict(inputPath){let resolution=resolveWithoutOpen(inputPath);if(resolution.errorCode!==void 0&&!MISSING_PATH_CODES.has(resolution.errorCode))throw Object.assign(new Error(`${resolution.errorCode}: cannot resolve path '${inputPath}' without opening it`),{code:resolution.errorCode,path:inputPath});return resolution.path}import{lstatSync as lstatSync2,readdirSync,readFileSync as readFileSync2,readlinkSync as readlinkSync2,realpathSync as realpathSync2}from"node:fs";import{basename,dirname,isAbsolute as isAbsolute2,join as join2,parse as parse2,sep as sep2}from"node:path";var MISSING=new Set(["ENOENT","ENOTDIR"]),MAX_DANGLING_HOPS=40;function failure(code){return Object.assign(new Error(code),{code})}function errorCode(error){let code=error?.code;return typeof code=="string"?code:"EUNKNOWN"}function stripWin32Components(value,sep4){return value.split(sep4).map((part,index)=>index===0?part:part.replace(/[. ]+$/u,"")).join(sep4)}function createPathIdentity({realpathNative,lstat,readlink,pathApi,platform}){let{join:join4,dirname:dirname3,basename:basename3,isAbsolute:isAbsolute5,sep:sep4,win32Resolve}=pathApi,normalizeForm=value=>platform==="darwin"?value.normalize("NFC"):value,foldDefault=platform==="darwin"||platform==="win32",foldByDevice=new Map,anchor=(value,cwd)=>{if(platform==="win32")return stripWin32Components(cwd===void 0?win32Resolve(value):win32Resolve(cwd,value),sep4);if(isAbsolute5(value))return value;if(cwd===void 0)throw failure("ERELATIVE");return cwd+sep4+value},climb=base=>{let existing=base,missing=[],hops=0,followedDangling=!1;for(;;){let real;try{real=realpathNative(existing)}catch(error){let code=errorCode(error);if(!MISSING.has(code))throw failure(code);let info;try{info=lstat(existing)}catch(inner){let innerCode=errorCode(inner);if(!MISSING.has(innerCode))throw failure(innerCode);info=void 0}if(info?.isSymbolicLink()){if(hops+=1,hops>MAX_DANGLING_HOPS)throw failure("ELOOP");let target=readlink(existing);existing=isAbsolute5(target)?target:join4(dirname3(existing),target),followedDangling=!0;continue}if(followedDangling&&missing.length>0)throw failure("EDANGLING");missing.unshift(basename3(existing));let parent=dirname3(existing);if(parent===existing)throw failure(code);existing=parent;continue}return{real,path:missing.length?join4(real,...missing):real}}},sameDevice=(value,device)=>{try{return lstat(value,{bigint:!0}).dev===device}catch{return!1}},probeFoldCase=(existingPath,device)=>{let probe=existingPath;for(;;){let chars=[...basename3(probe)],index=chars.findIndex(char=>char.toLowerCase()!==char.toUpperCase());if(index>=0){let char=chars[index]??"";chars[index]=char===char.toLowerCase()?char.toUpperCase():char.toLowerCase();let swapped=join4(dirname3(probe),chars.join(""));try{let original=lstat(probe,{bigint:!0}),variant=lstat(swapped,{bigint:!0});return original.dev===variant.dev&&original.ino===variant.ino}catch{return!1}}let parent=dirname3(probe);if(parent===probe||(probe=parent,!sameDevice(probe,device)))return foldDefault}},volumeFoldCase=existingPath=>{let device;try{device=lstat(existingPath,{bigint:!0}).dev}catch{return foldDefault}let cached=foldByDevice.get(device);if(cached!==void 0)return cached;let answer=probeFoldCase(existingPath,device);return foldByDevice.set(device,answer),answer},canonical=(executed,cwd)=>{let{real,path}=climb(anchor(executed,cwd));return{path:normalizeForm(path),foldCase:volumeFoldCase(real)}};return{canonical,canonicalRule:(pattern,cwd)=>{if(pattern==="*")return;let wildcard=pattern.search(/[*?]/u);if(wildcard<0){let{path:path2,foldCase:foldCase2}=canonical(pattern,cwd);return{prefix:path2,foldCase:foldCase2,suffix:"",wildcardOnly:!1}}let boundary=Math.max(pattern.lastIndexOf("/",wildcard),pattern.lastIndexOf(sep4,wildcard));if(boundary<0)return{prefix:void 0,foldCase:foldDefault,suffix:normalizeForm(pattern),wildcardOnly:!0};let{path,foldCase}=canonical(pattern.slice(0,boundary)||sep4,cwd);return{prefix:path,foldCase,suffix:normalizeForm(pattern.slice(boundary)),wildcardOnly:!1}},volumeFoldCase}}var REAL_FS=new Set(["apfs","hfs","ext4","xfs","btrfs","zfs","tmpfs","ntfs","exfat","overlay","virtiofs","nfs","nfs4"]),DETECTOR_MAX_READDIR=256,DETECTOR_MAX_ENTRIES=5e3;function mountAliasRoots(snapshot,platform=process.platform){if(platform!=="darwin")return[];let dataDevice=snapshot.mounts.find(mount=>mount.on==="/System/Volumes/Data")?.dev;return snapshot.mounts.filter(mount=>mount.on==="/System/Volumes/Data"||dataDevice!==void 0&&mount.dev===dataDevice&&mount.on!=="/").map(mount=>mount.on)}var DARWIN_FIRMLINKS="/usr/share/firmlinks";function readFirmlinks(platform=process.platform){if(platform!=="darwin")return[];try{return readFileSync2(DARWIN_FIRMLINKS,"utf8").split(`
`).map(line=>line.split(" ")[0]?.trim()??"").filter(entry=>entry.startsWith("/"))}catch{return[]}}var defaultIO={walk:realpathWithoutOpenStrict,readdir:value=>readdirSync(value),lstat:value=>lstatSync2(value)};function codeOf(error){let code=error?.code;return typeof code=="string"?code:"UNKNOWN"}function createDetector(snapshot,budget={maxReaddir:DETECTOR_MAX_READDIR,maxEntries:DETECTOR_MAX_ENTRIES},io=defaultIO,platform=process.platform){let mounts=[...snapshot.mounts].sort((a,b)=>b.on.length-a.on.length),ambiguous=new Set(snapshot.ambiguous),roots=mountAliasRoots(snapshot,platform),mountFor=value=>mounts.find(mount=>value===mount.on||value.startsWith(mount.on==="/"?"/":`${mount.on}/`)),unconfirmedBy=value=>{let mount=mountFor(value);return!mount||!REAL_FS.has(mount.type)?`fs-type:${mount?.type??"no-mount-entry"}`:ambiguous.has(mount.on)?`mount-point-ambiguous:${mount.on}`:void 0},mountAliased=value=>roots.some(root=>value===root||value.startsWith(`${root}/`));return value=>{let reasons=[],readdirs=0;snapshot.degraded&&reasons.push("mount-snapshot-degraded"),isAbsolute2(value)||reasons.push("relative"),value.split(sep2).some(component=>component==="."||component==="..")&&reasons.push("dot-component"),value!=="/"&&(value.endsWith("/")||value.includes("//"))&&reasons.push("separator-spelling"),mountAliased(value)&&reasons.push("mount-alias");let walked;try{walked=io.walk(value)}catch(error){return reasons.push(`walker:${codeOf(error)}`),{alias:!0,reasons,readdirs}}if(walked!==value&&reasons.push("walker-differs"),mountAliased(walked)&&reasons.push("mount-alias-after-walk"),reasons.length)return{alias:!0,reasons,readdirs};let root=parse2(walked).root,parts=walked.slice(root.length).split(sep2).filter(Boolean),parent=root,rootReason=unconfirmedBy(root);if(rootReason!==void 0)return reasons.push(rootReason),{alias:!0,reasons,readdirs};for(let part of parts){let here=join2(parent,part),reason=unconfirmedBy(here);if(reason!==void 0){reasons.push(`${reason}@${here}`);break}let entries;try{if(readdirs+=1,readdirs>budget.maxReaddir)throw Object.assign(new Error("EBUDGET"),{code:"EBUDGET"});entries=io.readdir(parent)}catch(error){reasons.push(`readdir:${codeOf(error)}@${parent}`);break}if(entries.length>budget.maxEntries){reasons.push(`EBUDGET-entries@${parent}`);break}if(!entries.includes(part)){let exists=!0;try{io.lstat(here)}catch(error){let code=codeOf(error);if(code!=="ENOENT"&&code!=="ENOTDIR"){reasons.push(`lstat:${code}@${here}`);break}exists=!1}if(exists){reasons.push(`not-enumerable@${here}`);break}let full=!1;try{io.lstat(walked),full=!0}catch(error){let code=codeOf(error);code!=="ENOENT"&&code!=="ENOTDIR"&&reasons.push(`lstat:${code}@${walked}`)}full&&reasons.push(`phantom-parent@${here}`);break}parent=here}return{alias:reasons.length>0,reasons,readdirs}}}import{spawnSync}from"node:child_process";import{existsSync,readFileSync as readFileSync3}from"node:fs";import{isAbsolute as isAbsolute3}from"node:path";var TYPE_TOKEN=/^[a-z0-9_.-]+$/i;function validMountPoint(on){return on.length>0&&isAbsolute3(on)&&!on.includes("//")&&(on==="/"||!on.endsWith("/"))}function parseDarwinMountLine(line){let match=/^(.*) \(([^()]*)\)$/.exec(line);if(!match)return;let type=(match[2]??"").split(",")[0]?.trim()??"";if(!TYPE_TOKEN.test(type))return;let head=match[1]??"",onIndex=head.indexOf(" on ");if(onIndex<=0)return;let dev=head.slice(0,onIndex),on=head.slice(onIndex+4);if(!(!dev||!validMountPoint(on)))return{dev,on,type}}function unescapeLinuxMountField(value){return value.replace(/\\([0-7]{3})/g,(_,octal)=>String.fromCharCode(Number.parseInt(octal,8)))}function parseLinuxMountLine(line){let parts=line.split(" ");if(parts.length<3)return;let on=unescapeLinuxMountField(parts[1]??""),type=parts[2]??"",dev=unescapeLinuxMountField(parts[0]??"");if(!(!dev||!validMountPoint(on)||!TYPE_TOKEN.test(type)))return{dev,on,type}}function parseMountTable(text,platform=process.platform){let byPoint=new Map,rejected=[],order=0;for(let line of text.split(`
`)){if(line.trim().length===0)continue;let entry=platform==="darwin"?parseDarwinMountLine(line):parseLinuxMountLine(line);entry?byPoint.set(entry.on,{entry,lines:(byPoint.get(entry.on)?.lines??0)+1,last:order++}):rejected.push(line)}let listed=[...byPoint.values()],under=(point,ancestor)=>point!==ancestor&&point.startsWith(ancestor==="/"?"/":`${ancestor}/`),points=platform==="linux"?listed.filter(point=>!listed.some(other=>other.last>point.last&&under(point.entry.on,other.entry.on))):listed,mounts=points.map(point=>point.entry).sort((a,b)=>b.on.length-a.on.length),ambiguous=platform==="linux"?[]:points.filter(point=>point.lines>1).map(point=>point.entry.on),degraded=rejected.length>0||!mounts.some(mount=>mount.on==="/");return{mounts,degraded,rejected,ambiguous}}function readMountTable(platform=process.platform){if(platform==="darwin"){let result=spawnSync("mount",[],{encoding:"utf8"});return result.error||result.status!==0?{mounts:[],degraded:!0,rejected:["mount command failed"],ambiguous:[]}:parseMountTable(result.stdout,"darwin")}return existsSync("/proc/self/mounts")?parseMountTable(readFileSync3("/proc/self/mounts","utf8"),"linux"):{mounts:[],degraded:!0,rejected:["no mount table source"],ambiguous:[]}}var MOUNT_REFRESH_MS=6e4;function codeOf2(error){let code=error?.code;return typeof code=="string"?code:"EUNKNOWN"}function createResolverService(readTable=readMountTable){let identity=createPathIdentity({realpathNative:value=>realpathSync3.native(value),lstat:(value,options)=>options?lstatSync3(value,options):lstatSync3(value,{bigint:!0}),readlink:value=>readlinkSync3(value),pathApi:{join:join3,dirname:dirname2,basename:basename2,isAbsolute:isAbsolute4,sep:sep3,win32Resolve:win32.resolve},platform:process.platform}),detector,snapshot=()=>{let table=readTable();return detector=createDetector(table),{type:"snapshot",snapshot:table,firmlinks:readFirmlinks()}},detect=value=>(detector||snapshot(),detector?detector(value).alias:!0);return{snapshot,serve(request){try{switch(request.kind){case"canonicalize":return{id:request.id,ok:!0,value:identity.canonical(request.path,request.cwd)};case"canonicalizeRule":return{id:request.id,ok:!0,value:identity.canonicalRule(request.pattern,request.cwd)};case"detect":return{id:request.id,ok:!0,value:detect(request.path)};case"walk":return{id:request.id,ok:!0,value:realpathWithoutOpenStrict(request.path)};case"refresh":return{id:request.id,ok:!0,value:void 0}}}catch(error){return{id:request.id,ok:!1,code:codeOf2(error)}}}}}if(parentPort){let port=parentPort,service=createResolverService(),publish=()=>port.postMessage(service.snapshot());publish(),setInterval(publish,MOUNT_REFRESH_MS).unref(),port.on("message",request=>{request.kind==="refresh"&&publish(),port.postMessage(service.serve(request))})}export{createResolverService};