knarr 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/add-CZp5YVWF.mjs +1 -0
- package/dist/add-flow-D9HxSmKS.mjs +3 -0
- package/dist/batch-push-CT5k2SrS.mjs +1 -0
- package/dist/build-detect-Bf2HAfXm.mjs +1 -0
- package/dist/bundler-detect-BaShXORS.mjs +1 -0
- package/dist/check-BFgQ7Px_.mjs +1 -0
- package/dist/chokidar-DoHpObCq.mjs +1 -0
- package/dist/clean-B4S8pHpI.mjs +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.mjs +2 -3
- package/dist/config-DEpSKyI8.mjs +2 -0
- package/dist/console-C8XtlRyM.mjs +1 -0
- package/dist/dev-DtbwBD_E.mjs +1 -0
- package/dist/dist-jMqCJR3W.mjs +5 -0
- package/dist/doctor-Ca2eGyC8.mjs +4 -0
- package/dist/dry-run-DPoN8bZo.mjs +1 -0
- package/dist/errors-DRugrv36.mjs +1 -0
- package/dist/explain-U6-XLo4U.mjs +1 -0
- package/dist/format-IsfSiyGV.mjs +1 -0
- package/dist/fs-Ce7wcxvx.mjs +1 -0
- package/dist/fs-DusqxRQR.mjs +1 -0
- package/dist/hints-BKo_2axg.mjs +1 -0
- package/dist/history-BNX-3W-p.mjs +1 -0
- package/dist/history-Da5gEptz.mjs +1 -0
- package/dist/index.mjs +1 -3637
- package/dist/init-BJZdXWmg.mjs +2 -0
- package/dist/init-helpers-DfznkCwv.mjs +13 -0
- package/dist/injector-CwNZ9rDe.mjs +1 -0
- package/dist/json-b5d4W58a.mjs +1 -0
- package/dist/list-BekXJBqC.mjs +1 -0
- package/dist/logger-Oo2Slehd.mjs +1 -0
- package/dist/migrate-DGXYBPRz.mjs +3 -0
- package/dist/nextjs-config-C2Xv-pZR.mjs +1 -0
- package/dist/nextjs-config-D3H6P4Is.mjs +2 -0
- package/dist/output-B7NC4xgj.mjs +1 -0
- package/dist/package-manager-DENvuHqT.mjs +11 -0
- package/dist/paths-V3_BeE_z.mjs +1 -0
- package/dist/picomatch-DEttMFSR.mjs +1 -0
- package/dist/preflight-DPlVrYLp.mjs +1 -0
- package/dist/preflight-tgLzruAR.mjs +1 -0
- package/dist/publish-DViw9ie6.mjs +1 -0
- package/dist/publisher-PQIqCt7r.mjs +2 -0
- package/dist/push-ChVt0ofE.mjs +1 -0
- package/dist/push-engine-IoOaMeZe.mjs +1 -0
- package/dist/remove-BVr3n-3t.mjs +1 -0
- package/dist/remove-Ch5tlQkh.mjs +1 -0
- package/dist/reset-DD5BaA6m.mjs +1 -0
- package/dist/restore-DaJjdT2B.mjs +1 -0
- package/dist/rollback-B7QjnKje.mjs +1 -0
- package/dist/shell-DQfdqK0J.mjs +1 -0
- package/dist/status-BHe6UGa2.mjs +1 -0
- package/dist/store-D2r3Vo5S.mjs +1 -0
- package/dist/tailwind-source-Ck2WyTX8.mjs +3 -0
- package/dist/timer-BZNWRS3O.mjs +1 -0
- package/dist/topo-sort-CNCKE3Ap.mjs +1 -0
- package/dist/topo-sort-I086ZoiN.mjs +1 -0
- package/dist/tracker-BUpkmn8j.mjs +1 -0
- package/dist/tracker-Cf_gNhit.mjs +1 -0
- package/dist/update-BuQUMzU2.mjs +1 -0
- package/dist/use-By-V869_.mjs +1 -0
- package/dist/validators-C0_prNkT.mjs +1 -0
- package/dist/vite-config-Bvv75_oH.mjs +10 -0
- package/dist/vite-config-DQfi8QwQ.mjs +1 -0
- package/dist/vite-plugin.mjs +1 -210
- package/dist/watch-orchestrator-5eaHlofc.mjs +1 -0
- package/dist/watch-orchestrator-B1hlJ10Y.mjs +1 -0
- package/dist/watcher-DN6vT6nw.mjs +1 -0
- package/dist/watcher-LcNLwOgA.mjs +1 -0
- package/dist/webpack-plugin.mjs +1 -145
- package/dist/workspace-BBfh7dJY.mjs +1 -0
- package/dist/workspace-CYaUDFd5.mjs +1 -0
- package/package.json +4 -7
- package/dist/add-B_xzUp5y.mjs +0 -3
- package/dist/add-flow-cvrMO_aV.mjs +0 -5
- package/dist/batch-push-DXtZxRx0.mjs +0 -3
- package/dist/build-detect-BTHh2OBm.mjs +0 -3
- package/dist/bundler-detect-Dq-QAbQj.mjs +0 -3
- package/dist/check-CbVdpTsw.mjs +0 -3
- package/dist/chokidar-BkIWf7Ix.mjs +0 -3
- package/dist/clean-CyDDqbBD.mjs +0 -3
- package/dist/config-BJsL6NqN.mjs +0 -4
- package/dist/console-CIiXr7ge.mjs +0 -3
- package/dist/console-CyaBcUd-.mjs +0 -98
- package/dist/dev-kqgY9NjI.mjs +0 -3
- package/dist/dist-CFkjiIqD.mjs +0 -7
- package/dist/doctor-D-S1P0UG.mjs +0 -6
- package/dist/dry-run-BkdMYSIx.mjs +0 -3
- package/dist/errors-BlOfexcH.mjs +0 -3
- package/dist/explain-9Y4SZHjC.mjs +0 -3
- package/dist/format-DRqD29u-.mjs +0 -3
- package/dist/fs-C4juVCTd.mjs +0 -3
- package/dist/fs-CPnWm9CR.mjs +0 -3
- package/dist/fs-DzsciYAL.mjs +0 -757
- package/dist/hints-Hz3V4h3A.mjs +0 -3
- package/dist/history-DRhLwzhq.mjs +0 -3
- package/dist/history-vS3w4EGu.mjs +0 -3
- package/dist/init-TN84d5jM.mjs +0 -4
- package/dist/init-helpers-CYYWQm-P.mjs +0 -15
- package/dist/injector-nt40JxVt.mjs +0 -3
- package/dist/json-DbSkpxtr.mjs +0 -3
- package/dist/list-9hWJjw19.mjs +0 -3
- package/dist/logger-9C6B9Na8.mjs +0 -3
- package/dist/migrate-Co4qcFt6.mjs +0 -5
- package/dist/nextjs-config-BQgTWZ96.mjs +0 -3
- package/dist/nextjs-config-dUw2J6B9.mjs +0 -4
- package/dist/output-BxR2v-jn.mjs +0 -3
- package/dist/package-manager-DJ8CE0zL.mjs +0 -13
- package/dist/picomatch-B0_Pxgms.mjs +0 -3
- package/dist/preflight-BDsxR2Ct.mjs +0 -3
- package/dist/preflight-MzNjLXiy.mjs +0 -3
- package/dist/publish-C7ZUvHkE.mjs +0 -3
- package/dist/publisher-CvXTbkLP.mjs +0 -4
- package/dist/push-B5KrkILW.mjs +0 -3
- package/dist/push-engine-BpNr8qXR.mjs +0 -3
- package/dist/remove-DkOgVQMZ.mjs +0 -3
- package/dist/remove-J5tY_BFk.mjs +0 -3
- package/dist/reset-ClGouUb5.mjs +0 -3
- package/dist/restore-Bx2V59SL.mjs +0 -3
- package/dist/rollback-RPjHZWtG.mjs +0 -3
- package/dist/rolldown-runtime-BZbIAPMk.mjs +0 -3
- package/dist/shell-RQ7Hf1kp.mjs +0 -3
- package/dist/status-Rnvw6dG2.mjs +0 -3
- package/dist/store-DjPdOKqg.mjs +0 -3
- package/dist/tailwind-source-D1cUiG-t.mjs +0 -5
- package/dist/timer-DqgB175x.mjs +0 -3
- package/dist/topo-sort-DOCpHjT7.mjs +0 -3
- package/dist/topo-sort-yd4jxr_E.mjs +0 -3
- package/dist/tracker-89eW0ArT.mjs +0 -3
- package/dist/tracker-B3Fqx94J.mjs +0 -3
- package/dist/update-CAKFICZu.mjs +0 -3
- package/dist/use-CCx6J0mc.mjs +0 -3
- package/dist/vite-config-BHmawlD2.mjs +0 -12
- package/dist/vite-config-BRlYc4ni.mjs +0 -3
- package/dist/watch-orchestrator-BfuCaZLA.mjs +0 -3
- package/dist/watcher-T123sBDg.mjs +0 -3
- package/dist/workspace-CdLSxPFS.mjs +0 -3
- package/dist/workspace-DBxNrowu.mjs +0 -3
- package/dist/xxhash-wasm-D_QjdUuv.mjs +0 -3
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{type as e}from"node:os";import{EventEmitter as t}from"node:events";import{realpathSync as n,watch as r}from"node:fs";import{lstat as i,open as a,readdir as o,readlink as s,realpath as c,stat as l}from"node:fs/promises";import*as u from"node:path";import{join as d,resolve as f,sep as p}from"node:path";import{Readable as m}from"node:stream";const h={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},g={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:h.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(g);const _=`READDIRP_RECURSIVE_ERROR`,v=/* @__PURE__ */ new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,_]),y=[h.DIR_TYPE,h.EVERYTHING_TYPE,h.FILE_DIR_TYPE,h.FILE_TYPE],b=/* @__PURE__ */ new Set([h.DIR_TYPE,h.EVERYTHING_TYPE,h.FILE_DIR_TYPE]),x=/* @__PURE__ */ new Set([h.EVERYTHING_TYPE,h.FILE_DIR_TYPE,h.FILE_TYPE]),isNormalFlowError=e=>v.has(e.code),S=process.platform===`win32`,emptyFn=e=>!0,normalizeFilter=e=>{if(e===void 0)return emptyFn;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return emptyFn};var ReaddirpStream=class extends m{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark??g.highWaterMark});let t={...g,...e},n=t.root??g.root,r=t.type??g.type;this._fileFilter=normalizeFilter(t.fileFilter),this._directoryFilter=normalizeFilter(t.directoryFilter);let a=t.lstat?i:l;this._stat=S?e=>a(e,{bigint:!0}):a,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:g.depth,this._wantsDir=b.has(r),this._wantsFile=x.has(r),this._wantsEverything=r===h.EVERYTHING_TYPE,this._root=f(n),this._relStart=this._root.endsWith(p)?this._root.length:this._root.length+1,this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent};let o={path:this._root,depth:1};o.pending=this._exploreDir(this._root,1),this.parents=[o],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=this._isDirent?a:await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=this._getEntryType(t);typeof n!=`string`&&(n=await n),n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push({path:t.fullPath,depth:i+1}),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}let t=e.pending??this._exploreDir(e.path,e.depth),n=this.parents[this.parents.length-1];if(n&&!n.pending&&(n.pending=this._exploreDir(n.path,n.depth)),this.parent=await t,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await o(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}_formatEntry(e,t){let n=this._isDirent?e.name:e,r=d(t,n),i={path:r.slice(this._relStart),fullPath:r,basename:n};return this._isDirent?(i.dirent=e,i):this._stat(r).then(e=>(i.stats=e,i),e=>{this._onError(e)})}_onError(e){isNormalFlowError(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return``;let t=e[this._statsProp];return t.isFile()?`file`:t.isDirectory()?`directory`:t.isSymbolicLink()?this._getSymlinkEntryType(e):``}async _getSymlinkEntryType(e){let t=e.fullPath;try{let e=await c(t),n=await i(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t[n]===p){let n=/* @__PURE__ */ Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=_,this._onError(n),``}return`directory`}}catch(e){this._onError(e)}return``}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function readdirp(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=h.FILE_DIR_TYPE),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!y.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${y.join(`, `)}`);let r={...t,root:e};return n&&(r.type=n),new ReaddirpStream(r)}const C=process.platform,w=C===`win32`,T=C===`darwin`,E=C===`linux`,D=e()===`OS400`;function errorCode(e){return e?.code}function classifyError(e){let t=errorCode(e);return t===`ENOENT`||t===`ENOTDIR`?`missing`:t===`EPERM`||t===`EACCES`?`permission`:t===`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`?`recursive-unsupported`:`other`}function isMissingError(e){return classifyError(e)===`missing`}function isPermissionError(e){return classifyError(e)===`permission`}function isRecursiveWatchUnsupported(e){return classifyError(e)===`recursive-unsupported`}const O=Object.freeze({now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>{e&&clearTimeout(e)}}),k={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},A=/\\/g,j=/\/\//g;function normalizePath(e){if(typeof e!=`string`)throw TypeError(`string expected`);let t=e.replace(A,`/`),n=t.startsWith(`//`),r=u.normalize(t).replace(A,`/`).replace(j,`/`);return n&&!r.startsWith(`//`)&&(r=`/${r}`),r}function statIdentity(e){if(typeof e.mtimeMs!=`bigint`)return e;let t=e,n=t.mtimeNs/1000000000n,r=t.mtimeNs%1000000000n,i=Number(n)*1e3+Number(r)/1e6;return{size:Number(t.size),mtimeMs:i,ino:Number(t.ino)}}function logicalPathKey(e){let t=u.resolve(e);return w||!t.includes(`\\`)?t.replace(A,`/`):normalizePath(t)}function isInsideRelativePath(e){return e!==`..`&&!e.startsWith(`..${u.sep}`)&&!u.isAbsolute(e)}function isSameOrInside(e,t){let n=u.relative(e,t);return n===``||isInsideRelativePath(n)}function isStrictlyInside(e,t){let n=u.relative(e,t);return n!==``&&isInsideRelativePath(n)}function isMatcherObject(e){return typeof e==`object`&&!!e&&!(e instanceof RegExp)}function cloneOwnedMatcher(e){return e instanceof RegExp?new RegExp(e.source,e.flags):isMatcherObject(e)?Object.freeze({...e}):e}function compileMatcher(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>(e.lastIndex=0,e.test(t)):isMatcherObject(e)?t=>e.path===t||!!(e.recursive&&isStrictlyInside(e.path,t)):()=>!1}function compileMatchers(e){let t=e.map(compileMatcher);return(e,n)=>{if(t.length===0)return!1;let r=normalizePath(e);return t.some(e=>e(r,n))}}function normalizeMatcher(e,t=process.cwd()){return typeof e==`string`?normalizePath(u.isAbsolute(e)?e:u.join(t,e)):isMatcherObject(e)?{path:normalizePath(u.isAbsolute(e.path)?e.path:u.join(t,e.path)),recursive:e.recursive}:e}const M=/^\.[/\\]/;var N=class WatchHelper{watchPath;followSymlinks;recursiveRoot;recursiveDisabled;observationTrigger;realpathAncestry;pathGeneration;context;constructor(e,t,n){this.context=n,this.watchPath=e.replace(M,``),this.followSymlinks=t,this.realpathAncestry=/* @__PURE__ */ new Set,this.pathGeneration=n.capturePathGeneration()}fork(e){let t=new WatchHelper(e,this.followSymlinks,this.context);return t.recursiveRoot=this.recursiveRoot,t.recursiveDisabled=this.recursiveDisabled,t.observationTrigger=this.observationTrigger,t.realpathAncestry=new Set(this.realpathAncestry),t.pathGeneration=this.pathGeneration,t}withObservation(e){let t=Object.create(this);return t.observationTrigger=e,t}filterPath(e){return e.stats?.isSymbolicLink()?this.filterDir(e):this.context.isntIgnored(u.join(this.watchPath,e.path),e.stats)}filterDir(e){return this.context.isntIgnored(u.join(this.watchPath,e.path),e.stats)}};let P=0;function allocateSharedResourceGeneration(){return++P}function attachSharedSubscriber(e,t){return!e.closed&&(e.subscribers.add(t),!0)}function detachSharedSubscriber(e,t){if(!e.closed&&e.subscribers.delete(t))return e.subscribers.size>0?`remaining`:`last`}function invalidateSharedResource(e){if(e.closed)return;e.closed=!0;let t=[...e.subscribers];return e.subscribers.clear(),t}function reconfigureWatcherPersistence(e){[...e.subscribers].some(e=>e.persistent)?e.watcher.ref():e.watcher.unref()}function invalidateWatcherResource(e,t){let n=invalidateSharedResource(e);if(n)return t.get(e.resource)===e&&t.delete(e.resource),e.watcher.close(),n}function attachWatcherSubscriber(e,t){attachSharedSubscriber(e,t),reconfigureWatcherPersistence(e)}function createWatcherSubscription(e,t,n){let r=!1;return{resource:e.resource,close:()=>{if(r)return;r=!0;let i=detachSharedSubscriber(e,t);i===`remaining`?reconfigureWatcherPersistence(e):i===`last`&&n.get(e.resource)===e&&invalidateWatcherResource(e,n)}}}function selectBackend(e){let t=e.backend===`native-recursive`||e.backend===`auto`&&(T||w),n=e.backend===`polling`?`polling`:t&&e.depth===void 0?`native-recursive-preferred`:`native-per-directory`;return Object.freeze({kind:n,polling:n===`polling`,recursive:n===`native-recursive-preferred`,perDirectory:n===`native-per-directory`})}const F=k;function backendNow(){return performance.now()}function toNativeWatchPath(e){let t=u.normalize(e);if(!w)return t;try{return n.native(t)}catch{return t}}function projectNativeRelativePath(e,t){if(!w||t===null||!u.isAbsolute(t))return t;let n=u.normalize(u.toNamespacedPath(e)),r=u.normalize(u.toNamespacedPath(t)),i=u.relative(n,r);return isSameOrInside(n,r)?i||null:t}const I=/* @__PURE__ */ new Map;function systemNativeWatchFactory(e,t,n){return r(e,t,n)}let L=systemNativeWatchFactory;const R=/* @__PURE__ */ new Map;let z=!1;function systemRecursiveWatchFactory(e,t,n){return r(e,t,n)}let B=systemRecursiveWatchFactory;function failRecursiveResource(e,t){let n=invalidateWatcherResource(e,R);n&&n.forEach(e=>e.failure(t))}function subscribeRecursiveNative(e,t,n,r){if(z)return{kind:`unsupported`};let i=u.resolve(e),a={...n,watchedPath:e,persistent:t},o=R.get(i);if(!o){let n,r,a=toNativeWatchPath(e);try{n=B(a,{persistent:t,recursive:!0},(e,t)=>{let n=r;if(!n||n.closed||R.get(i)!==n)return;let o={kind:`native`,resource:i,rawEvent:e,relativePath:projectNativeRelativePath(a,t),sequence:++n.sequence,observedAt:backendNow()};n.subscribers.forEach(n=>{n.rawEmitter(e,t,{watchedPath:n.watchedPath}),n.publish(o)})})}catch(e){return isRecursiveWatchUnsupported(e)?(z=!0,{kind:`unsupported`}):{kind:`failed`,error:e}}r=o={resource:i,generation:allocateSharedResourceGeneration(),subscribers:/* @__PURE__ */ new Set,closed:!1,watcher:n,sequence:0},R.set(i,o),n.on(F.ERROR,e=>failRecursiveResource(o,e))}attachWatcherSubscriber(o,a);let s=createWatcherSubscription(o,a,R);return r.aborted&&s.close(),{kind:`subscribed`,subscription:s}}function createFsWatchInstance(e,t,n,r){try{return L(e,{persistent:t.persistent},n)}catch(e){r(e);return}}function publishNativeTrigger(e,t,n,r,i=n){if(e.closed||I.get(e.resource)!==e)return;let a={kind:`native`,resource:e.resource,rawEvent:t,relativePath:n,sequence:++e.sequence,observedAt:backendNow()};e.subscribers.forEach(e=>{r&&e.rawEmitter(t,i,{watchedPath:e.watchedPath}),e.publish(a)})}function broadcastNativeError(e,t){e.closed||I.get(e.resource)!==e||e.subscribers.forEach(e=>e.errHandler(t))}function closeFailedNativeResource(e,t){invalidateWatcherResource(e,I)?.forEach(e=>e.failure?.(t))}async function handleNativeError(e,t,n){if(w&&n.code===`EPERM`)try{await(await a(e,`r`)).close(),broadcastNativeError(t,n)}catch{publishNativeTrigger(t,`rename`,null,!1)}else broadcastNativeError(t,n);closeFailedNativeResource(t,n)}async function retireIfSelfRemoved(e,t){try{await i(u.join(t,u.basename(t)));return}catch(e){if(!isMissingError(e))return}try{if(!(await l(t)).isDirectory())return}catch{return}e.closed||I.get(e.resource)!==e||closeFailedNativeResource(e,/* @__PURE__ */ Error(`Watched directory was replaced: ${t}`))}function createNativeContainer(e,t,n,r,i){let a,o=createFsWatchInstance(t,r,(e,n)=>{let r=projectNativeRelativePath(t,n);publishNativeTrigger(a,e,r,!0,n),E&&e===`rename`&&n===u.basename(t)&&retireIfSelfRemoved(a,t)},i.errHandler);if(o)return a={resource:n,generation:allocateSharedResourceGeneration(),subscribers:/* @__PURE__ */ new Set([i]),closed:!1,watcher:o,sequence:0},I.set(n,a),o.on(F.ERROR,t=>{handleNativeError(e,a,t)}),a}function setFsWatchListener(e,t,n,r,i){let a=t,o={...r,watchedPath:e,persistent:n.persistent??!0},s=I.get(a);if(s)attachWatcherSubscriber(s,o);else if(s=createNativeContainer(e,toNativeWatchPath(e),a,n,o),!s)return;let c=createWatcherSubscription(s,o,I);if(i.aborted)c.close();else return c}const V=Object.freeze({missing:!0}),H=/* @__PURE__ */ new Map;function isMissingObservation(e){return`missing`in e}function observationsDiffer(e,t){let n=isMissingObservation(e),r=isMissingObservation(t);if(n||r)return n!==r;let i=!w&&e.ino!==0&&t.ino!==0&&e.ino!==t.ino;return e.size!==t.size||e.mtimeMs!==t.mtimeMs||i}function setTimerPersistence(e){e.timer&&(e.persistent?e.timer.ref():e.timer.unref())}function schedulePoll(e,t=e.interval){e.closed||e.subscribers.size===0||(e.timer=e.scheduler.setTimeout(()=>{e.timer=void 0;let t=pollResource(e);e.currentPoll=t,t.then(()=>{e.currentPoll===t&&(e.currentPoll=void 0)},()=>{e.currentPoll===t&&(e.currentPoll=void 0)})},t),setTimerPersistence(e))}async function pollResource(e){if(e.closed||e.running||e.subscribers.size===0)return;e.running=!0;let t=e.scheduler.now(),n;try{n=await l(e.resource)}catch(t){isMissingError(t)?n=V:e.subscribers.forEach(e=>e.errHandler(t))}if(!e.closed&&n){let t=e.previous;e.previous=n;let r=e.scheduler.now(),i=t&&observationsDiffer(t,n),a=e.directoryReplayAt!==void 0&&r>=e.directoryReplayAt;if(!isMissingObservation(n)&&n.isDirectory()?i?e.directoryReplayAt=r+1e3:a&&(e.directoryReplayAt=void 0):e.directoryReplayAt=void 0,t&&(i||a)){let r={kind:`poll`,resource:e.resource,current:n,previous:t,sequence:++e.sequence,observedAt:e.scheduler.now()};e.subscribers.forEach(i=>{i.rawEmitter(F.CHANGE,e.resource,{current:n,previous:t}),i.publish(r)})}}if(e.running=!1,!e.closed&&e.subscribers.size>0){let n=e.scheduler.now()-t;schedulePoll(e,Math.max(0,e.interval-n))}}function reconfigurePollResource(e){if(e.closed||e.subscribers.size===0)return;let t=Math.min(...[...e.subscribers].map(e=>e.interval)),n=[...e.subscribers].some(e=>e.persistent),r=e.interval!==t;e.interval=t,e.persistent=n,e.timer&&r?(e.scheduler.clearTimeout(e.timer),e.timer=void 0,schedulePoll(e)):e.timer?setTimerPersistence(e):e.running||schedulePoll(e)}function setPollingListener(e,t,n,r,i,a,o){let s=t,c={watchedPath:e,...n,...i},l=H.get(s);l||(l=/* @__PURE__ */ new Map,H.set(s,l));let u=l.get(r);u?!u.previous&&a&&(u.previous=a):(u={resource:s,generation:allocateSharedResourceGeneration(),scheduler:r,subscribers:/* @__PURE__ */ new Set,interval:n.interval,persistent:n.persistent,previous:a,running:!1,closed:!1,sequence:0},l.set(r,u)),u.subscribers.add(c),reconfigurePollResource(u);let d=!1,f,p={resource:s,close:()=>f||(f=(async()=>{if(d)return;if(d=!0,u.subscribers.delete(c),u.subscribers.size>0){reconfigurePollResource(u);return}if(u.closed)return;u.closed=!0,u.timer&&u.scheduler.clearTimeout(u.timer),u.timer=void 0;let e=H.get(s);e?.get(r)===u&&(e.delete(r),e.size===0&&H.delete(s)),u.currentPoll&&await Promise.allSettled([u.currentPoll])})(),f)};if(o.aborted)p.close();else return p}var LifecycleScope=class{state=`OPEN`;generation=0;abortController=new AbortController;tasks=/* @__PURE__ */ new Set;closers=/* @__PURE__ */ new Map;onTaskSettled;onTaskError;constructor(e,t){this.onTaskSettled=e,this.onTaskError=t}isActive(e){return this.state===`OPEN`&&this.generation===e}track(e){let t=Promise.resolve(e).finally(()=>{this.tasks.delete(t),this.onTaskSettled()});return this.tasks.add(t),t.catch(this.onTaskError),t}addCloser(e,t){let n=this.closers.get(e);n?n.push(t):this.closers.set(e,[t])}takeClosers(e){let t=this.closers.get(e)??[];return this.closers.delete(e),t}beginClose(){if(this.state!==`OPEN`)return[];this.state=`CLOSING`,this.generation+=1,this.abortController.abort();let e=[];return this.closers.forEach(t=>{t.forEach(t=>{try{e.push(Promise.resolve(t()))}catch(t){e.push(Promise.reject(t))}})}),this.closers.clear(),e}async drain(){for(;this.tasks.size>0;)await Promise.allSettled([...this.tasks])}finishClose(){this.state=`CLOSED`}};function IGNORE_RECONCILIATION_ERROR(){}function resolveRecursiveCandidate(e,t){if(u.isAbsolute(t))return;let n=u.resolve(e);if(isSameOrInside(n,u.resolve(n,t)))return u.join(e,t)}var ReconciliationQueue=class{queues=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;lifecycle;constructor(e){this.lifecycle=e}enqueue(e,t,n=e){let r=logicalPathKey(e),i=n===!1?void 0:`${r}\0${logicalPathKey(n)}`,a=i?this.pending.get(i):void 0;if(a)return a.work=t,a.replay=!0,a.promise;let o=this.lifecycle.generation,s={promise:Promise.resolve(),work:t,replay:!1},c=(this.queues.get(r)??Promise.resolve()).catch(IGNORE_RECONCILIATION_ERROR).then(async()=>{do{let e=s.work;if(s.replay=!1,!this.lifecycle.isActive(o))return;await e()}while(s.replay)}).finally(()=>{this.queues.get(r)===c&&this.queues.delete(r),i&&this.pending.get(i)===s&&this.pending.delete(i)});this.queues.set(r,c);let l=this.lifecycle.track(c);return s.promise=l,i&&this.pending.set(i,s),l}forgetPending(e){for(let t of this.pending.keys()){let[n,r]=t.split(`\0`,2);e(n,r)&&this.pending.delete(t)}}clear(){this.queues.clear(),this.pending.clear()}};const U=Object.freeze({size:0,mtimeMs:0,ino:0,kind:`other`,initialRecursive:!0});function statKind(e){return e.isSymbolicLink()?`symlink`:e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function sameStatFact(e,t){let n=statIdentity(t);return e?.size===n.size&&e.mtimeMs===n.mtimeMs&&e.ino===n.ino&&e.kind===statKind(t)}function withinWindow(e,t,n){return e?.observedAt!==void 0&&t.observedAt>=e.observedAt&&t.observedAt-e.observedAt<=n}var DirEntry=class{path;items=/* @__PURE__ */ new Set;constructor(e){this.path=e}add(e){e!==`.`&&e!==`..`&&e!==``&&this.items.add(e)}remove(e){return this.items.delete(e)&&this.items.size===0}has(e){return this.items.has(e)}getChildren(){return[...this.items]}dispose(){this.items.clear(),this.path=``}},TreeState=class{watched=/* @__PURE__ */ new Map;observed=/* @__PURE__ */ new Map;symlinkPaths=/* @__PURE__ */ new Map;recursiveRoots=/* @__PURE__ */ new Set;observesNative;constructor(e){this.observesNative=e}getDirectory(e){let t=u.resolve(e),n=logicalPathKey(t),r=this.watched.get(n);return r||(r=new DirEntry(t),this.watched.set(n,r)),r}peekDirectory(e){return this.watched.get(logicalPathKey(u.resolve(e)))}recordObserved(e,t,n,r,i=!1,a=!1){if(!this.observesNative()||!r&&!i&&!a)return;let{size:o,mtimeMs:s,ino:c}=statIdentity(t);this.observed.set(logicalPathKey(e),{size:o,mtimeMs:s,ino:c,kind:statKind(t),transition:n,rawEvent:r?.rawEvent,relativePath:r?.relativePath,observedAt:r?.observedAt,initialRecursive:i})}consumeInitialCreate(e,t,n,r){if(this.observed.get(logicalPathKey(e))?.initialRecursive&&n.rawEvent===`rename`)return this.recordObserved(e,t,`add`,n),r?t.isDirectory()?k.ADD_DIR:k.ADD:!1}markInitialCreate(e){let t=logicalPathKey(e),n=this.observed.get(t);n?n.initialRecursive=!0:this.observed.set(t,{...U})}clearInitialCreate(e){let t=this.observed.get(logicalPathKey(e));t&&(t.initialRecursive=!1)}clearInitialCreates(e){let t=logicalPathKey(e);for(let[e,n]of this.observed)isSameOrInside(t,e)&&n.initialRecursive&&(n.initialRecursive=!1)}replacedSinceObserved(e,t){let n=this.observed.get(logicalPathKey(e)),{ino:r}=statIdentity(t);return n?.kind===`directory`&&t.isDirectory()&&n.ino!==0&&r!==0&&n.ino!==r}changedSinceObserved(e,t){let n=this.observed.get(logicalPathKey(e));return n!==void 0&&n.kind===statKind(t)&&!sameStatFact(n,t)}isDuplicateObservation(e,t,n){let r=this.observed.get(logicalPathKey(e)),i=sameStatFact(r,t),a=i&&r?.transition===`add`&&r?.relativePath===n.relativePath&&r.rawEvent===`rename`&&n.rawEvent===`change`&&withinWindow(r,n,25),o=i&&t.isFile()&&!r?.initialRecursive&&(r?.transition===`add`||n.relativePath===null),s=i&&r?.transition===`change`&&r.relativePath===n.relativePath&&withinWindow(r,n,10)&&r.rawEvent===n.rawEvent,c=o||a||s,l=s?void 0:o?r?.transition:`change`;return this.recordObserved(e,t,l,n),c}dispose(){this.watched.forEach(e=>e.dispose()),this.watched.clear(),this.observed.clear(),this.symlinkPaths.clear(),this.recursiveRoots.clear()}};function isEmptyFile(e){return e!==void 0&&e.isFile()&&statIdentity(e).size===0}function sameChangeStats(e,t){if(e===void 0||t===void 0)return!1;let n=statIdentity(e),r=statIdentity(t);return n.size===r.size&&n.mtimeMs===r.mtimeMs&&n.ino===r.ino}var EventPolicy=class{pendingWrites=/* @__PURE__ */ new Map;pendingUnlinks=/* @__PURE__ */ new Map;pendingChanges=/* @__PURE__ */ new Map;heldAdds=/* @__PURE__ */ new Map;throttled=/* @__PURE__ */ new Map;context;constructor(e){this.context=e}presentPath(e){return w&&(e=u.normalize(e)),this.context.options.cwd?u.relative(this.context.options.cwd,e):e}dropHeldAdd(e){let t=this.heldAdds.get(e);t&&this.context.scheduler.clearTimeout(t.timer),this.heldAdds.delete(e)}dropPendingChange(e){let t=this.pendingChanges.get(e);t?.held&&this.context.scheduler.clearTimeout(t.held.timer),this.pendingChanges.delete(e)}setTimeout(e,t){let n=this.context.scheduler.setTimeout(e,t);return this.context.options.persistent||n.unref(),n}async emit(e,t,n){if(this.context.isClosed())return;let{options:r,scheduler:i}=this.context,a=t,o=logicalPathKey(t),s=this.context.lifecycle.generation,c=this.context.capturePathGeneration();t=this.presentPath(t);let d=[t];n!=null&&d.push(n);let f=this.heldAdds.get(o);if(f){if(e===k.CHANGE){f.path=a,n&&(f.stats=n),isEmptyFile(n)||f.release();return}f.release()}(e===k.UNLINK||e===k.UNLINK_DIR)&&(this.dropPendingChange(o),this.throttled.get(k.CHANGE)?.get(o)?.clear(!1));let p=r.awaitWriteFinish,m=p?this.pendingWrites.get(o):void 0;if(m)m.lastChange=i.now();else{if(r.atomic){if(e===k.UNLINK){let t=this.pendingUnlinks.get(o);t&&i.clearTimeout(t.timer);let n=[e,...d],a=this.setTimeout(()=>{let e=this.pendingUnlinks.get(o);if(!e||e.timer!==a||(this.pendingUnlinks.delete(o),this.context.isClosed()))return;let[t,...n]=e.event;this.context.publish(t,n)},typeof r.atomic==`number`?r.atomic:100);this.pendingUnlinks.set(o,{event:n,timer:a});return}let t=this.pendingUnlinks.get(o);e===k.ADD&&t&&(e=k.CHANGE,i.clearTimeout(t.timer),this.pendingUnlinks.delete(o))}if(p&&(e===k.ADD||e===k.CHANGE)&&this.context.isReady()){let awfEmit=(t,n)=>{this.context.isClosed()||(t?(e=k.ERROR,d[0]=t,this.context.publish(e,d)):n&&(d.length>1?d[1]=n:d.push(n),this.context.publish(e,d)))};this.awaitWriteFinish(t,p.stabilityThreshold,e,awfEmit,o)}else if(e===k.ADD&&isEmptyFile(n)&&this.context.isReady()){let e={path:a,stats:n,release:()=>{if(this.context.scheduler.clearTimeout(e.timer),this.heldAdds.get(o)!==e||(this.heldAdds.delete(o),this.context.isClosed()||!this.context.lifecycle.isActive(s)||!this.context.isPathGenerationActive(o,c)))return;let t=[this.presentPath(e.path)];e.stats&&t.push(e.stats),this.context.publish(k.ADD,t)}};e.timer=this.setTimeout(e.release,10),this.heldAdds.set(o,e)}else{if(e===k.CHANGE){if(!this.throttle(k.CHANGE,a,50,e=>{let t=this.pendingChanges.get(o);this.dropPendingChange(o),e>0&&t?.replay&&this.context.lifecycle.isActive(s)&&this.context.isPathGenerationActive(o,c)&&this.emit(k.CHANGE,t.path,t.stats)})){let e=this.pendingChanges.get(o);e&&!sameChangeStats(e.stats,n)&&(e.path=a,e.stats=n,e.replay=!0,e.held&&!isEmptyFile(n)&&e.held.release());return}let e={path:a,stats:n,replay:!1};if(this.pendingChanges.set(o,e),isEmptyFile(n)){let release=()=>{if(e.held&&this.context.scheduler.clearTimeout(e.held.timer),e.held=void 0,this.pendingChanges.get(o)!==e||this.context.isClosed()||!this.context.lifecycle.isActive(s)||!this.context.isPathGenerationActive(o,c))return;e.replay=!1;let t=[this.presentPath(e.path)];e.stats&&t.push(e.stats),this.context.publish(k.CHANGE,t)};e.held={timer:this.setTimeout(release,10),release};return}}if(r.alwaysStat&&n===void 0&&(e===k.ADD||e===k.ADD_DIR||e===k.CHANGE)){let e=r.cwd?u.join(r.cwd,t):t;try{n=await l(e)}catch(e){this.context.handleError(e)}if(!n||!this.context.lifecycle.isActive(s)||!this.context.isPathGenerationActive(o,c))return;d.push(n)}this.context.publish(e,d)}}}throttle(e,t,n,r){let i=this.throttled.get(e);i||(i=/* @__PURE__ */ new Map,this.throttled.set(e,i));let a=e===`readdir`?t:logicalPathKey(t),o=i.get(a);if(o)return o.count+=1,!1;let s,clear=(e=!0)=>{let t=i.get(a),n=t?.count??0;return i.delete(a),this.context.scheduler.clearTimeout(s),t&&this.context.scheduler.clearTimeout(t.timeoutObject),e&&r&&r(n),n};s=this.setTimeout(clear,n);let c={timeoutObject:s,clear,count:0};return i.set(a,c),c}awaitWriteFinish(e,t,n,r,i){let a=this.context.options.awaitWriteFinish;if(typeof a!=`object`)return;let o=a.pollInterval,s,c=e;this.context.options.cwd&&!u.isAbsolute(e)&&(c=u.join(this.context.options.cwd,e));let d=i??logicalPathKey(c);if(this.pendingWrites.has(d))return;let f=this.context.lifecycle.generation,p={lastChange:this.context.scheduler.now(),cancelWait:()=>(this.pendingWrites.get(d)===p&&this.pendingWrites.delete(d),this.context.scheduler.clearTimeout(s),n)},isCurrent=()=>this.context.lifecycle.isActive(f)&&this.pendingWrites.get(d)===p,inspect=e=>{let n=(async()=>{let n;try{n=await l(c)}catch(e){if(!isCurrent())return;isMissingError(e)?(this.context.remove(u.dirname(c),u.basename(c)),this.pendingWrites.get(d)===p&&p.cancelWait()):(this.pendingWrites.delete(d),r(e));return}if(!isCurrent())return;let i=this.context.scheduler.now();e&&n.size!==e.size&&(p.lastChange=i),i-p.lastChange>=t?(this.pendingWrites.delete(d),r(void 0,n)):s=this.setTimeout(()=>inspect(n),o)})();this.context.lifecycle.track(n)};this.pendingWrites.set(d,p),s=this.setTimeout(inspect,o)}cancelPath(e){let t=logicalPathKey(e),n=this.pendingUnlinks.get(t);n&&(this.context.scheduler.clearTimeout(n.timer),this.pendingUnlinks.delete(t)),this.pendingWrites.get(t)?.cancelWait(),this.dropPendingChange(t),this.dropHeldAdd(t),[`watch`,`add`,`remove`,`change`].forEach(e=>{this.throttled.get(e)?.get(t)?.clear(!1)});let r=this.throttled.get(`readdir`);r?.get(t)?.clear(!1),r?.get(`${logicalPathKey(u.dirname(t))}\0${u.basename(t)}`)?.clear(!1)}cancelWhere(e){[.../* @__PURE__ */ new Set([...this.pendingUnlinks.keys(),...this.pendingWrites.keys(),...this.pendingChanges.keys(),...this.heldAdds.keys()])].filter(e).forEach(e=>this.cancelPath(e)),this.throttled.forEach((t,n)=>{[...t.keys()].filter(t=>e(n===`readdir`?t.split(`\0`,1)[0]:t)).forEach(e=>t.get(e)?.clear(!1))})}close(){this.pendingWrites.forEach(e=>e.cancelWait()),this.pendingUnlinks.forEach(({timer:e})=>this.context.scheduler.clearTimeout(e)),this.pendingUnlinks.clear(),this.pendingChanges.forEach(({held:e})=>this.context.scheduler.clearTimeout(e?.timer)),this.pendingChanges.clear(),this.heldAdds.forEach(({timer:e})=>this.context.scheduler.clearTimeout(e)),this.heldAdds.clear(),this.throttled.forEach(e=>{e.forEach(e=>e.clear(!1))}),this.throttled.clear()}};const W=k,G=1024,K=Object.freeze({});function recoveryTrigger(e){return{kind:`native`,resource:e,rawEvent:W.CHANGE,relativePath:null,sequence:2**53-1,observedAt:backendNow()}}function sameMappedFileSnapshot(e,t){return e===!1||t===!1?e===t:e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.ctimeMs===t.ctimeMs&&e.ino===t.ino&&e.mode===t.mode}var ReplayBuffer=class{entries=[];overflow;limit;constructor(e){this.limit=e}get overflowed(){return this.overflow!==void 0}push(e){this.entries.length<this.limit&&!this.overflowed?this.entries.push(e):this.overflow=e}clear(){this.entries.length=0,this.overflow=void 0}};function consumeDirectoryStream(e,t){let n=[];return e.on(`data`,e=>{let r;try{r=t(e)}catch(e){r=Promise.reject(e)}r&&n.push(Promise.resolve(r))}),new Promise(t=>{e.once(`end`,()=>t({complete:!0})),e.once(`close`,()=>t({complete:!1})),e.once(W.ERROR,e=>t({complete:!1,error:e}))}).then(async({complete:e,error:t})=>{let r=(await Promise.allSettled(n)).filter(e=>e.status===`rejected`).map(e=>e.reason);return{complete:e&&r.length===0,error:t,failures:r}})}const q=new Set(`3dm 3ds 3g2 3gp 7z a aac adp afdesign afphoto afpub ai aif aiff alz ape apk appimage ar arj asf au avi bak baml bh bin bk bmp btif bz2 bzip2 cab caf cgm class cmx cpio cr2 cur dat dcm deb dex djvu dll dmg dng doc docm docx dot dotm dra ds_store dsk dts dtshd dvb dwg dxf ecelp4800 ecelp7470 ecelp9600 egg eol eot epub exe f4v fbs fh fla flac flatpak fli flv fpx fst fvt g3 gh gif graffle gz gzip h261 h263 h264 icns ico ief img ipa iso jar jpeg jpg jpgv jpm jxr key ktx lha lib lvp lz lzh lzma lzo m3u m4a m4v mar mdi mht mid midi mj2 mka mkv mmr mng mobi mov movie mp3 mp4 mp4a mpeg mpg mpga mxu nef npx numbers nupkg o odp ods odt oga ogg ogv otf ott pages pbm pcx pdb pdf pea pgm pic png pnm pot potm potx ppa ppam ppm pps ppsm ppsx ppt pptm pptx psd pya pyc pyo pyv qt rar ras raw resources rgb rip rlc rmf rmvb rpm rtf rz s3m s7z scpt sgi shar snap sil sketch slk smv snk so stl suo sub swf tar tbz tbz2 tga tgz thmx tif tiff tlz ttc ttf txz udf uvh uvi uvm uvp uvs uvu viv vob war wav wax wbmp wdp weba webm webp whl wim wm wma wmv wmx woff woff2 wrm wvx xbm xif xla xlam xls xlsb xlsm xlsx xlt xltm xltx xm xmind xpi xpm xwd xz z zip zipx`.split(` `));function isBinaryPath(e){return q.has(u.extname(e).slice(1).toLowerCase())}var ObservationEngine=class{fsw;reportError;constructor(e){this.fsw=e,this.reportError=t=>e.handleError(t)}subscribePath(e,t,n,r=!1,i=e){let a=this.fsw.options,o=u.basename(e),s=u.resolve(e),c={persistent:a.persistent},l=this.fsw.lifecycle.generation,d=!0,trackedListener=(e,n,r)=>{if(d&&this.fsw.lifecycle.isActive(l))return t(e,n,r)},publish=t=>{this.reconcileBackendTrigger(e,r,t,e=>trackedListener(e,t.kind===`poll`&&!isMissingObservation(t.current)?t.current:void 0,t),()=>d&&this.fsw.lifecycle.isActive(l),!0,i)},f,p=0,subscribeNative=()=>setFsWatchListener(e,s,c,{publish:e=>{p=0,publish(e)},errHandler:this.reportError,rawEmitter:(...e)=>this.fsw.emitRaw(...e),failure:()=>{d&&this.fsw.lifecycle.isActive(l)&&(f=p++<3?subscribeNative():void 0,publish(recoveryTrigger(s)))}},this.fsw.lifecycle.abortController.signal);if(f=a.backendCapabilities.polling?setPollingListener(e,s,{interval:a.pollingInterval!==a.pollingBinaryInterval&&isBinaryPath(o)?a.pollingBinaryInterval:a.pollingInterval,persistent:a.persistent},this.fsw.scheduler,{publish,errHandler:this.reportError,rawEmitter:(...e)=>this.fsw.emitRaw(...e)},n,this.fsw.lifecycle.abortController.signal):subscribeNative(),f)return()=>{if(d)return d=!1,f?.close()}}subscribeMappedFile(e,t,n,r,i=T){if(this.fsw.options.backendCapabilities.polling)return;let a=u.dirname(t),o=logicalPathKey(t),s=u.dirname(e),c=this.fsw.lifecycle.generation,l=!0,d=i,f=!1,p,m,h,isActive=()=>l&&this.fsw.lifecycle.isActive(c)&&this.isHelperActive(n,e),matchesTarget=e=>{if(e===null)return!0;let t=logicalPathKey(u.isAbsolute(e)?e:u.resolve(a,e));return w?t.toLowerCase()===o.toLowerCase():t===o},retireExact=()=>{d&&(d=!1,h&&h.close())},publish=(i,o)=>{if(o.kind!==`native`||!matchesTarget(o.relativePath)||!isActive())return;let c=i===`directory`&&f;i===`directory`?(f=!1,retireExact()):m&&(f=!0,retireExact()),this.reconcileBackendTrigger(a,!0,o,async()=>{if(c&&p!==void 0){let e=await this.mappedFileSnapshot(t);if(e!==void 0&&sameMappedFileSnapshot(p,e))return}await this.reconcileNativeTrigger(s,n,o,e,r-1,K),i===`exact`&&(p=await this.mappedFileSnapshot(t))},isActive,!1,e)},g=0,handlers=t=>({publish:e=>{t===`directory`&&(g=0),publish(t,e)},errHandler:this.reportError,rawEmitter:(n,r)=>{(t===`directory`||d)&&matchesTarget(r)&&isActive()&&this.fsw.emitRaw(n,r,{watchedPath:e})},failure:()=>{t===`exact`?(h=void 0,d=!1):(m=void 0,isActive()&&(g++<3&&(m=subscribe(t)),publish(t,recoveryTrigger(u.resolve(a)))))}}),subscribe=e=>{let n=e===`directory`?a:t;return setFsWatchListener(n,u.resolve(n),{persistent:this.fsw.options.persistent},handlers(e),this.fsw.lifecycle.abortController.signal)};if(m=subscribe(`directory`),h=i?subscribe(`exact`):void 0,h||(d=!1),m||h)return async()=>{if(!l)return;l=!1;let e=[m,h].filter(e=>e!==void 0);await Promise.allSettled(e.map(e=>e.close()))}}async mappedFileSnapshot(e){try{return await i(e)}catch(e){if(isMissingError(e))return!1;this.reportError(e);return}}watchSymlinkDeletion(e,t=!1){if(!T&&!t||this.fsw.options.backendCapabilities.polling)return;let n=this.fsw,r=n.lifecycle.generation,a=u.dirname(e),o=u.basename(e),s=!0,c,schedule=()=>{c=n.scheduler.setTimeout(()=>{c=void 0,(async()=>{try{await i(e)}catch(e){if(!s||!n.lifecycle.isActive(r))return;if(isMissingError(e)){s=!1,n.removePath(a,o);return}this.reportError(e)}s&&n.lifecycle.isActive(r)&&schedule()})()},n.options.pollingInterval),n.options.persistent||c.unref()};return schedule(),()=>{s&&(s=!1,n.scheduler.clearTimeout(c),c=void 0)}}reconcileBackendTrigger(e,t,n,r,i=()=>!0,a=!0,o=e){let s=e;if(t&&n.kind===`native`&&n.relativePath!==null){let t=resolveRecursiveCandidate(e,n.relativePath);if(!t)return this.reportError(/* @__PURE__ */ Error(`Watcher reported a path outside its root: ${n.relativePath}`)),Promise.resolve();s=t}if(!i()||this.fsw.isUnwatched(s))return Promise.resolve();let c=logicalPathKey(o),l=logicalPathKey(s);return this.fsw.reconciliation.enqueue(c,async()=>{i()&&!this.fsw.isUnwatched(l)&&await r(s)},a?l:!1)}handleFile(e,t,n,r=!0,a,o=!1,s=!1){if(this.fsw.closed)return;let c=u.dirname(e),d=u.basename(e),f=this.fsw.tree.getDirectory(c),p=t;if(f.has(d))return;let m=this.fsw.capturePathGeneration(),isActive=()=>this.fsw.isPathGenerationActive(e,m),listener=async(t,n)=>{if(!n||n.mtimeMs===0)try{let t=p.isSymbolicLink()&&!this.fsw.options.followSymlinks?await i(e):await l(e);if(!isActive())return;let n=t.atimeMs,r=t.mtimeMs;(!n||n<=r||r!==p.mtimeMs)&&this.fsw.emitEvent(W.CHANGE,e,t),this.fsw.tree.recordObserved(e,t,`change`),p=t}catch(e){if(!isActive())return;isMissingError(e)?this.fsw.removePath(c,d):this.reportError(e)}else if(f.has(d)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==p.mtimeMs)&&this.fsw.emitEvent(W.CHANGE,e,n),this.fsw.tree.recordObserved(e,n,`change`),p=n}},h=r&&this.fsw.options.backendCapabilities.polling?this.subscribePath(e,listener,t):void 0;return f.add(d),this.fsw.tree.recordObserved(e,t,`add`,a,o,s),!(n&&this.fsw.options.ignoreInitial)&&!this.fsw.isIgnored(e,t)&&this.fsw.emitEvent(W.ADD,e,t),h}async handleSymlink(e,t,n,r,i,a){if(this.fsw.closed||a&&!this.isHelperActive(a,n))return;let o=logicalPathKey(e.fullPath),c=this.fsw.tree.getDirectory(t);if(!this.fsw.options.followSymlinks){let t;try{t=await s(n)}catch(e){return isMissingError(e)||this.reportError(e),!0}return this.fsw.closed||a&&!this.isHelperActive(a,n)||(c.has(r)?this.fsw.tree.symlinkPaths.get(o)!==t&&(this.fsw.tree.symlinkPaths.set(o,t),this.fsw.emitEvent(W.CHANGE,n,e.stats)):(c.add(r),this.fsw.tree.symlinkPaths.set(o,t),this.fsw.tree.recordObserved(n,e.stats,`add`,a?.observationTrigger,i&&!!a?.recursiveRoot),i&&this.fsw.options.ignoreInitial||this.fsw.emitEvent(W.ADD,n,e.stats))),!0}if(this.fsw.tree.symlinkPaths.has(o))return!0;this.fsw.tree.symlinkPaths.set(o,!0)}readDirectory(e,t,n,r,a,o){if(!this.isHelperActive(n,e))return;e=u.join(e,``);let s=logicalPathKey(e),c=this.fsw.tree.getDirectory(n.watchPath),d=/* @__PURE__ */ new Set,f=this.fsw.createScanStream(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(f)return consumeDirectoryStream(f,i=>{if(!this.isHelperActive(n,e))return;let s=i.stats;if(!s)return;let l=i.path,f=u.join(e,l);if(!this.isHelperActive(n,f))return;d.add(l);let p=l===r||!r&&!c.has(l);if(r===void 0&&!s.isSymbolicLink()&&!s.isDirectory()){if(!p)return;f=u.join(a,u.relative(a,f));let e=this.handleFile(f,s,t,!n.recursiveRoot,n.observationTrigger,t&&!!n.recursiveRoot);e&&this.fsw.addPathCloser(f,e)}else return(async()=>{s.isSymbolicLink()&&await this.handleSymlink(i,e,f,l,t,n)||this.isHelperActive(n,f)&&p&&(f=u.join(a,u.relative(a,f)),await this.addPathOnce(f,t,n,o+1))})()}).then(async({complete:t,error:a,failures:f})=>{if(f.forEach(this.reportError),a){if(isMissingError(a)&&this.isHelperActive(n,e)){let t=r?u.join(e,r):e,a=!1,d=!1;try{let e=r?await i(t):await l(t);d=!r&&!e.isDirectory()}catch(e){isMissingError(e)?a=!0:this.reportError(e)}r?a&&c.has(r)&&this.fsw.removePath(e,r):(a||d)&&this.fsw.tree.watched.has(s)&&(this.fsw.removePath(u.dirname(e),u.basename(e),!0),d&&await this.addPathOnce(e,!1,n,o))}else this.reportError(a)}t&&this.isHelperActive(n,e)&&await Promise.all(c.getChildren().filter(e=>!d.has(e)).map(t=>this.removeIfMissing(n,e,t,c)))})}async removeIfMissing(e,t,n,r){let a=u.join(t,n);if(this.isHelperActive(e,a)){try{await i(a);return}catch(e){if(!isMissingError(e))return}this.isHelperActive(e,a)&&r.has(n)&&this.fsw.removePath(t,n)}}scanRecursiveTree(e,t,n,r,i){if(!this.isHelperActive(n,e))return;let a=this.fsw,o=a.options.depth,s=o===void 0?void 0:o-r,c=a.createScanStream(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>!e.stats?.isSymbolicLink()&&n.filterDir(e),depth:s});if(c)return consumeDirectoryStream(c,o=>{if(!this.isHelperActive(n,e))return;let s=o.stats;if(!s)return;let c=u.join(e,o.path);if(!this.isHelperActive(n,c))return;let l=u.dirname(c),d=u.basename(c);if(i&&(i.seen.add(logicalPathKey(c)),s.isDirectory()&&i.directories.push(c)),s.isSymbolicLink())return(async()=>{if(await this.handleSymlink(o,l,c,d,t,n)||!this.isHelperActive(n,c))return;let e=r+o.path.split(/[/\\]/).length;await this.addPathOnce(c,t,n,e)})();let f=a.tree.getDirectory(l);if(f.has(d)){i&&s.isFile()&&a.tree.changedSinceObserved(c,s)&&(a.tree.recordObserved(c,s,`change`,void 0,!1,!0),a.emitEvent(W.CHANGE,c,s));return}f.add(d);let p=s.isDirectory();p&&a.tree.getDirectory(c),a.tree.recordObserved(c,s,`add`,n.observationTrigger,t),t&&a.options.ignoreInitial||a.emitEvent(p?W.ADD_DIR:W.ADD,c,s)}).then(e=>{e.error&&this.reportError(e.error),e.failures.forEach(this.reportError),i&&(i.complete=e.complete)})}async rescanRecursiveTree(e,t,n){let r={seen:/* @__PURE__ */ new Set,directories:[e],complete:!1};if(await this.scanRecursiveTree(e,!1,t,n,r),!r.complete||!this.isHelperActive(t,e))return;let i=[];for(let e of r.directories)for(let t of this.fsw.tree.peekDirectory(e)?.getChildren()??[]){let n=u.join(e,t);r.seen.has(logicalPathKey(n))||i.push(n)}i.sort((e,t)=>e.length-t.length);for(let e of i){let n=this.fsw.tree.peekDirectory(u.dirname(e));n?.has(u.basename(e))&&await this.removeIfMissing(t,u.dirname(e),u.basename(e),n)}}isHelperActive(e,t=e.watchPath){return this.fsw.isPathGenerationActive(t,e.pathGeneration)}candidateDepth(e,t){let n=u.relative(e,t);return n?n.split(u.sep).length:0}candidateIgnored(e,t,n){let r=u.relative(e,t),i=e;if(this.fsw.isIgnored(i))return!0;if(r){let e=r.split(u.sep);for(let t=0;t<e.length-1;t++)if(i=u.join(i,e[t]),this.fsw.isIgnored(i))return!0}return this.fsw.isIgnored(t,n)}async highestMissingPath(e,t){let n=t,r=u.dirname(t);for(;;){try{return await i(r),n}catch(e){if(!isMissingError(e))return this.reportError(e),n}if(n=r,r===e)return n;let t=u.dirname(r);if(t===r)return n;r=t}}async reconcileNativeTrigger(e,t,n,r,a=0,o){let l=this.fsw;if(!this.isHelperActive(t,e))return;let d,helper=()=>d??=t.withObservation(n),f=r??(n.relativePath===null?e:resolveRecursiveCandidate(e,n.relativePath));if(!f){this.reportError(/* @__PURE__ */ Error(`Native watcher reported a path outside its root: ${n.relativePath}`));return}let p=a+this.candidateDepth(e,f),m=l.options.depth;if(m!==void 0&&p>m+1||this.candidateIgnored(e,f))return;let h;try{h=await i(f)}catch(t){if(!isMissingError(t)){if(this.reportError(t),o)return;let n=f===e?e:u.dirname(f),r=Math.max(0,a+this.candidateDepth(e,n));await this.readDirectory(n,!1,helper().fork(n),void 0,n,r);return}if(l.closed)return;let n=f===e?e:await this.highestMissingPath(e,f);if(l.closed)return;if(n===e){l.removePath(u.dirname(e),u.basename(e),!0),o?.onRootMissing?.();return}let r=u.dirname(n),i=u.basename(n);l.tree.getDirectory(r).has(i)?l.removePath(r,i):o||await this.readDirectory(r,!1,helper().fork(r),void 0,r,Math.max(0,a+this.candidateDepth(e,r)));return}if(!this.isHelperActive(t,f)||this.candidateIgnored(e,f,h))return;if(!h.isDirectory()&&!(h.isSymbolicLink()&&l.options.followSymlinks)){let e=l.tree.consumeInitialCreate(f,h,n,l.options.ignoreInitial);if(e!==void 0){e&&l.emitEvent(e,f,h);return}}if(f===e){if(!h.isDirectory())return;t.recursiveRoot===e?await this.rescanRecursiveTree(e,helper(),a):await this.readDirectory(e,!1,helper(),void 0,e,a);return}let g=u.dirname(f),_=u.basename(f),v=l.tree.getDirectory(g),y=v.has(_);if(h.isSymbolicLink()){if(!l.options.followSymlinks){let e=!0;try{e=await s(f)}catch{}y||v.add(_),l.tree.symlinkPaths.set(logicalPathKey(f),e),y&&l.tree.isDuplicateObservation(f,h,n)||l.emitEvent(y?W.CHANGE:W.ADD,f,h),y||l.tree.recordObserved(f,h,`add`,n);return}let e=logicalPathKey(f),r=l.tree.symlinkPaths.get(e),i;try{i=await c(f)}catch(e){if(!isMissingError(e)){this.reportError(e);return}}if(y&&typeof r==`string`&&(i===void 0||logicalPathKey(r)!==logicalPathKey(i))){let n=l.tree.observed.get(e)?.kind;if(l.removePath(g,_,n===`directory`),!i||!this.isHelperActive(t,f))return;let r=helper().fork(f);r.recursiveRoot=void 0,await this.addPathOnce(f,!1,r,p);return}let a=l.tree.consumeInitialCreate(f,h,n,l.options.ignoreInitial);if(a!==void 0){if(a){l.closePath(f,!0);let e=helper().fork(f);e.recursiveRoot=void 0,await this.addPathOnce(f,!1,e,p)}return}if(y)l.emitEvent(W.CHANGE,f,h);else{let e=helper().fork(f);e.recursiveRoot=void 0,await this.addPathOnce(f,!1,e,p)}}else if(h.isDirectory()){let e=helper().fork(f),t=l.tree.consumeInitialCreate(f,h,n,l.options.ignoreInitial);if(t!==void 0){t&&(l.closePath(f,!0),await this.addPathOnce(f,!1,e,p));return}y?l.tree.replacedSinceObserved(f,h)?(l.removePath(g,_,!0),await this.addPathOnce(f,!1,e,p)):(m===void 0||p<=m)&&await this.readDirectory(f,!1,e,void 0,f,p):await this.addPathOnce(f,!1,e,p)}else y?l.tree.isDuplicateObservation(f,h,n)||l.emitEvent(W.CHANGE,f,h):await this.addPathOnce(f,!1,helper(),p)}watchRootParent(e,t){if(!this.fsw.options.backendCapabilities.perDirectory||!w)return;let n=u.dirname(e);if(u.resolve(n)===u.resolve(e))return;let r=u.normalize(u.toNamespacedPath(u.resolve(n))).toLowerCase(),a=u.basename(e).toLowerCase(),o=this.fsw.lifecycle.generation,s=!0,matchesRoot=e=>{if(e===null)return!0;let t=u.isAbsolute(e)?u.resolve(e):u.resolve(n,e);return u.normalize(u.toNamespacedPath(u.dirname(t))).toLowerCase()===r&&u.basename(t).toLowerCase()===a},isActive=()=>s&&this.fsw.lifecycle.isActive(o)&&this.isHelperActive(t,e),publish=r=>{r.kind===`native`&&matchesRoot(r.relativePath)&&isActive()&&this.reconcileBackendTrigger(e,!1,r,async()=>{let r;try{r=await i(e)}catch(t){isMissingError(t)?this.fsw.removePath(n,u.basename(e),!0):this.reportError(t);return}isActive()&&(r.isDirectory()?await this.readDirectory(e,!1,t,void 0,e,0):(this.fsw.removePath(n,u.basename(e),!0),await this.addPathOnce(e,!1,t,0)))},isActive)},c=setFsWatchListener(n,u.resolve(n),{persistent:this.fsw.options.persistent},{publish,errHandler:this.reportError,rawEmitter:(e,t,n)=>{matchesRoot(t)&&this.fsw.emitRaw(e,t,n)}},this.fsw.lifecycle.abortController.signal);if(c)return()=>{if(s)return s=!1,c.close()}}async watchRecursiveDirectory(e,t,n,r){let a=this.fsw,o=a.lifecycle.generation,s=logicalPathKey(e),c=new ReplayBuffer(G),l=[],d=`scanning`,f,p=!1,m,h,scopeActive=(t=e)=>a.lifecycle.isActive(o)&&a.isPathGenerationActive(t,r.pathGeneration),acceptsTrigger=(t=e)=>d!==`recovering`&&d!==`closed`&&scopeActive(t),establishFallback=async t=>{if(!scopeActive())return;r.recursiveRoot=void 0,r.recursiveDisabled=!0;let o;try{o=await i(e)}catch(n){isMissingError(n)?a.removePath(u.dirname(e),u.basename(e),!0):this.reportError(n),this.reportError(t);return}let s=await this.handleDirectory(e,o,!1,n,void 0,r);scopeActive()?(s&&l.push(s),await this.subscribeTrackedDirectories(e,r,n),this.reportError(t)):s&&await s()},handleFailure=t=>{if(!acceptsTrigger())return;let n=d!==`live`;d=`recovering`,a.tree.recursiveRoots.delete(s),f=t,p=!0,n||(m=a.reconciliation.enqueue(e,()=>establishFallback(t),!1))},processTrigger=t=>{if(!acceptsTrigger())return;if(d!==`live`){c.push(t);return}let n=t.relativePath===null?e:resolveRecursiveCandidate(e,t.relativePath)??e;this.reconcileBackendTrigger(e,!0,t,()=>acceptsTrigger()?this.reconcileNativeTrigger(e,r,t):void 0,()=>acceptsTrigger(n))},g=subscribeRecursiveNative(e,a.options.persistent,{publish:processTrigger,failure:handleFailure,rawEmitter:(...e)=>a.emitRaw(...e)},a.lifecycle.abortController.signal);if(g.kind===`unsupported`)return!1;if(g.kind===`failed`)throw g.error;h=g.subscription,a.tree.recursiveRoots.add(s),r.recursiveRoot=e;let close=async()=>{d!==`closed`&&(d=`closed`,a.tree.recursiveRoots.delete(s),c.clear(),await h?.close(),m&&await Promise.allSettled([m]),await Promise.allSettled(l.map(e=>e())))};try{if(await this.scanRecursiveTree(e,t,r,n),!p){d=`replaying`;let t=0;for(;acceptsTrigger();){if(c.overflowed){c.clear(),t=0;let n={kind:`native`,resource:h.resource,rawEvent:W.CHANGE,relativePath:null,sequence:2**53-1,observedAt:backendNow()};await this.reconcileBackendTrigger(e,!0,n,()=>this.reconcileNativeTrigger(e,r,n),()=>acceptsTrigger(),!1);continue}if(t>=c.entries.length)break;let n=c.entries[t++];if(n.rawEvent===`rename`&&n.relativePath!==null){let t=resolveRecursiveCandidate(e,n.relativePath);t&&t!==e&&a.tree.getDirectory(u.dirname(t)).has(u.basename(t))&&a.tree.markInitialCreate(t)}await this.reconcileBackendTrigger(e,!0,n,()=>this.reconcileNativeTrigger(e,r,n),()=>acceptsTrigger(),!1)}d!==`recovering`&&(d=`live`)}p&&(c.clear(),await establishFallback(f)),c.clear(),a.tree.clearInitialCreates(e)}catch(e){throw await close(),e}if(!scopeActive())await close();else return close}async subscribeTrackedDirectories(e,t,n){let r=this.fsw,i=u.resolve(e),needsSubscription=e=>{let n=logicalPathKey(e);return this.isHelperActive(t,e)&&!r.lifecycle.closers.has(n)&&!r.tree.symlinkPaths.has(n)&&(r.tree.peekDirectory(u.dirname(e))?.has(u.basename(e))??!1)},a=[...r.tree.watched.values()].filter(e=>isStrictlyInside(i,e.path)).map(t=>u.join(e,u.relative(i,t.path))).filter(needsSubscription).sort((e,t)=>e.length-t.length),o=0,subscribeNext=async()=>{for(;o<a.length;){let r=a[o++];needsSubscription(r)&&await this.addPathOnce(r,!1,t,n+this.candidateDepth(e,r))}},s=Math.min(16,a.length);await Promise.all(Array.from({length:s},subscribeNext))}async handleDirectory(e,t,n,r,a,o){if(!this.isHelperActive(o,e))return;if(a)this.fsw.tree.getDirectory(e);else{let r=this.fsw.tree.getDirectory(u.dirname(e)),i=r.has(u.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&this.fsw.emitEvent(W.ADD_DIR,e,t),r.add(u.basename(e)),this.fsw.tree.getDirectory(e),this.fsw.tree.recordObserved(e,t,i?void 0:`add`,o.observationTrigger,n&&!!o.recursiveRoot,!0)}let closer,s=this.fsw.options.depth;if(s==null||r<=s){if(this.fsw.options.backendCapabilities.recursive&&r===0&&!a&&!o.recursiveRoot&&!o.recursiveDisabled){let t=await this.watchRecursiveDirectory(e,n,r,o);if(t!==!1)return t}if(o.recursiveRoot){a||await this.scanRecursiveTree(e,n,o,r);return}let s=new ReplayBuffer(G),c=/* @__PURE__ */ new Set,d=!a,f=!0,p=T&&!a,m=a?u.join(e,a):void 0,rewatchTarget=()=>{m&&f&&this.isHelperActive(o,m)&&this.fsw.rewatchMissingPath(m)},removeObserved=e=>{a?(this.fsw.tree.getDirectory(e).has(a)&&this.fsw.removePath(e,a),rewatchTarget()):this.fsw.removePath(u.dirname(e),u.basename(e),!0)},observeDirectory=async(t,n,s)=>{if(f&&this.isHelperActive(o,t)){if(this.fsw.options.backendCapabilities.polling&&!n)removeObserved(t);else{if(s.kind===`native`){let e;try{let n=await i(t);e=n.isSymbolicLink()&&this.fsw.options.followSymlinks?await l(t):n}catch(e){isMissingError(e)?removeObserved(t):this.reportError(e);return}if(!e.isDirectory()){removeObserved(t),a||await this.addPathOnce(t,!1,o,r);return}}await this.readDirectory(t,!1,o,a,e,r)}}},reconcile=(t,n,i)=>{if(f&&this.isHelperActive(o,t)){if(d)s.push({path:t,stats:n,trigger:i});else return i.kind===`native`&&!a?p?(p=!1,(async()=>{await this.reconcileNativeTrigger(e,o,i,t,r),await observeDirectory(e,void 0,i)})()):this.reconcileNativeTrigger(e,o,i,t,r):i.kind===`native`&&a&&(t===e||(w?u.basename(t).toLowerCase()===a.toLowerCase():u.basename(t)===a))?this.reconcileNativeTrigger(e,o,i,m,r,{onRootMissing:rewatchTarget}):observeDirectory(e,n,i)}},h=r===0&&!a?this.watchRootParent(e,o):void 0;if(closer=this.subscribePath(e,reconcile,t.isDirectory()?t:void 0,!0,a?u.join(e,a):e),a&&m&&closer){let t=recoveryTrigger(u.resolve(e));await this.fsw.reconciliation.enqueue(m,async()=>{this.fsw.tree.getDirectory(e).has(a)||await reconcile(m,void 0,t)},m)}if(!a){await this.readDirectory(e,n,o,a,e,r);let t=0;for(;!this.fsw.closed;){if(s.overflow){let n=s.overflow;s.clear(),t=0,await observeDirectory(e,n.stats,n.trigger);continue}if(t>=s.entries.length)break;let n=s.entries[t++];n.trigger.kind===`native`&&n.trigger.rawEvent===`rename`&&n.path!==e&&this.fsw.tree.getDirectory(u.dirname(n.path)).has(u.basename(n.path))&&(this.fsw.tree.markInitialCreate(n.path),c.add(n.path)),await this.reconcileBackendTrigger(e,!0,n.trigger,()=>n.trigger.kind===`native`&&!a?this.reconcileNativeTrigger(e,o,n.trigger,n.path,r):observeDirectory(e,n.stats,n.trigger),()=>f&&this.isHelperActive(o,n.path),!1)}s.clear(),c.forEach(e=>this.fsw.tree.clearInitialCreate(e)),d=!1}if(!this.isHelperActive(o,e)){f=!1,closer&&await closer(),h&&await h();return}if(closer||h){let e=[closer,h].filter(e=>e!==void 0);closer=async()=>{f&&(f=!1,s.clear(),await Promise.allSettled(e.map(e=>e())))}}}return closer}async addRoot(e,t,n,r){let i=e,a=r,o=this.fsw.lifecycle.generation;for(;this.fsw.lifecycle.isActive(o);){if(await this.addPathOnce(i,t,void 0,0,a,n)===`complete`)return;let e=u.dirname(i);if(e===i)return;a=u.basename(i),i=e}}async addPathOnce(e,t,n,r,a,o){if(this.fsw.isIgnored(e)||this.fsw.closed)return`complete`;let d=n?n.fork(e):this.fsw.createHelper(e);if(!n&&o!==void 0&&(d.pathGeneration=o),!this.isHelperActive(d))return`complete`;try{let o=await i(d.watchPath);if(!this.isHelperActive(d)||this.fsw.isIgnored(d.watchPath,o))return`complete`;let f=this.fsw.options.followSymlinks,p=o.isSymbolicLink(),m=p&&f?await l(d.watchPath):o,h=p&&f?await c(e):void 0,closer;if(m.isDirectory()){let n=logicalPathKey(e),i=f?await c(e):e,o=h??e,s=logicalPathKey(i);if(!this.isHelperActive(d))return`complete`;if(p&&d.realpathAncestry.has(s))return this.fsw.tree.getDirectory(u.dirname(d.watchPath)).add(u.basename(d.watchPath)),this.fsw.tree.getDirectory(d.watchPath),this.fsw.tree.symlinkPaths.set(n,o),this.fsw.tree.recordObserved(d.watchPath,m,`add`,d.observationTrigger,t&&!!d.recursiveRoot),t&&this.fsw.options.ignoreInitial||this.fsw.emitEvent(W.ADD_DIR,d.watchPath,m),`complete`;if(d.realpathAncestry.add(s),d.recursiveRoot&&p&&(d.recursiveRoot=void 0),p&&(d.recursiveDisabled=!0),closer=await this.handleDirectory(d.watchPath,m,t,r,a,d),!this.isHelperActive(d))return closer&&await closer(),`complete`;if(a&&!closer)return`watch-parent`;p&&this.fsw.tree.symlinkPaths.set(n,o)}else if(p&&!f){let i=await s(e),a=!this.fsw.options.backendCapabilities.polling&&!d.recursiveRoot&&!n,o=this.handleFile(d.watchPath,m,t,!d.recursiveRoot,d.observationTrigger,t&&!!d.recursiveRoot,a);if(d.recursiveRoot)return this.fsw.tree.symlinkPaths.set(logicalPathKey(e),i),`complete`;let c=u.dirname(d.watchPath),f=await l(c),p=this.fsw.createHelper(c);p.pathGeneration=d.pathGeneration;let h=await this.handleDirectory(c,f,t,r,u.basename(d.watchPath),p),g=this.watchSymlinkDeletion(d.watchPath);if(!this.isHelperActive(d))return o&&await o(),h&&await h(),g&&g(),`complete`;closer=async()=>{await Promise.allSettled([o,h,g].filter(e=>e!==void 0).map(e=>e()))},this.fsw.tree.symlinkPaths.set(logicalPathKey(e),i)}else{h&&this.fsw.tree.symlinkPaths.set(logicalPathKey(e),h);let i=!this.fsw.options.backendCapabilities.polling&&!d.recursiveRoot&&!n,a=this.handleFile(d.watchPath,m,t,!d.recursiveRoot,d.observationTrigger,t&&!!d.recursiveRoot,i),o=h??(i?d.watchPath:void 0),s=o?this.subscribeMappedFile(d.watchPath,o,d,r,T&&m.isFile()):void 0,c;if(i&&h){let e=u.dirname(d.watchPath),n=await l(e),i=this.fsw.createHelper(e);i.pathGeneration=d.pathGeneration,c=await this.handleDirectory(e,n,t,r,u.basename(d.watchPath),i)}let f=[a,s,c].filter(e=>e!==void 0);closer=f.length===0?void 0:async()=>{await Promise.allSettled(f.map(e=>e()))}}return this.isHelperActive(d)?(closer&&this.fsw.addPathCloser(a?u.join(e,a):e,closer),`complete`):(closer&&await closer(),`complete`)}catch(e){return this.isHelperActive(d)?(this.fsw.handleError(e),`watch-parent`):`complete`}}};const J=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Y=/* @__PURE__ */ new Set([`auto`,`native`,`native-recursive`,`polling`]),X=Object.freeze({stabilityThreshold:2e3,pollInterval:100});function*ancestorKeys(e){let t=u.resolve(e);for(let e=u.dirname(t);e!==t;e=u.dirname(e))yield logicalPathKey(e),t=e}function arrify(e){return Array.isArray(e)?e:[e]}function unifyPaths(e){let t=arrify(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(normalizePath)}function getAbsolutePath(e,t){return u.isAbsolute(e)?e:u.join(t,e)}function validatePositiveFinite(e,t){if(!Number.isFinite(t)||t<=0)throw TypeError(`${e} must be a finite number greater than zero`)}function validateNonNegativeFinite(e,t){if(!Number.isFinite(t)||t<0)throw TypeError(`${e} must be a finite non-negative number`)}function validateOptions(e){if(validatePositiveFinite(`pollingInterval`,e.pollingInterval),validatePositiveFinite(`pollingBinaryInterval`,e.pollingBinaryInterval),typeof e.atomic==`number`)validateNonNegativeFinite(`atomic`,e.atomic);else if(typeof e.atomic!=`boolean`)throw TypeError(`atomic must be a boolean or finite non-negative number`);if(e.depth!==void 0&&(!Number.isSafeInteger(e.depth)||e.depth<0))throw TypeError(`depth must be a non-negative safe integer`);e.awaitWriteFinish&&(validatePositiveFinite(`awaitWriteFinish.pollInterval`,e.awaitWriteFinish.pollInterval),validateNonNegativeFinite(`awaitWriteFinish.stabilityThreshold`,e.awaitWriteFinish.stabilityThreshold))}var FSWatcher=class extends t{options;lifecycle;tree;reconciliation;events;scheduler;handler;readyEmitted;streams;get closed(){return this.lifecycle!==void 0&&this.lifecycle.state!==`OPEN`}#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e={},t=O){if(super(),e.backend!==void 0&&!Y.has(e.backend))throw TypeError(`backend must be auto, native, native-recursive, or polling`);this.#e=/* @__PURE__ */ new Set,this.streams=/* @__PURE__ */ new Set,this.#t=/* @__PURE__ */ new Map,this.#n=0,this.#r=/* @__PURE__ */ new Map,this.#o=/* @__PURE__ */ new Map,this.#s=/* @__PURE__ */ new Set,this.#c=/* @__PURE__ */ new Map,this.readyEmitted=!1,this.#u=!1,this.#d=!1,this.scheduler=t;let n=e.awaitWriteFinish,r={...e,persistent:e.persistent??!0,ignoreInitial:e.ignoreInitial??!1,ignorePermissionErrors:e.ignorePermissionErrors??!1,pollingInterval:e.pollingInterval??e.interval??100,pollingBinaryInterval:e.pollingBinaryInterval??e.binaryInterval??300,interval:100,binaryInterval:300,followSymlinks:e.followSymlinks??!0,backend:e.backend??`auto`,usePolling:e.usePolling??!1,depth:e.depth===1/0?void 0:e.depth,backendStrategy:`native-per-directory`,backendCapabilities:void 0,atomic:e.atomic??!0,ignored:Object.freeze(e.ignored?arrify(e.ignored).map(cloneOwnedMatcher):[]),awaitWriteFinish:n===!0?X:typeof n==`object`&&Object.freeze({...X,...n})};(e.usePolling===!0||D)&&(r.backend=`polling`);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e!==`false`&&e!==`0`&&(e===`true`||e===`1`||e)?r.backend=`polling`:r.backend===`polling`&&(r.backend=`auto`)}let a=process.env.CHOKIDAR_INTERVAL;a!==void 0&&(r.pollingInterval=Number(a)),r.interval=r.pollingInterval,r.binaryInterval=r.pollingBinaryInterval,r.usePolling=r.backend===`polling`,r.backendCapabilities=selectBackend(r),r.backendStrategy=r.backendCapabilities.kind,e.atomic===void 0&&(r.atomic=!r.usePolling),validateOptions(r),this.options=r,this.lifecycle=new LifecycleScope(()=>{this.#u&&this.queueReady()},e=>{this.closed||this.handleError(e instanceof Error?e:Error(String(e)))}),this.tree=new TreeState(()=>!this.options.backendCapabilities.polling),this.reconciliation=new ReconciliationQueue(this.lifecycle),this.events=new EventPolicy({options:this.options,scheduler:this.scheduler,lifecycle:this.lifecycle,isClosed:()=>this.closed,capturePathGeneration:()=>this.capturePathGeneration(),isPathGenerationActive:(e,t)=>this.isPathGenerationActive(e,t),isReady:()=>this.readyEmitted,remove:(e,t)=>this.removePath(e,t),handleError:e=>this.handleError(e),publish:(e,t)=>this.emitWithAll(e,t)}),this.handler=new ObservationEngine(this),Object.freeze(r)}addIgnoredPath(e){if(e=this.ignoredMatcher(e),isMatcherObject(e)){for(let t of this.#e)if(isMatcherObject(t)&&t.path===e.path&&t.recursive===e.recursive)return}this.#e.add(e),this.#l=void 0}removeIgnoredPath(e){if(e=this.ignoredMatcher(e),this.#e.delete(e),typeof e==`string`)for(let t of this.#e)isMatcherObject(t)&&t.path===e&&this.#e.delete(t);this.#l=void 0}ignoredMatcher(e){return typeof e==`string`?logicalPathKey(e):isMatcherObject(e)?{path:logicalPathKey(e.path),recursive:e.recursive}:e}capturePathGeneration(){return this.#n}invalidatePath(e){this.#r.set(logicalPathKey(e),++this.#n)}isPathGenerationActive(e,t){if(this.lifecycle.state!==`OPEN`)return!1;if(this.#r.size===0)return!0;let n=logicalPathKey(e);for(let[e,r]of this.#r)if(!(r<=t)&&isSameOrInside(e,n))return!1;return!0}queueReady(){this.closed||this.readyEmitted||(this.#u=!0,this.lifecycle.tasks.size>0||this.#d||(this.#d=!0,process.nextTick(()=>{this.#d=!1,this.closed||this.readyEmitted||this.lifecycle.tasks.size>0||(this.#u=!1,this.readyEmitted=!0,this.emit(k.READY))})))}add(e){if(this.closed)throw Error(`Cannot add paths after FSWatcher.close() has been called`);let{cwd:t}=this.options,n=unifyPaths(e);t&&(n=n.map(e=>getAbsolutePath(e,t))),n.forEach(e=>{this.removeIgnoredPath(e),this.addRootAncestors(e)}),this.readyEmitted||(this.#u=!0);let r=Promise.all(n.map(async e=>{let t=logicalPathKey(e);if(this.lifecycle.closers.has(t)||this.#t.has(t))return;let n=Symbol(t),r=this.capturePathGeneration();this.#t.set(t,n);try{await this.handler.addRoot(e,!0,r)}finally{this.#t.get(t)===n&&this.#t.delete(t)}}));return this.lifecycle.track(r),this.readyEmitted||this.queueReady(),this}unwatch(e){if(this.closed)return this;let t=unifyPaths(e),{cwd:n}=this.options;return n&&(t=t.map(e=>getAbsolutePath(e,n))),t.forEach(e=>{let t=logicalPathKey(e),n=this.tree.watched.has(t);this.invalidatePath(t),this.removeRootAncestors(t),this.#t.delete(t),this.events.cancelPath(t),this.closePath(t,n),this.addIgnoredPath(t),n&&this.addIgnoredPath({path:t,recursive:!0}),this.#l=void 0}),this}close(){if(this.#i)return this.#i;let e=this.lifecycle.beginClose();return this.removeAllListeners(),this.events.close(),this.#t.clear(),this.#s.clear(),this.#c.clear(),this.streams.forEach(e=>e.destroy()),this.#a=void 0,this.#l=void 0,this.readyEmitted=!1,this.tree.dispose(),this.#r.clear(),this.streams.clear(),this.reconciliation.clear(),this.#o.clear(),this.#i=(async()=>{let t=await Promise.allSettled(e);await this.lifecycle.drain(),this.lifecycle.finishClose();let n=t.find(e=>e.status===`rejected`);if(n)throw n.reason})(),this.#i}getWatched(){let e=Object.create(null);return this.tree.watched.forEach(t=>{let n=t.path,r=(this.options.cwd?u.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitRaw(...e){this.closed||this.emit(k.RAW,...e)}emitWithAll(e,t){this.emit(e,...t),e!==k.ERROR&&this.emit(k.ALL,e,...t)}async emitEvent(e,t,n){this.closed||await this.events.emit(e,t,n)}handleError(e){if(this.closed)return;let t=e instanceof Error?e:Error(String(e));isMissingError(t)||this.options.ignorePermissionErrors&&isPermissionError(t)||this.emit(k.ERROR,t)}isIgnored(e,t){if(this.options.atomic&&J.test(e))return!0;if(!this.#a){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(t=>normalizeMatcher(t,e)),n=compileMatchers(t),r=t.filter(e=>typeof e==`string`||isMatcherObject(e)),i=compileMatchers(r);this.#a=(e,t)=>{if(n(e,t))return!0;if(w||r.length===0)return!1;let a=u.resolve(e),o;if(t?.isDirectory())o=this.realDirectory(a);else{let e=this.realDirectory(u.dirname(a));e!==void 0&&(o=u.join(e,u.basename(a)))}return o!==void 0&&o!==a&&i(o,t)}}return this.#a(e,t)&&!this.isRootAncestor(e,t)?!0:this.#e.size!==0&&(this.#l||=compileMatchers([...this.#e]),this.#l(logicalPathKey(e),t))}isRootAncestor(e,t){return!t?.isFile()&&this.#c.has(logicalPathKey(e))}addRootAncestors(e){let t=logicalPathKey(e);if(!this.#s.has(t)){this.#s.add(t);for(let t of ancestorKeys(e))this.#c.set(t,(this.#c.get(t)??0)+1)}}removeRootAncestors(e){if(this.#s.delete(logicalPathKey(e)))for(let t of ancestorKeys(e)){let e=(this.#c.get(t)??1)-1;e>0?this.#c.set(t,e):this.#c.delete(t)}}realDirectory(e){let t=logicalPathKey(e);if(this.#o.has(t))return this.#o.get(t);let r;try{r=n.native(e)}catch{}return this.#o.set(t,r),r}isUnwatched(e){return this.#e.size!==0&&(this.#l||=compileMatchers([...this.#e]),this.#l(logicalPathKey(e)))}createHelper(e){return new N(e,this.options.followSymlinks,{capturePathGeneration:()=>this.capturePathGeneration(),isntIgnored:(e,t)=>!this.isIgnored(e,t)})}removeTreeItem(e,t){let n=this.tree.peekDirectory(e);if(!n?.remove(t))return;let r=n.path,i=this.lifecycle.generation;this.lifecycle.track((async()=>{try{await o(r)}catch(e){isMissingError(e)&&this.lifecycle.isActive(i)&&this.removePath(u.dirname(r),u.basename(r))}})())}removePath(e,t,n){let r=u.join(e,t),i=logicalPathKey(r);n??=this.tree.watched.has(i);let a=this.tree.peekDirectory(r)?.getChildren()??[];for(let e of a)this.removePath(r,e);let o=this.tree.peekDirectory(e)?.has(t)??!1,s=this.lifecycle.closers.has(i);this.removeTreeItem(e,t),this.tree.symlinkPaths.has(i)&&this.tree.symlinkPaths.delete(i);let c=this.events.pendingWrites.get(i),l=!1;this.options.awaitWriteFinish&&c&&(l=c.cancelWait()===k.ADD),this.tree.watched.delete(i),this.tree.observed.delete(i);let d=n?k.UNLINK_DIR:k.UNLINK;o&&!l&&!this.isIgnored(r)&&this.emitEvent(d,r),this.closePath(r),(o||s)&&this.#s.has(i)&&this.rewatchMissingPath(r)}rewatchMissingPath(e){this.closed||this.isUnwatched(e)||(this.closePath(e),this.lifecycle.track(this.handler.addRoot(e,!1,this.capturePathGeneration())))}closePath(e,t=!1){let n=logicalPathKey(e),contains=e=>e===n?!0:t?isStrictlyInside(n,e):!1;if([...this.lifecycle.closers.keys()].filter(contains).forEach(e=>this.closeFile(e)),this.#o.delete(n)||t){let e=n.endsWith(`/`)?n:`${n}/`;for(let t of this.#o.keys())t.startsWith(e)&&this.#o.delete(t)}if(t){for(let[e,t]of this.tree.watched)contains(e)&&(t.dispose(),this.tree.watched.delete(e));for(let e of this.tree.observed.keys())contains(e)&&this.tree.observed.delete(e);for(let e of this.tree.symlinkPaths.keys())contains(e)&&this.tree.symlinkPaths.delete(e);this.events.cancelWhere(contains),this.reconciliation.forgetPending((e,t)=>contains(e)||contains(t));for(let e of this.#t.keys())contains(e)&&this.#t.delete(e)}let r=u.dirname(n);this.removeTreeItem(r,u.basename(n))}closeFile(e){let t=logicalPathKey(e),n=this.lifecycle.takeClosers(t);n.length!==0&&n.forEach(e=>{try{let t=e();t instanceof Promise&&this.lifecycle.track(t)}catch(e){this.lifecycle.track(Promise.reject(e))}})}addPathCloser(e,t){if(!t)return;if(this.closed||this.isUnwatched(e)){try{let e=t();e instanceof Promise&&this.lifecycle.track(e)}catch(e){this.lifecycle.track(Promise.reject(e))}return}let n=logicalPathKey(e);this.lifecycle.addCloser(n,t)}createScanStream(e,t){if(this.closed)return;let n=readdirp(e,{type:k.ALL,alwaysStat:!0,lstat:!0,depth:0,...t});this.streams.add(n);let finalize=()=>this.streams.delete(n);return n.once(`close`,finalize),n.once(`end`,finalize),n.once(k.ERROR,finalize),n}};function watch(e,t={}){let n=new FSWatcher(t);return n.add(e),n}export{watch};
|
package/dist/clean-CyDDqbBD.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{t}from"./console-CIiXr7ge.mjs";import{c as n,l as r,r as i}from"./tracker-B3Fqx94J.mjs";import{a,r as o,s}from"./store-DjPdOKqg.mjs";import{D as c,E as l,a as u,c as d,f}from"./fs-CPnWm9CR.mjs";import{t as p}from"./format-DRqD29u-.mjs";import{i as m,n as h}from"./logger-9C6B9Na8.mjs";import{r as g}from"./dry-run-BkdMYSIx.mjs";import{n as _,t as v}from"./output-BxR2v-jn.mjs";import{t as y}from"./timer-DqgB175x.mjs";import{readdir as b}from"node:fs/promises";import{join as x}from"node:path";const S=3e5;var C=e({meta:{name:`clean`,description:`Remove unreferenced store entries and stale consumer registrations`},args:{yes:{type:`boolean`,alias:`y`,description:`Skip confirmation prompts`,default:!1}},async run({args:e}){_();let C=new y;t.start(`Checking consumer registrations...`);let{removedConsumers:w,removedPackages:T}=await i();w>0&&t.success(`Removed ${w} stale consumer registration(s) across ${T} package(s)`);let E=await r(),D=/* @__PURE__ */ new Set,O=[...new Set(Object.values(E).flat())],k=await Promise.all(O.map(async e=>{let{state:t,reliable:r}=await n(e);return{path:e,state:t,reliable:r}}));for(let{state:e,reliable:t}of k)if(t)for(let[t,n]of Object.entries(e.links))D.add(`${t}@${n.version}`);let A=/* @__PURE__ */ new Set,j=k.filter(e=>!e.reliable);if(j.length>0){t.warn(`${j.length} consumer(s) have corrupt state; their store entries will be preserved`);let e=new Set(j.map(e=>c(e.path)));for(let[t,n]of Object.entries(E))n.some(t=>e.has(t))&&A.add(t);m(`[clean] Protected packages (corrupt state): ${[...A].join(`, `)}`)}m(`[clean] Referenced entries: ${[...D].join(`, `)||`(none)`}`);let M=await o(),N=[];for(let e of M){let t=`${e.name}@${e.version}`;if(!D.has(t)){if(A.has(e.name)){m(`[clean] Preserving ${t} (consumer state unreadable)`);continue}let n=Date.now()-new Date(e.meta.publishedAt).getTime();if(n<S){m(`[clean] Skipping recently published entry: ${t} (${Math.round(n/1e3)}s old)`);continue}N.push(e)}}let P=[],F=l();if(await d(F)){let e=await b(F,{withFileTypes:!0});for(let t of e){let e=t.isDirectory()?a(t.name):null;if(e===null)continue;let n=Date.now()-e;n<S?m(`[clean] Skipping recent temp directory: ${t.name} (${Math.round(n/1e3)}s old)`):P.push(t.name)}}if(N.length+P.length>0&&!e.yes){let e=[];N.length>0&&e.push(`${N.length} unreferenced store entry(ies)`),P.length>0&&e.push(`${P.length} orphaned temp directory(ies)`);let n=await t.prompt(`Remove ${e.join(` and `)}?`,{type:`confirm`});if(!n||typeof n==`symbol`){t.info(`Cancelled`);return}}let I=0,L=await Promise.all(N.map(e=>u(e.packageDir))),R=await Promise.all(P.map(e=>u(x(F,e)))),z=0;for(let[e,t]of N.entries())m(`[clean] Removing unreferenced store entry: ${t.name}@${t.version}`),await s(t.name,t.version),I+=L[e]??0,z++;z>0&&t.success(`Removed ${z} unreferenced store entry(ies)`);let B=0;for(let[e,t]of P.entries())m(`[clean] Removing orphaned directory: ${t}`),await f(x(F,t)),I+=R[e]??0,B++;B>0&&t.success(`Removed ${B} orphaned temp directory(ies)`),w===0&&z===0&&B===0&&t.info(`Store is clean; no stale entries or registrations found`);let V=I>0?` (reclaimed ${p(I)})`:``;t.info(`Clean complete in ${C.elapsed()}${V}`),v({removedConsumers:w,removedPackages:T,removedEntries:z,removedOrphans:B,reclaimedBytes:I,elapsed:C.elapsedMs()}),h()&&g()}});export{C as default};
|
package/dist/config-BJsL6NqN.mjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{i as e}from"./logger-9C6B9Na8.mjs";import{t}from"./fs-CPnWm9CR.mjs";import{i as n,n as r,s as i}from"./json-DbSkpxtr.mjs";import{readFile as a}from"node:fs/promises";import{join as o}from"node:path";function finiteNumber(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}async function loadKnarrConfig(t){try{let r=await a(o(t,`package.json`),`utf-8`),s=n(i(r,`package.json`),`knarr`);if(!s)return{};let c={};typeof s.buildCmd==`string`&&(c.buildCmd=s.buildCmd);let l=s.watchPatterns;Array.isArray(l)&&(c.watchPatterns=l.filter(e=>typeof e==`string`));let u=finiteNumber(s.debounce);u!==void 0&&(c.debounce=u);let d=finiteNumber(s.cooldown);d!==void 0&&(c.cooldown=d);let f=finiteNumber(s.historyLimit);return f!==void 0&&(c.historyLimit=Math.max(0,Math.floor(f))),typeof s.notify==`boolean`&&(c.notify=s.notify),e(`[config] Loaded knarr config from package.json: ${JSON.stringify(c)}`),c}catch{return{}}}async function setKnarrBuildCmdIfMissing(e,o){if(!o)return!1;let s=await a(e,`utf-8`),c=i(s,e),l=n(c,`knarr`);return l&&typeof l.buildCmd==`string`?!1:(c.knarr={...l,buildCmd:o},await t(e,JSON.stringify(c,null,r(s))+`
|
|
4
|
-
`),!0)}export{setKnarrBuildCmdIfMissing as n,loadKnarrConfig as t};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{styleText as e}from"node:util";import{createInterface as t}from"node:readline/promises";import{stdin as n,stdout as r}from"node:process";function style(t){return n=>e(t,String(n))}const i={bold:style(`bold`),dim:style(`dim`),cyan:style(`cyan`),green:style(`green`),red:style(`red`),yellow:style(`yellow`)};let a=3;async function prompt(e,a){if(!n.isTTY)return answerNonInteractive(e,a);let o=t({input:n,output:r});try{if(a.type===`confirm`){let t=a.initial===!1?`y/N`:`Y/n`,n=(await o.question(`${i.cyan(`?`)} ${e} ${i.dim(`(${t})`)} `)).trim().toLowerCase();return n===``?a.initial!==!1:n===`y`||n===`yes`}if(a.type===`text`){let t=a.default?i.dim(` (${a.default})`):``;return(await o.question(`${i.cyan(`?`)} ${e}${t} `)).trim()||a.default||``}console.log(`${i.cyan(`?`)} ${e}`);for(let[e,t]of a.options.entries())console.log(` ${i.cyan(`${e+1}.`)} ${t.label}`);let t=await o.question(`${i.dim(`Enter number:`)} `),n=a.options[parseInt(t,10)-1]??a.options[0];if(!n)throw Error(`No options to choose from for "${e}"`);return n.value}finally{o.close()}}function answerNonInteractive(e,t){if(t.type===`confirm`&&t.initial!==void 0)return console.error(`${i.cyan(`i`)} ${e} ${i.dim(`-> ${t.initial?`yes`:`no`} (no interactive terminal, using default)`)}`),t.initial;if(t.type===`text`)return t.default??``;console.error(`${i.red(`x`)} Cannot ask "${e}": no interactive terminal (stdin is not a TTY).`),console.error(`${i.cyan(`i`)} ${i.dim(`Suggestion:`)} ${t.type===`confirm`?`Re-run with --yes to confirm.`:t.nonInteractiveHint??`Pass the choice as a flag (see --help).`}`),process.exit(1)}const o={get level(){return a},set level(e){a=e},info(e,...t){a>=3&&console.log(i.cyan(`i`),e,...t)},success(e,...t){a>=3&&console.log(i.green(`OK`),e,...t)},warn(e,...t){a>=2&&console.warn(i.yellow(`!`),e,...t)},error(e,...t){a>=1&&console.error(i.red(`x`),e,...t)},start(e,...t){a>=3&&console.log(i.cyan(`...`),e,...t)},debug(e,...t){a>=4&&console.debug(i.dim(`D`),e,...t)},log(e,...t){a>=3&&console.log(e,...t)},prompt};export{i as n,o as t};
|
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
import { styleText } from "node:util";
|
|
2
|
-
import { createInterface } from "node:readline/promises";
|
|
3
|
-
import { stdin, stdout } from "node:process";
|
|
4
|
-
// src/utils/colors.ts
|
|
5
|
-
/**
|
|
6
|
-
* Terminal colors via Node's built-in `util.styleText` (stable since 22.13).
|
|
7
|
-
* It checks the output stream and honours NO_COLOR, NODE_DISABLE_COLORS and
|
|
8
|
-
* FORCE_COLOR, so piped or CI output stays plain unless FORCE_COLOR is set.
|
|
9
|
-
*/
|
|
10
|
-
function style(format) {
|
|
11
|
-
return (text) => styleText(format, String(text));
|
|
12
|
-
}
|
|
13
|
-
const pc = {
|
|
14
|
-
bold: style("bold"),
|
|
15
|
-
dim: style("dim"),
|
|
16
|
-
cyan: style("cyan"),
|
|
17
|
-
green: style("green"),
|
|
18
|
-
red: style("red"),
|
|
19
|
-
yellow: style("yellow")
|
|
20
|
-
};
|
|
21
|
-
// src/utils/console.ts
|
|
22
|
-
/** Logging level: -1=silent, 0=fatal, 1=error, 2=warn, 3=info, 4=debug */
|
|
23
|
-
let _level = 3;
|
|
24
|
-
async function prompt(message, options) {
|
|
25
|
-
if (!stdin.isTTY) return answerNonInteractive(message, options);
|
|
26
|
-
const rl = createInterface({
|
|
27
|
-
input: stdin,
|
|
28
|
-
output: stdout
|
|
29
|
-
});
|
|
30
|
-
try {
|
|
31
|
-
if (options.type === "confirm") {
|
|
32
|
-
const hint = options.initial !== false ? "Y/n" : "y/N";
|
|
33
|
-
const val = (await rl.question(`${pc.cyan("?")} ${message} ${pc.dim(`(${hint})`)} `)).trim().toLowerCase();
|
|
34
|
-
if (val === "") return options.initial !== false;
|
|
35
|
-
return val === "y" || val === "yes";
|
|
36
|
-
}
|
|
37
|
-
if (options.type === "text") {
|
|
38
|
-
const hint = options.default ? pc.dim(` (${options.default})`) : "";
|
|
39
|
-
return (await rl.question(`${pc.cyan("?")} ${message}${hint} `)).trim() || options.default || "";
|
|
40
|
-
}
|
|
41
|
-
console.log(`${pc.cyan("?")} ${message}`);
|
|
42
|
-
for (const [i, option] of options.options.entries()) console.log(` ${pc.cyan(`${i + 1}.`)} ${option.label}`);
|
|
43
|
-
const answer = await rl.question(`${pc.dim("Enter number:")} `);
|
|
44
|
-
const chosen = options.options[parseInt(answer, 10) - 1] ?? options.options[0];
|
|
45
|
-
if (!chosen) throw new Error(`No options to choose from for "${message}"`);
|
|
46
|
-
return chosen.value;
|
|
47
|
-
} finally {
|
|
48
|
-
rl.close();
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* Without a TTY, readline never resolves: Node drains the event loop and exits
|
|
53
|
-
* 0 mid-command, so a script or CI job "succeeds" having done nothing. Answer
|
|
54
|
-
* from the prompt's declared default instead, and fail loudly when there is no
|
|
55
|
-
* safe default (destructive confirms declare none; selects need a choice).
|
|
56
|
-
*/
|
|
57
|
-
function answerNonInteractive(message, options) {
|
|
58
|
-
if (options.type === "confirm" && options.initial !== void 0) {
|
|
59
|
-
console.error(`${pc.cyan("i")} ${message} ${pc.dim(`-> ${options.initial ? "yes" : "no"} (no interactive terminal, using default)`)}`);
|
|
60
|
-
return options.initial;
|
|
61
|
-
}
|
|
62
|
-
if (options.type === "text") return options.default ?? "";
|
|
63
|
-
console.error(`${pc.red("x")} Cannot ask "${message}": no interactive terminal (stdin is not a TTY).`);
|
|
64
|
-
console.error(`${pc.cyan("i")} ${pc.dim("Suggestion:")} ${options.type === "confirm" ? "Re-run with --yes to confirm." : options.nonInteractiveHint ?? "Pass the choice as a flag (see --help)."}`);
|
|
65
|
-
process.exit(1);
|
|
66
|
-
}
|
|
67
|
-
const consola = {
|
|
68
|
-
get level() {
|
|
69
|
-
return _level;
|
|
70
|
-
},
|
|
71
|
-
set level(n) {
|
|
72
|
-
_level = n;
|
|
73
|
-
},
|
|
74
|
-
info(msg, ...args) {
|
|
75
|
-
if (_level >= 3) console.log(pc.cyan("i"), msg, ...args);
|
|
76
|
-
},
|
|
77
|
-
success(msg, ...args) {
|
|
78
|
-
if (_level >= 3) console.log(pc.green("OK"), msg, ...args);
|
|
79
|
-
},
|
|
80
|
-
warn(msg, ...args) {
|
|
81
|
-
if (_level >= 2) console.warn(pc.yellow("!"), msg, ...args);
|
|
82
|
-
},
|
|
83
|
-
error(msg, ...args) {
|
|
84
|
-
if (_level >= 1) console.error(pc.red("x"), msg, ...args);
|
|
85
|
-
},
|
|
86
|
-
start(msg, ...args) {
|
|
87
|
-
if (_level >= 3) console.log(pc.cyan("..."), msg, ...args);
|
|
88
|
-
},
|
|
89
|
-
debug(msg, ...args) {
|
|
90
|
-
if (_level >= 4) console.debug(pc.dim("D"), msg, ...args);
|
|
91
|
-
},
|
|
92
|
-
/** Plain log (no icon) that still respects level suppression */
|
|
93
|
-
log(msg, ...args) {
|
|
94
|
-
if (_level >= 3) console.log(msg, ...args);
|
|
95
|
-
},
|
|
96
|
-
prompt
|
|
97
|
-
};
|
|
98
|
-
export { pc as n, consola as t };
|
package/dist/dev-kqgY9NjI.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t}from"./output-BxR2v-jn.mjs";import{a as n,i as r,o as i,s as a,t as o}from"./push-engine-BpNr8qXR.mjs";import{t as s}from"./batch-push-DXtZxRx0.mjs";import{t as c}from"./config-BJsL6NqN.mjs";import{n as l}from"./logger-9C6B9Na8.mjs";import{r as u}from"./dry-run-BkdMYSIx.mjs";import{resolve as d}from"node:path";var f=e({meta:{name:`dev`,description:`Watch, rebuild, and push to all consumers. Auto-detects build command.`},args:{all:{type:`boolean`,description:`Watch all workspace packages in dependency order`,default:!1},build:{type:`string`,description:`Override build command (default: auto-detect from package.json)`},"skip-build":{type:`boolean`,description:`Watch output dirs directly, skip build command detection`,default:!1},debounce:{type:`string`,description:`Debounce delay in ms (default: 500)`},cooldown:{type:`string`,description:`Minimum time between builds in ms (default: 500)`},"no-scripts":{type:`boolean`,description:`Skip prepack/postpack lifecycle hooks`,default:!1},force:{type:`boolean`,alias:`f`,description:`Force copy all files, bypassing hash comparison`,default:!1},notify:{type:`boolean`,description:`Ring terminal bell on push completion`,default:!1},"no-cascade":{type:`boolean`,description:`Disable cascading rebuilds in --all mode`,default:!1}},async run({args:e}){t();let f=d(`.`),p=await c(f),m={runScripts:!e[`no-scripts`],force:e.force,historyLimit:p.historyLimit};if(e.all){let t=await n(f,e),r=/* @__PURE__ */ new Set([...t.failedPackages,...t.skippedPackages]);if(t.canPush&&await s(f,{...m,skipPackages:r}),l()){u();return}await i(f,e,m)}else{let push=()=>o(f,m);if(await r(f,e,p)&&await push(),l()){u();return}await a(f,e,push)}}});export{f as default};
|
package/dist/dist-CFkjiIqD.mjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import{n as e}from"./rolldown-runtime-BZbIAPMk.mjs";import{parseArgs as t}from"node:util";const n=/\d/,r=[`-`,`_`,`/`,`.`];function isUppercase(e=``){if(!n.test(e))return e!==e.toLowerCase()}function splitByCase(e,t){let n=t??r,i=[];if(!e||typeof e!=`string`)return i;let a=``,o,s;for(let t of e){let e=n.includes(t);if(e===!0){i.push(a),a=``,o=void 0;continue}let r=isUppercase(t);if(s===!1){if(o===!1&&r===!0){i.push(a),a=t,o=r;continue}if(o===!0&&r===!1&&a.length>1){let e=a.at(-1);i.push(a.slice(0,Math.max(0,a.length-1))),a=e+t,o=r;continue}}a+=t,o=r,s=e}return i.push(a),i}function upperFirst(e){return e?e[0].toUpperCase()+e.slice(1):``}function lowerFirst(e){return e?e[0].toLowerCase()+e.slice(1):``}function pascalCase(e,t){return e?(Array.isArray(e)?e:splitByCase(e)).map(e=>upperFirst(t?.normalize?e.toLowerCase():e)).join(``):``}function camelCase(e,t){return lowerFirst(pascalCase(e||``,t))}function kebabCase(e,t){return e?(Array.isArray(e)?e:splitByCase(e)).map(e=>e.toLowerCase()).join(t??`-`):``}function snakeCase(e){return kebabCase(e||``,`_`)}function toArray(e){return Array.isArray(e)?e:e===void 0?[]:[e]}function formatLineColumns(e,t=``){let n=[];for(let t of e)for(let[e,r]of t.entries())n[e]=Math.max(n[e]||0,r.length);return e.map(e=>e.map((e,r)=>t+e[r===0?`padStart`:`padEnd`](n[r])).join(` `)).join(`
|
|
4
|
-
`)}function resolveValue(e){return typeof e==`function`?e():e}var CLIError=class extends Error{code;constructor(e,t){super(e),this.name=`CLIError`,this.code=t}};function parseRawArgs(e=[],n={}){let r=new Set(n.boolean||[]),i=new Set(n.string||[]),a=n.alias||{},o=n.default||{},s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let[e,t]of Object.entries(a)){let n=t;for(let t of n)s.set(e,t),c.has(t)||c.set(t,[]),c.get(t).push(e),s.set(t,e),c.has(e)||c.set(e,[]),c.get(e).push(t)}let l={};function getType(e){if(r.has(e))return`boolean`;let t=c.get(e)||[];for(let e of t)if(r.has(e))return`boolean`;return`string`}function isStringType(e){if(i.has(e))return!0;let t=c.get(e)||[];for(let e of t)if(i.has(e))return!0;return!1}let u=/* @__PURE__ */ new Set([...r,...i,...Object.keys(a),...Object.values(a).flat(),...Object.keys(o)]);for(let e of u)l[e]||(l[e]={type:getType(e),default:o[e]});for(let[e,t]of s.entries())e.length===1&&l[t]&&!l[t].short&&(l[t].short=e);let d=[],f={};for(let t=0;t<e.length;t++){let n=e[t];if(n===`--`){d.push(...e.slice(t));break}if(n.startsWith(`--no-`)){let e=n.slice(5);f[e]=!0}else d.push(n)}let p;try{p=t({args:d,options:Object.keys(l).length>0?l:void 0,allowPositionals:!0,strict:!1})}catch{p={values:{},positionals:d}}let m={_:[]};m._=p.positionals;for(let[e,t]of Object.entries(p.values)){let n=t;getType(e)===`boolean`&&typeof t==`string`?n=t!==`false`:isStringType(e)&&typeof t==`boolean`&&(n=``),m[e]=n}for(let[e]of Object.entries(f)){m[e]=!1;let t=s.get(e);t&&(m[t]=!1);let n=c.get(e);if(n)for(let e of n)m[e]=!1}for(let[e,t]of s.entries())m[e]!==void 0&&m[t]===void 0&&(m[t]=m[e]),m[t]!==void 0&&m[e]===void 0&&(m[e]=m[t]),m[e]!==m[t]&&o[t]===m[t]&&(m[t]=m[e]);return m}const i=/* @__PURE__ */ (()=>{let e=globalThis.process?.env??{};return e.NO_COLOR===`1`||e.TERM===`dumb`||e.TEST||e.CI})(),_c=(e,t=39)=>n=>i?n:`\u001B[${e}m${n}\u001B[${t}m`,a=/* @__PURE__ */ _c(1,22),o=/* @__PURE__ */ _c(36),s=/* @__PURE__ */ _c(90),c=/* @__PURE__ */ _c(4,24);function parseArgs$2(e,t){let n={boolean:[],string:[],alias:{},default:{}},r=resolveArgs(t);for(let e of r){if(e.type===`positional`)continue;e.type===`string`||e.type===`enum`?n.string.push(e.name):e.type===`boolean`&&n.boolean.push(e.name),e.default!==void 0&&(n.default[e.name]=e.default),e.alias&&(n.alias[e.name]=e.alias);let t=camelCase(e.name),r=kebabCase(e.name);if(t!==e.name||r!==e.name){let i=toArray(n.alias[e.name]||[]);t!==e.name&&!i.includes(t)&&i.push(t),r!==e.name&&!i.includes(r)&&i.push(r),i.length>0&&(n.alias[e.name]=i)}}let i=parseRawArgs(e,n),[...a]=i._,s=new Proxy(i,{get(e,t){return e[t]??e[camelCase(t)]??e[kebabCase(t)]}});for(let[,e]of r.entries())if(e.type===`positional`){let t=a.shift();if(t!==void 0)s[e.name]=t;else if(e.default===void 0&&e.required!==!1)throw new CLIError(`Missing required positional argument: ${e.name.toUpperCase()}`,`EARG`);else s[e.name]=e.default}else if(e.type===`enum`){let t=s[e.name],n=e.options||[];if(t!==void 0&&n.length>0&&!n.includes(t))throw new CLIError(`Invalid value for argument: ${o(`--${e.name}`)} (${o(t)}). Expected one of: ${n.map(e=>o(e)).join(`, `)}.`,`EARG`)}else if(e.required&&s[e.name]===void 0)throw new CLIError(`Missing required argument: --${e.name}`,`EARG`);return s}e(parseArgs$2,`parseArgs`);function resolveArgs(e){let t=[];for(let[n,r]of Object.entries(e||{}))t.push({...r,name:n,alias:toArray(r.alias)});return t}async function resolvePlugins(e){return Promise.all(e.map(e=>resolveValue(e)))}function defineCommand(e){return e}async function runCommand(e,t){let n=await resolveValue(e.args||{}),r=parseArgs$2(t.rawArgs,n),i={rawArgs:t.rawArgs,args:r,data:t.data,cmd:e},a=await resolvePlugins(e.plugins??[]),s,c;try{for(let e of a)await e.setup?.(i);typeof e.setup==`function`&&await e.setup(i);let r=await resolveValue(e.subCommands);if(r&&Object.keys(r).length>0){let i=findSubCommandIndex(t.rawArgs,n),a=t.rawArgs[i];if(a){let e=await _findSubCommand(r,a);if(!e)throw new CLIError(`Unknown command ${o(a)}`,`E_UNKNOWN_COMMAND`);await runCommand(e,{rawArgs:t.rawArgs.slice(i+1)})}else{let n=await resolveValue(e.default);if(n){if(e.run)throw new CLIError(`Cannot specify both 'run' and 'default' on the same command.`,`E_DEFAULT_CONFLICT`);let i=await _findSubCommand(r,n);if(!i)throw new CLIError(`Default sub command ${o(n)} not found in subCommands.`,`E_UNKNOWN_COMMAND`);await runCommand(i,{rawArgs:t.rawArgs})}else if(!e.run)throw new CLIError(`No command specified.`,`E_NO_COMMAND`)}}typeof e.run==`function`&&(s=await e.run(i))}catch(e){c=e}let l=[];if(typeof e.cleanup==`function`)try{await e.cleanup(i)}catch(e){l.push(e)}for(let e of[...a].reverse())try{await e.cleanup?.(i)}catch(e){l.push(e)}if(c)throw c;if(l.length===1)throw l[0];if(l.length>1)throw Error(`Multiple cleanup errors`,{cause:l});return{result:s}}async function resolveSubCommand(e,t,n){let r=await resolveValue(e.subCommands);if(r&&Object.keys(r).length>0){let n=findSubCommandIndex(t,await resolveValue(e.args||{})),i=t[n],a=await _findSubCommand(r,i);if(a)return resolveSubCommand(a,t.slice(n+1),e)}return[e,n]}async function _findSubCommand(e,t){if(t in e)return resolveValue(e[t]);for(let n of Object.values(e)){let e=await resolveValue(n),r=await resolveValue(e?.meta);if(r?.alias&&toArray(r.alias).includes(t))return e}}function findSubCommandIndex(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r===`--`)return-1;if(r.startsWith(`-`))!r.includes(`=`)&&_isValueFlag(r,t)&&n++;else return n}return-1}function _isValueFlag(e,t){let n=e.replace(/^-{1,2}/,``),r=camelCase(n);for(let[e,i]of Object.entries(t))if((i.type===`string`||i.type===`enum`)&&(r===camelCase(e)||(Array.isArray(i.alias)?i.alias:i.alias?[i.alias]:[]).includes(n)))return!0;return!1}async function showUsage(e,t){try{console.log(await renderUsage(e,t)+`
|
|
5
|
-
`)}catch(e){console.error(e)}}const l=/^no[-A-Z]/;async function renderUsage(e,t){let n=await resolveValue(e.meta||{}),r=resolveArgs(await resolveValue(e.args||{})),i=await resolveValue(t?.meta||{}),u=`${i.name?`${i.name} `:``}`+(n.name||process.argv[1]),d=[],f=[],p=[],m=[];for(let e of r)if(e.type===`positional`){let t=e.name.toUpperCase(),n=e.required!==!1&&e.default===void 0;f.push([o(t+renderValueHint(e)),renderDescription(e,n)]),m.push(n?`<${t}>`:`[${t}]`)}else{let t=e.required===!0&&e.default===void 0,n=[...(e.alias||[]).map(e=>`-${e}`),`--${e.name}`].join(`, `)+renderValueHint(e);if(d.push([o(n),renderDescription(e,t)]),e.type===`boolean`&&(e.default===!0||e.negativeDescription)&&!l.test(e.name)){let n=[...(e.alias||[]).map(e=>`--no-${e}`),`--no-${e.name}`].join(`, `);d.push([o(n),[e.negativeDescription,t?s(`(Required)`):``].filter(Boolean).join(` `)])}t&&m.push(`--${e.name}`+renderValueHint(e))}if(e.subCommands){let t=[],n=await resolveValue(e.subCommands);for(let[e,r]of Object.entries(n)){let n=await resolveValue((await resolveValue(r))?.meta);if(n?.hidden)continue;let i=toArray(n?.alias),a=[e,...i].join(`, `);p.push([o(a),n?.description||``]),t.push(e,...i)}m.push(t.join(`|`))}let h=[],g=n.version||i.version;h.push(s(`${n.description} (${u+(g?` v${g}`:``)})`),``);let _=d.length>0||f.length>0;return h.push(`${c(a(`USAGE`))} ${o(`${u}${_?` [OPTIONS]`:``} ${m.join(` `)}`)}`,``),f.length>0&&(h.push(c(a(`ARGUMENTS`)),``),h.push(formatLineColumns(f,` `)),h.push(``)),d.length>0&&(h.push(c(a(`OPTIONS`)),``),h.push(formatLineColumns(d,` `)),h.push(``)),p.length>0&&(h.push(c(a(`COMMANDS`)),``),h.push(formatLineColumns(p,` `)),h.push(``,`Use ${o(`${u} <command> --help`)} for more information about a command.`)),h.filter(e=>typeof e==`string`).join(`
|
|
6
|
-
`)}function renderValueHint(e){let t=e.valueHint?`=<${e.valueHint}>`:``,n=t||`=<${snakeCase(e.name)}>`;return!e.type||e.type===`positional`||e.type===`boolean`?t:e.type===`enum`&&e.options?.length?`=<${e.options.join(`|`)}>`:n}function renderDescription(e,t){let n=t?s(`(Required)`):``,r=e.default===void 0?``:s(`(Default: ${e.default})`);return[e.description,n,r].filter(Boolean).join(` `)}async function runMain(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||showUsage;try{let t=await _resolveBuiltinFlags(e);if(t.help.length>0&&n.some(e=>t.help.includes(e)))await r(...await resolveSubCommand(e,n)),process.exit(0);else if(n.length===1&&t.version.includes(n[0])){let t=typeof e.meta==`function`?await e.meta():await e.meta;if(!t?.version)throw new CLIError(`No version specified`,`E_NO_VERSION`);console.log(t.version)}else await runCommand(e,{rawArgs:n})}catch(t){t instanceof CLIError?(await r(...await resolveSubCommand(e,n)),console.error(t.message)):console.error(t,`
|
|
7
|
-
`),process.exit(1)}}async function _resolveBuiltinFlags(e){let t=await resolveValue(e.args||{}),n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set;for(let[e,i]of Object.entries(t)){n.add(e);for(let e of toArray(i.alias))r.add(e)}return{help:_getBuiltinFlags(`help`,`h`,n,r),version:_getBuiltinFlags(`version`,`v`,n,r)}}function _getBuiltinFlags(e,t,n,r){return n.has(e)||r.has(e)?[]:n.has(t)||r.has(t)?[`--${e}`]:[`--${e}`,`-${t}`]}export{runMain as n,defineCommand as t};
|
package/dist/doctor-D-S1P0UG.mjs
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t,t as n}from"./console-CIiXr7ge.mjs";import{c as r,i,m as a,r as o,u as s}from"./tracker-B3Fqx94J.mjs";import{n as c,r as l}from"./store-DjPdOKqg.mjs";import{o as u}from"./injector-nt40JxVt.mjs";import{E as d,_ as f,c as p,u as m,v as h,y as g}from"./fs-CPnWm9CR.mjs";import{t as _}from"./package-manager-DJ8CE0zL.mjs";import{n as v}from"./bundler-detect-Dq-QAbQj.mjs";import{a as y,c as b,d as x,l as S,o as C,u as w}from"./init-helpers-CYYWQm-P.mjs";import{n as T,t as E}from"./output-BxR2v-jn.mjs";import{n as D,r as O}from"./logger-9C6B9Na8.mjs";import{r as k}from"./dry-run-BkdMYSIx.mjs";import{c as A,i as j,l as M}from"./json-DbSkpxtr.mjs";import{readFile as N,stat as P}from"node:fs/promises";import{basename as F,join as I,resolve as L}from"node:path";async function runDoctorDiagnostics(e,t={}){let n=[],m=D(),w=t.fix===!0,T=m?`Would `:``;async function addCheck(e,t){let r={fixable:!1,fixed:!1,fixes:[],...e};if(w&&r.fixable&&t){let e=await t();e&&(r.fixed=!m,r.fixes.push(`${T}${e}`))}n.push(r)}let E=(await _(e)).resolve(),O=E.packageManager,k=!!E.nodeModulesCompatible,N="Yarn PnP has no node_modules tree for Knarr to manage. Set `nodeLinker: node-modules` or `nodeLinker: pnpm`, run `yarn install`, then re-run `knarr doctor --fix`.",P=d();await p(P)?await addCheck({name:`Store directory`,status:`pass`,message:`${(await l()).length} entries in ${P}`}):await addCheck({name:`Store directory`,status:`warn`,message:`Store not found at ${P}. Run 'knarr publish' to create it.`});let L=g(),{registry:R,reliable:z}=await s();if(!z)await addCheck({name:`Global registry`,status:`fail`,message:`${L} is corrupt or unreadable.`,unfixableReason:i()});else if(await p(L)){let e=Object.values(R).flat().length;await addCheck({name:`Global registry`,status:`pass`,message:`${Object.keys(R).length} packages, ${e} consumer registrations`})}else await addCheck({name:`Global registry`,status:`warn`,message:`No consumers registered yet. Use 'knarr add' to link packages.`});let B=await findStaleRegistryEntries(R),V=B.missingDirectories+B.missingLinks;V>0&&await addCheck({name:`Stale registry entries`,status:`warn`,message:`${V} stale consumer registration(s) found`+(B.unreadableConsumers>0?`; ${B.unreadableConsumers} unreadable state file(s) skipped`:``),fixable:!0},async()=>`remove ${(await o({removeMissingLinks:!0})).removedConsumers} stale consumer registration(s)`);let H=h(e),U=f(e),W=await pathKind(U),G=await p(H),{state:K,reliable:q}=await r(e);if(W===`file`)await addCheck({name:`Consumer state`,status:`fail`,message:`${U} exists but is not a directory.`,unfixableReason:`Move or delete ${U}, then run 'knarr init'.`}),q=!1;else if(G)q||await addCheck({name:`Consumer state`,status:`fail`,message:`state.json is corrupt or unreadable. Delete .knarr/state.json and re-run 'knarr add' for each package.`,unfixableReason:`Corrupt state may contain links Knarr cannot safely reconstruct.`});else{let t={name:`Consumer state`,status:`warn`,message:`No .knarr/state.json found.`,fixable:k,fixed:!1,fixes:[],...k?{}:{unfixableReason:N}};w&&t.fixable&&(await a(e,e=>{e.packageManager=O,e.role=`consumer`}),t.fixed=!m,t.fixes.push(`${T}create .knarr/state.json`),G=await p(H),{state:K,reliable:q}=await r(e)),n.push(t)}let J=q?Object.entries(K.links):[];q&&G&&(J.length>0?await addCheck({name:`Consumer state`,status:`pass`,message:`${J.length} linked package(s)`}):await addCheck({name:`Consumer state`,status:`warn`,message:`No packages linked. Use 'knarr add' to link a package.`}));for(let[t,n]of J){let r=await c(t,n.version);r?r.meta.contentHash===n.contentHash?await addCheck({name:`Store: ${t}`,status:`pass`,message:`${t}@${n.version} in sync`}):await addCheck({name:`Store: ${t}`,status:`warn`,message:`Store has newer content. Run 'knarr update' to sync.`}):await addCheck({name:`Store: ${t}`,status:`fail`,message:`Store entry missing for ${t}@${n.version}. Re-publish it.`});let i;try{i=await u(e,t,n.packageManager,n.version,{warnOnFallback:!1})}catch(e){await addCheck({name:`node_modules: ${t}`,status:`fail`,message:`Cannot resolve package target. ${e instanceof Error?e.message:String(e)}`});continue}if(!await p(i))await addCheck({name:`node_modules: ${t}`,status:`fail`,message:`Missing from node_modules. Run 'knarr restore'.`});else try{let e=await A(I(i,`package.json`)),r=M(e,`name`),a=M(e,`version`);r&&r!==t?await addCheck({name:`node_modules: ${t}`,status:`fail`,message:`node_modules target contains package "${r}". Run your package manager install, then 'knarr restore'.`}):a&&a!==n.version?await addCheck({name:`node_modules: ${t}`,status:`warn`,message:`node_modules has v${a} but Knarr linked v${n.version}. Run 'knarr restore'.`}):await addCheck({name:`node_modules: ${t}`,status:`pass`,message:`present`})}catch{await addCheck({name:`node_modules: ${t}`,status:`pass`,message:`present`})}}await addCheck({name:`Package manager`,status:`pass`,message:O}),E.yarnLinkerDiagnostic&&await addCheck({name:`Yarn linker`,...E.yarnLinkerDiagnostic});let Y=await v(e);if(Y.type?await addCheck({name:`Bundler`,status:`pass`,message:`${Y.type}${Y.configFile?` (${Y.configFile})`:``}`}):await addCheck({name:`Bundler`,status:`warn`,message:`No bundler config detected`}),Y.type===`vite`&&Y.configFile){let{addKnarrVitePlugin:e,hasKnarrVitePlugin:t}=await import(`./vite-config-BRlYc4ni.mjs`),r=await t(Y.configFile);if(r.error)await addCheck({name:`Vite integration`,status:`warn`,message:r.error});else if(r.configured)await addCheck({name:`Vite integration`,status:`pass`,message:`Knarr plugin configured`});else{let t={name:`Vite integration`,status:`warn`,message:`Knarr Vite plugin is missing.`,fixable:k,fixed:!1,fixes:[],...k?{}:{unfixableReason:N}};if(w&&t.fixable){let n=await e(Y.configFile);n.modified?(t.fixed=!m,t.fixes.push(`${T}add Knarr Vite plugin to ${F(Y.configFile)}`)):n.error&&(t.unfixableReason=n.error)}n.push(t)}}if(Y.type===`next`&&Y.configFile){let{addToTranspilePackages:e,hasTranspilePackage:t}=await import(`./nextjs-config-BQgTWZ96.mjs`);for(let[r]of J){let i=await t(Y.configFile,r);if(i.configured){await addCheck({name:`Next.js integration: ${r}`,status:`pass`,message:`transpilePackages configured`});continue}let a={name:`Next.js integration: ${r}`,status:`warn`,message:`${r} is missing from transpilePackages.`,fixable:!i.error&&k,fixed:!1,fixes:[],...i.error?{unfixableReason:i.error}:k?{}:{unfixableReason:N}};if(w&&a.fixable){let t=await e(Y.configFile,r);t.modified?(a.fixed=!m,a.fixes.push(`${T}add ${r} to transpilePackages in ${F(Y.configFile)}`)):t.error&&(a.unfixableReason=t.error)}n.push(a)}}let X=I(e,`.gitignore`);await gitignoreIncludesKnarr(X)?await addCheck({name:`.gitignore`,status:`pass`,message:`.knarr/ is ignored`}):await addCheck({name:`.gitignore`,status:`warn`,message:`.knarr/ not in .gitignore.`,fixable:k,...k?{}:{unfixableReason:N}},async()=>await y(X)?`add .knarr/ to .gitignore`:null);let Z=I(e,`package.json`);if(await p(Z)){let t=await readJsonFile(Z),n=t?j(t,`scripts`)?.postinstall:void 0;typeof n==`string`&&S(n)?await p(I(e,`.knarr`,`restore.cjs`))?await addCheck({name:`Postinstall restore`,status:`pass`,message:`postinstall re-applies links via .knarr/restore.cjs`}):await addCheck({name:`Postinstall restore`,status:`warn`,message:`.knarr/restore.cjs is missing, so installs won't re-apply links.`,fixable:k,...k?{}:{unfixableReason:N}},async()=>(await x(e),`write .knarr/restore.cjs`)):typeof n==`string`&&b(n)?await canVerifyKnarrForPostinstall(e,t,n)?await addCheck({name:`Postinstall restore`,status:`pass`,message:`postinstall runs knarr restore`}):n.includes(`knarr restore --silent || node -e "process.exit(0)"`)?await addCheck({name:`Postinstall restore`,status:`warn`,message:`postinstall runs knarr restore, but no local knarr dependency or binary was found, so installs silently drop links.`,fixable:k,...k?{}:{unfixableReason:N}},async()=>(await C(e),`upgrade postinstall restore hook (works without a global knarr)`)):await addCheck({name:`Postinstall restore`,status:`warn`,message:`postinstall runs knarr restore, but no local knarr dependency or binary was found.`,unfixableReason:`Install knarr as a devDependency for reliable auto-restore, or ensure a global knarr binary is available during installs.`}):typeof n==`string`?await addCheck({name:`Postinstall restore`,status:`warn`,message:`postinstall exists but does not run knarr restore.`,unfixableReason:`Existing postinstall scripts are not merged automatically.`}):await addCheck({name:`Postinstall restore`,status:`warn`,message:`postinstall restore hook is missing.`,fixable:k,...k?{}:{unfixableReason:N}},async()=>(await C(e),`add postinstall restore hook to package.json`))}else await addCheck({name:`Postinstall restore`,status:`warn`,message:`No package.json found.`});let[Q=0,$=0]=process.versions.node.split(`.`).map(e=>parseInt(e,10));return Q>22||Q===22&&$>=22?await addCheck({name:`Node.js version`,status:`pass`,message:`v${process.versions.node}`}):await addCheck({name:`Node.js version`,status:`fail`,message:`v${process.versions.node}; Knarr requires Node.js >= 22.22`}),{results:n,failures:n.filter(e=>e.status===`fail`).length,warnings:n.filter(e=>e.status===`warn`).length,fixed:n.filter(e=>e.fixed).length,plannedFixes:m?n.reduce((e,t)=>e+t.fixes.length,0):0,dryRun:m}}var R=e({meta:{name:`doctor`,description:`Run diagnostic checks on your Knarr setup`},args:{fix:{type:`boolean`,description:`Apply safe automatic repairs`,default:!1}},async run({args:e}){T();let r=L(`.`);n.info(e.fix?`Running Knarr diagnostics with safe fixes...
|
|
4
|
-
`:`Running Knarr diagnostics...
|
|
5
|
-
`);let i=await runDoctorDiagnostics(r,{fix:e.fix}),a={pass:t.green(`PASS`),fail:t.red(`FAIL`),warn:t.yellow(`WARN`)};for(let e of i.results){n.log(` ${a[e.status]} ${e.name}: ${t.dim(e.message)}`);for(let r of e.fixes)n.log(` ${t.cyan(D()?`PLAN`:`FIX`)} ${t.dim(r)}`);e.unfixableReason&&n.log(` ${t.yellow(`!`)} ${t.dim(e.unfixableReason)}`)}n.log(``),i.plannedFixes>0?n.info(`${i.plannedFixes} fix(es) would be applied`):i.fixed>0&&n.success(`Applied ${i.fixed} fix(es)`),i.failures>0?n.error(`${i.failures} issue(s) found that need attention`):i.warnings>0?n.warn(`${i.warnings} warning(s), but no critical issues`):n.success(`All checks passed!`),E(i),e.fix&&D()&&!O()&&k()}});async function findStaleRegistryEntries(e){let t=0,n=0,i=0;for(let[a,o]of Object.entries(e))for(let e of o){if(!await p(e)){t++;continue}let{state:o,reliable:s}=await r(e);s?o.links[a]||n++:i++}return{missingDirectories:t,missingLinks:n,unreadableConsumers:i}}async function gitignoreIncludesKnarr(e){try{return(await N(e,`utf-8`)).split(`
|
|
6
|
-
`).some(e=>{let t=e.trim();return t===`.knarr/`||t===`.knarr`||t===`/.knarr/`||t===`/.knarr`})}catch{return!1}}async function pathKind(e){try{return(await P(e)).isDirectory()?`dir`:`file`}catch(e){return m(e)&&e.code===`ENOENT`?`missing`:`file`}}async function canVerifyKnarrForPostinstall(e,t,n){return w(n)||declaresKnarrDependency(t)?!0:await p(I(e,`node_modules`,`.bin`,`knarr`))||await p(I(e,`node_modules`,`.bin`,`knarr.cmd`))}function declaresKnarrDependency(e){return e?[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`].some(t=>j(e,t)?.knarr!==void 0):!1}async function readJsonFile(e){try{return await A(e)}catch{return null}}export{R as default};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{r as e}from"./logger-9C6B9Na8.mjs";import{t}from"./console-CIiXr7ge.mjs";import{homedir as n}from"node:os";import{isAbsolute as r,relative as i,sep as a}from"node:path";function displayMutationPath(e,t=process.cwd(),o=n()){let inside=t=>{let n=i(t,e);return n!==``&&!n.startsWith(`..`)&&!r(n)?n:n===``?`.`:null},s=inside(t);if(s!==null)return s;let c=inside(o);return c===null?e:c===`.`?`~`:`~${a}${c}`}const o=[];let s=!1;function recordMutation(e){o.push(e)}function getMutations(){return[...o]}function markDryRunJsonReportPrinted(){s=!0}function printDryRunReport(){if(o.length===0){t.info(`[dry-run] No mutations would be performed`);return}if(e()){if(s)return;console.log(JSON.stringify({dryRun:!0,mutations:o},null,2)),s=!0;return}let n=/* @__PURE__ */ new Map;for(let e of o){let t=n.get(e.type);t||(t=[],n.set(e.type,t)),t.push(e)}t.info(`\n[dry-run] ${o.length} mutation(s) would be performed:\n`);let r={copy:`Copy`,remove:`Remove`,move:`Move`,mkdir:`Create directory`,write:`Write file`,"bin-link":`Create bin link`,"bin-unlink":`Remove bin link`,"cache-invalidate":`Invalidate cache`,"lock-skip":`Skip lock`,"lifecycle-skip":`Skip lifecycle hook`,"command-skip":`Skip command`};for(let[e,i]of n){t.info(` ${r[e]} (${i.length}):`);for(let e of i.slice(0,20)){let n=e.dest?` → ${displayMutationPath(e.dest)}`:``,r=e.detail?` (${e.detail})`:``;t.info(` ${displayMutationPath(e.path)}${n}${r}`)}i.length>20&&t.info(` ... and ${i.length-20} more`)}}export{recordMutation as i,markDryRunJsonReportPrinted as n,printDryRunReport as r,getMutations as t};
|
package/dist/errors-BlOfexcH.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{n as e,t}from"./console-CIiXr7ge.mjs";const n=[{pattern:/not found in store/i,message:`Run 'knarr publish' in the package directory first, or use --from <path>.`},{pattern:/is not linked/i,message:`Run 'knarr add <package>' to link it first.`},{pattern:/No package\.json/i,message:`Make sure you're in a valid package directory with a package.json.`},{pattern:/missing 'name'/i,message:`Add a 'name' field to your package.json.`},{pattern:/missing 'version'/i,message:`Add a 'version' field to your package.json.`},{pattern:/store entry missing/i,message:`Re-publish the package with 'knarr publish'.`},{pattern:/EACCES|EPERM/i,message:`Permission denied. Try running with elevated privileges or check file ownership.`},{pattern:/ENOSPC/i,message:`Disk is full. Free up some space and try again.`},{pattern:/No publishable files/i,message:`Check the 'files' field in package.json, or ensure the build output exists.`},{pattern:/private.*package/i,message:`Use --private flag to publish private packages.`},{pattern:/Failed to read store entry/i,message:`The store may be corrupted. Try 'knarr clean' then re-publish.`},{pattern:/Failed to acquire lock/i,message:`Another Knarr process may be running. Wait or delete stale .lk directories.`},{pattern:/not a directory/i,message:`Check that the path exists and is a directory.`},{pattern:/timed out/i,message:`Set KNARR_HOOK_TIMEOUT to a higher value (in ms) if your scripts need more time.`},{pattern:/state.*corrupt|corrupt.*state/i,message:`Delete .knarr/state.json and re-run 'knarr add' for each package.`},{pattern:/EBUSY/i,message:`A file is locked by another process (e.g. dev server). Stop the process and retry.`},{pattern:/Invalid package name/i,message:`Package names must be non-empty. Use format: package-name or @scope/package-name.`}];function errorWithSuggestion(r){t.error(r);for(let{pattern:i,message:a}of n)if(i.test(r)){t.info(`${e.dim(`Suggestion:`)} ${a}`);break}}export{errorWithSuggestion as t};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t,t as n}from"./console-CIiXr7ge.mjs";import{n as r,t as i}from"./store-DjPdOKqg.mjs";import{o as a}from"./injector-nt40JxVt.mjs";import{c as o,l as s}from"./tracker-B3Fqx94J.mjs";import{t as c}from"./package-manager-DJ8CE0zL.mjs";import{D as l,c as u,g as d,x as f}from"./fs-CPnWm9CR.mjs";import{n as p,t as m}from"./output-BxR2v-jn.mjs";import{c as h,l as g}from"./json-DbSkpxtr.mjs";import{join as _,resolve as v}from"node:path";async function explainState(e,t){let{state:n,reliable:r}=await o(e),i=(await c(e)).resolve().packageManager;if(!r)return{consumerPath:e,stateReliable:!1,packages:t?[await explainPackage(e,t,null,i,!1)]:[]};let a=t?[[t,n.links[t]??null]]:Object.entries(n.links);return{consumerPath:e,stateReliable:!0,packages:await Promise.all(a.map(([t,n])=>explainPackage(e,t,n,i,!0)))}}var y=e({meta:{name:`explain`,description:`Explain linked package state and suggested recovery actions`},args:{package:{type:`positional`,description:`Package name to explain (default: all linked packages)`,required:!1}},async run({args:e}){p();let r=await explainState(v(`.`),e.package);if(!r.stateReliable)n.error(`Consumer state is corrupt or unreadable`),n.info(`Delete .knarr/state.json and re-run 'knarr add' for each package.`);else if(!r.packages[0])n.info(`No linked packages in this project`);else if(e.package)renderDetailed(r.packages[0]);else{n.info(`Linked packages (${r.packages.length}):\n`);for(let e of r.packages){let r=e.status===`ok`?t.green(`OK`):e.status===`warn`?t.yellow(`!`):t.red(`FAIL`),i=e.version?t.dim(`@${e.version}`):t.dim(`(not linked)`),a=e.buildId?t.dim(` [${e.buildId}]`):``;n.log(` ${r} ${t.cyan(e.name)} ${i}${a}`),n.log(` ${t.dim(e.summary)}`)}n.log(``),n.info(`Run ${t.cyan(`knarr explain <package>`)} for details.`)}m(r)}});async function explainPackage(e,t,n,c,p){let m=n?await r(t,n.version):await i(t),h=(await s())[t]??[],g=l(e),_=[];p||_.push(`consumer state is corrupt or unreadable`),n||_.push(`package is not linked in this project`);let v=n?.sourcePath??m?.meta.sourcePath??null,y=v?await u(v):null;v&&y===!1&&_.push(`source directory missing: ${v}`),m?n&&m.meta.contentHash!==n.contentHash&&_.push(`store has newer content than the current link`):_.push(n?`store entry missing for ${t}@${n.version}`:`package not found in store`);let b=f(e,t),x=n?await a(e,t,n.packageManager,n.version,{warnOnFallback:!1}):b,S=await u(x),C=S?await readPackageVersion(x):null;n&&!S?_.push(`package is missing from node_modules`):n&&C&&C!==n.version&&_.push(`node_modules has v${C} but link expects v${n.version}`);let w=n?d(e,t):null,T=w?await u(w):!1;n?.backupExists&&!T&&_.push(`backup is recorded but missing on disk`);let E=await Promise.all(h.map(async e=>{if(!await u(e))return{path:e,exists:!1,stateReliable:null,hasLink:null};let{state:n,reliable:r}=await o(e);return{path:e,exists:!0,stateReliable:r,hasLink:r?!!n.links[t]:null}}));return n&&!h.includes(g)&&_.push(`current project is not registered for pushes`),{name:t,status:_.some(e=>e.includes(`corrupt`)||e.includes(`missing from node_modules`)||e.includes(`store entry missing`)||e.includes(`not linked`))?`fail`:_.length>0?`warn`:`ok`,summary:summarize(t,n,_),suggestedAction:suggestAction(t,n,_,v),linked:!!n,version:n?.version??m?.version??null,buildId:n?.buildId||m?.meta.buildId||null,sourcePath:v,sourceExists:y,packageManager:n?.packageManager??c,store:{exists:!!m,path:m?.packageDir??null,contentHash:m?.meta.contentHash??null,matchesLink:n&&m?m.meta.contentHash===n.contentHash:null,publishedAt:m?.meta.publishedAt??null},nodeModules:{path:b,targetPath:x,exists:S,packageVersion:C},backup:{expected:n?.backupExists??!1,exists:T,path:w},consumers:E,issues:_}}function renderDetailed(e){let r=e.status===`ok`?t.green(`OK`):e.status===`warn`?t.yellow(`WARN`):t.red(`FAIL`);if(n.info(`${r} ${t.cyan(e.name)} ${t.dim(e.summary)}\n`),n.log(` Version: ${e.version??`(not linked)`}`),n.log(` Build ID: ${e.buildId??`(none)`}`),n.log(` Package manager: ${e.packageManager}`),n.log(` Source: ${e.sourcePath??`(unknown)`}${e.sourceExists===!1?` (missing)`:``}`),n.log(` Store: ${e.store.exists?e.store.path:`(missing)`}`),e.store.matchesLink!==null&&n.log(` Content hash: ${e.store.matchesLink?`matches link`:`differs from link`}`),n.log(` node_modules: ${e.nodeModules.targetPath}${e.nodeModules.exists?``:` (missing)`}`),n.log(` Backup: ${e.backup.expected?e.backup.exists?`present`:`missing`:`not recorded`}`),n.log(` Registered consumers: ${e.consumers.length}`),e.issues.length>0){n.log(``);for(let r of e.issues)n.log(` ${t.yellow(`!`)} ${r}`)}n.log(``),n.info(`Suggested action: ${e.suggestedAction}`)}function summarize(e,t,n){return t?n.length===0?`link, store, and node_modules are in sync`:n[0]??`link, store, and node_modules are in sync`:`${e} is not linked in this project`}function suggestAction(e,t,n,r){return n.some(e=>e.includes(`corrupt`))?`Delete .knarr/state.json and re-run 'knarr add' for each package.`:t?n.some(e=>e.includes(`store entry missing`))?r?`Run 'knarr publish' in ${r}, then 'knarr restore'.`:`Re-publish the package, then run 'knarr restore'.`:n.some(e=>e.includes(`newer content`))?`Run 'knarr update ${e}'.`:n.some(e=>e.includes(`node_modules`))?`Run 'knarr restore'.`:n.some(e=>e.includes(`not registered`))?`Run 'knarr add ${e}' again to refresh registration.`:n.some(e=>e.includes(`source directory`))?`Check the source path or re-run 'knarr use <path>'.`:`No action needed.`:`Run 'knarr add ${e}' or 'knarr use <path>'.`}async function readPackageVersion(e){try{let t=await h(_(e,`package.json`));return g(t,`version`)??null}catch{return null}}export{y as default};
|
package/dist/format-DRqD29u-.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";function formatBytes(e){if(e===0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1),r=e/1024**n;return n===0?`${e} B`:`${r.toFixed(1)} ${t[n]}`}export{formatBytes as t};
|
package/dist/fs-C4juVCTd.mjs
DELETED
package/dist/fs-CPnWm9CR.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{i as e,n as t}from"./logger-9C6B9Na8.mjs";import{t as n}from"./console-CIiXr7ge.mjs";import{a as r,s as i,u as a}from"./json-DbSkpxtr.mjs";import{i as o}from"./dry-run-BkdMYSIx.mjs";import{availableParallelism as s,homedir as c}from"node:os";import{constants as l,copyFile as u,cp as d,lstat as f,mkdir as p,readFile as m,readdir as h,realpath as g,rename as _,rm as v,stat as y,symlink as b,writeFile as x}from"node:fs/promises";import{dirname as S,isAbsolute as C,join as w,parse as T,relative as E,resolve as D}from"node:path";import{createHash as O,randomUUID as k}from"node:crypto";import{setTimeout as A}from"node:timers/promises";const j=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,M=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,N=/[\x00-\x1F\x7F]/;function validatePackageName(e){if(!e||e.length>214||N.test(e)||e.includes(`\\`)||e.includes(`//`)||e.split(`/`).some(e=>e===`.`||e===`..`)||!j.test(e))throw Error(`Invalid package name "${e}"`)}function validatePackageVersion(e){if(!e||N.test(e)||e.includes(`/`)||e.includes(`\\`)||e.includes(`..`)||!M.test(e))throw Error(`Invalid package version "${e}"`)}function validatePackageIdentity(e,t){validatePackageName(e),validatePackageVersion(t)}function isKnarrMeta(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.contentHash==`string`&&typeof t.publishedAt==`string`&&typeof t.sourcePath==`string`&&(t.buildId===void 0||typeof t.buildId==`string`)&&(t.schemaVersion===void 0||typeof t.schemaVersion==`number`)}function isLinkEntry(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.version==`string`&&typeof t.contentHash==`string`&&typeof t.linkedAt==`string`&&typeof t.sourcePath==`string`&&typeof t.backupExists==`boolean`&&typeof t.packageManager==`string`&&[`npm`,`pnpm`,`yarn`,`bun`].includes(t.packageManager)&&(t.buildId===void 0||typeof t.buildId==`string`)}function parseConsumerState(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.version!==`1`||typeof t.links!=`object`||t.links===null)return null;let n=r();for(let[e,r]of Object.entries(t.links)){if(!isLinkEntry(r))return null;n[e]=r}return{...t,links:n}}async function warnVersionMismatch(e,t,r){try{let o=await m(w(e,`package.json`),`utf-8`),s=i(o,`package.json`),c=a(s,`dependencies`)[t]??a(s,`devDependencies`)[t]??a(s,`peerDependencies`)[t];if(!c||/^(workspace:|catalog:|\*)/.test(c))return;let l=c.match(/(\d+)\.\d+\.\d+/);if(!l?.[1])return;parseInt(l[1],10)!==parseInt(r.split(`.`)[0]??``,10)&&n.warn(`Version mismatch: store has ${t}@${r} but your package.json declares "${c}". Consider updating your dependency range.`)}catch{}}function parseConsumersRegistry(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=r();for(let[n,r]of Object.entries(e)){if(!Array.isArray(r)||!r.every(e=>typeof e==`string`))return null;t[n]=r}return t}function assertInside(e,t,n){let r=D(e),i=D(t),a=E(r,i);if(a!==``&&(a.startsWith(`..`)||C(a)))throw Error(`${n} escapes expected directory: ${t}`)}function getKnarrHome(){return process.env.KNARR_HOME||w(c(),`.knarr`)}function getStorePath(){return w(getKnarrHome(),`store`)}function getConsumersPath(){return w(getKnarrHome(),`consumers.json`)}function encodePackageName(e){return validatePackageName(e),e.replace(/\//g,`+`)}function decodePackageName(e){if(e.startsWith(`@`)){let t=e.indexOf(`+`);if(t!==-1)return e.slice(0,t)+`/`+e.slice(t+1)}return e}function getStoreEntryPath(e,t){validatePackageIdentity(e,t);let n=getStorePath(),r=w(n,`${encodePackageName(e)}@${t}`);return assertInside(n,r,`Store entry path`),r}function getStorePackagePath(e,t){return w(getStoreEntryPath(e,t),`package`)}function getStoreMetaPath(e,t){return w(getStoreEntryPath(e,t),`.knarr-meta.json`)}function getStoreHistoryPath(e,t){return w(getStoreEntryPath(e,t),`history`)}function getHistoryEntryPath(e,t,n){if(!/^[a-f0-9]{8,64}$/i.test(n))throw Error(`Invalid build id "${n}"`);return w(getStoreHistoryPath(e,t),n)}function getConsumerKnarrDir(e){return w(e,`.knarr`)}function getConsumerStatePath(e){return w(e,`.knarr`,`state.json`)}function getConsumerBackupPath(e,t){validatePackageName(t);let n=w(e,`.knarr`,`backups`),r=w(n,encodePackageName(t));return assertInside(n,r,`Backup path`),r}function normalizePath(e){return e.replace(/\\/g,`/`)}function getNodeModulesPackagePath(e,t){validatePackageName(t);let n=w(e,`node_modules`),r=w(n,t);return assertInside(n,r,`node_modules package path`),r}function pLimit(e){let t=0,n=[],r=0,next=()=>{let i=t<e?n[r]:void 0;i&&(r++,t++,i()),r>0&&r===n.length&&(n.length=0,r=0)};return r=>new Promise((i,a)=>{let run=()=>{r().then(e=>{t--,i(e),next()},e=>{t--,a(e),next()})};t<e?(t++,run()):n.push(run)})}let P=null;function getXXHash(){return P||=import(`./xxhash-wasm-D_QjdUuv.mjs`).then(e=>e.default()).catch(e=>{throw P=null,e}),P}const F=pLimit(Math.max(s(),8));async function computeContentHash(t,n,r=/* @__PURE__ */ new Map){let i=new Map(t.map(e=>[normalizePath(E(n,e)),e]));for(let e of r.keys())i.has(e)||i.set(e,w(n,e));let a=[...i.entries()].sort(([e],[t])=>e.localeCompare(t)),o=await Promise.all(a.map(([e,t])=>F(async()=>{let n=r.get(e);return n===void 0?{rel:e,content:await m(t)}:{rel:e,content:Buffer.isBuffer(n)?n:Buffer.from(n)}})));e(`[hash] Computing content hash for ${a.length} files`);let s=O(`sha256`),c=Buffer.alloc(4);for(let{rel:e,content:t}of o)s.update(e),s.update(`\0`),c.writeUInt32LE(t.length),s.update(c),s.update(t);let l=`sha256v2:`+s.digest(`hex`);return e(`[hash] Result: ${l.slice(0,20)}...`),l}async function hashFile(e,t){let n=t??(await y(e)).size,r=await getXXHash();if(n>1048576)return hashFileStream(e,r);let i=await m(e);return r.h64Raw(i).toString(16)}async function hashFileStream(e,t){let{createReadStream:n}=await import(`node:fs`),r=t.create64();return new Promise((t,i)=>{let a=n(e);a.on(`data`,e=>r.update(e)),a.on(`end`,()=>t(r.digest().toString(16))),a.on(`error`,i)})}const I=pLimit(Math.max(s(),8));function isNodeError(e){return e instanceof Error&&`code`in e}const L=/* @__PURE__ */ new Map;function volumeRoot(e){let{root:t}=T(e);return t||`/`}async function copyWithCoW(n,r,i){if(t()){e(`[dry-run] would copy ${n} → ${r}`),o({type:`copy`,path:n,dest:r});return}i?.ensureParent!==!1&&await p(S(r),{recursive:!0});let a=`${r}${R}${process.pid}-${k()}`;try{await copyToFreshFile(n,a,volumeRoot(r)),await renameOverLockedTarget(a,r)}catch(e){throw await v(a,{force:!0}),e}}const R=`.knarr-tmp-`,z=/\.knarr-tmp-(\d+)-[0-9a-f-]{36}$/;function isInFlightCopyTemp(e){let t=z.exec(e)?.[1];if(t===void 0)return!1;try{return process.kill(Number(t),0),!0}catch(e){return isNodeError(e)&&e.code===`EPERM`}}const B=[10,20,40,80,160,300,400],V=/* @__PURE__ */ new Set([`EPERM`,`EACCES`,`EBUSY`]);async function renameOverLockedTarget(e,t){for(let n of B)try{await _(e,t);return}catch(e){if(process.platform!==`win32`||!isNodeError(e)||!V.has(e.code??``))throw e;await A(n)}await _(e,t)}async function copyToFreshFile(t,n,r){let i=L.get(r);if(i===!1)await u(t,n);else if(i===!0)await u(t,n,l.COPYFILE_FICLONE);else try{await u(t,n,l.COPYFILE_FICLONE_FORCE),L.set(r,!0)}catch{L.set(r,!1),e(`[copy] reflink not supported on ${r}, using plain copy`),await u(t,n)}}async function collectFiles(e){return(await h(e,{recursive:!0,withFileTypes:!0})).filter(e=>e.isFile()).map(e=>w(e.parentPath,e.name))}async function removeDestinationConflicts(e,n){let r=n.split(/[\\/]/).filter(Boolean),i=e;for(let[e,n]of r.entries()){i=w(i,n);try{let n=await y(i),a=e===r.length-1;if(n.isDirectory()){a&&(t()?o({type:`remove`,path:i}):await v(i,{recursive:!0,force:!0}));continue}if(!a){if(t()){o({type:`remove`,path:i});return}await v(i,{force:!0})}}catch(e){if(isNodeError(e)&&e.code===`ENOENT`)return;throw e}}}async function incrementalCopy(n,r,i={}){let a=collectFiles(n),s=collectFiles(r).catch(e=>{if(isNodeError(e)&&e.code===`ENOENT`)return[];throw e}),[c,l]=await Promise.all([a,s]),u=0,d=0,f=await Promise.all(c.map(t=>I(async()=>{let a=E(n,t),o=w(r,a),s=!0;if(i.force)e(`[copy] ${a} (forced)`);else try{let[n,r]=await Promise.all([y(t),y(o)]);if(n.size!==r.size)e(`[copy] ${a} (size differs: ${n.size} vs ${r.size})`);else{let[i,c]=await Promise.all([hashFile(t,n.size),hashFile(o,r.size)]);i===c?(s=!1,e(`[skip] ${a} (unchanged)`)):e(`[copy] ${a} (hash differs)`)}}catch(t){if(isNodeError(t)&&(t.code===`ENOENT`||t.code===`ENOTDIR`))e(`[copy] ${a} (new file)`);else throw t}return s?(await removeDestinationConflicts(r,a),await copyWithCoW(t,o),`copied`):`skipped`})));for(let e of f)e===`copied`?u++:d++;let p=new Set(c.map(e=>E(n,e))),m=l.filter(e=>!p.has(E(r,e))&&!isInFlightCopyTemp(e));await Promise.all(m.map(n=>I(async()=>{e(`[remove] ${E(r,n)} (no longer in source)`),t()?o({type:`remove`,path:n}):await v(n,{force:!0}).catch(e=>{if(!isNodeError(e)||e.code!==`ENOENT`&&e.code!==`ENOTDIR`&&e.code!==`EISDIR`&&e.code!==`ERR_FS_EISDIR`)throw e})})));let h=m.length;return{copied:u,removed:h,skipped:d}}async function moveDir(n,r){if(t())e(`[dry-run] would move ${n} → ${r}`),o({type:`move`,path:n,dest:r});else try{await _(n,r)}catch(e){if(isNodeError(e)&&e.code===`EXDEV`)await d(n,r,{recursive:!0}),await v(n,{recursive:!0,force:!0});else throw e}}async function removeDir(n){t()?(e(`[dry-run] would remove ${n}`),o({type:`remove`,path:n})):await v(n,{recursive:!0,force:!0})}async function ensureDir(n){t()?(e(`[dry-run] would ensure dir ${n}`),o({type:`mkdir`,path:n})):await p(n,{recursive:!0})}async function ensurePrivateDir(n){t()?(e(`[dry-run] would ensure private dir ${n}`),o({type:`mkdir`,path:n})):await p(n,{recursive:!0,mode:448})}async function exists(e){try{return await y(e),!0}catch{return!1}}async function atomicWriteFile(n,r){if(t()){e(`[dry-run] would write ${n}`),o({type:`write`,path:n});return}let i=`${n}.tmp-${process.pid}-${k()}`;try{await x(i,r),await _(i,n)}catch(e){throw await v(i,{force:!0}),e}}async function dirSize(e){try{let t=await collectFiles(e);return(await Promise.all(t.map(e=>y(e).then(e=>e.size).catch(()=>0)))).reduce((e,t)=>e+t,0)}catch{return 0}}async function copyDir(n,r){if(t())e(`[dry-run] would copy directory ${n} → ${r}`),o({type:`copy`,path:n,dest:r});else try{await d(n,r,{recursive:!0})}catch(e){if(process.platform!==`win32`||!isNodeError(e)||e.code!==`EPERM`||e.syscall!==`symlink`||!(await f(n)).isSymbolicLink())throw e;let t=await g(n);if(!(await y(t)).isDirectory())throw e;await p(S(r),{recursive:!0}),await b(t,r,`junction`)}}export{parseConsumersRegistry as A,getStoreHistoryPath as C,normalizePath as D,getStorePath as E,validatePackageName as M,validatePackageVersion as N,isKnarrMeta as O,warnVersionMismatch as P,getStoreEntryPath as S,getStorePackagePath as T,getConsumerKnarrDir as _,dirSize as a,getHistoryEntryPath as b,exists as c,moveDir as d,removeDir as f,getConsumerBackupPath as g,decodePackageName as h,copyWithCoW as i,validatePackageIdentity as j,parseConsumerState as k,incrementalCopy as l,pLimit as m,collectFiles as n,ensureDir as o,computeContentHash as p,copyDir as r,ensurePrivateDir as s,atomicWriteFile as t,isNodeError as u,getConsumerStatePath as v,getStoreMetaPath as w,getNodeModulesPackagePath as x,getConsumersPath as y};
|