openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 50.1 kB
JavaScript
import{C as e,F as t,I as n,L as r,M as i,P as a,R as o,S as s,_ as c,b as l,c as u,d,f,k as p,o as m,p as h,v as g,x as _,y as v}from"./openclaw-state-read-read-open-flags-CtNL1rJs.mjs";import{createRequire as y}from"node:module";import b,{closeSync as x,openSync as S,readSync as C,readdirSync as ee}from"node:fs";import w from"node:path";import T from"node:fs/promises";import te,{platform as E}from"node:os";import{createHash as D}from"node:crypto";import{AsyncLocalStorage as O}from"node:async_hooks";import{getSystemErrorName as k}from"node:util";function captureNativeFdClose(e){if(typeof e.closeOwnedFd!=`function`)throw new o(`helper-unavailable`,`native descriptor ownership is unavailable`);return e.closeOwnedFd.bind(e)}let A={};function parseMode(e){if(!e)return;let t=e.trim().toLowerCase();if(t===`0`||t===`false`||t===`off`||t===`never`)return`off`;if(t===`1`||t===`true`||t===`on`||t===`auto`)return`auto`;if(t===`required`||t===`require`)return`require`}function rejectLegacyMode(){for(let e of[`FS_SAFE_PYTHON_MODE`,`OPENCLAW_FS_SAFE_PYTHON_MODE`]){if(process.env[e]===void 0)continue;let t=parseMode(process.env[e])??`auto`;throw Error(`${e} has been removed. Set FS_SAFE_NATIVE_MODE=${t} or configureFsSafeNative({ mode: "${t}" }) before using fs-safe, then remove ${e}. Legacy mode settings no longer select native policy.`)}return`auto`}function getFsSafeNativeConfig(){return{mode:A.mode??parseMode(process.env.FS_SAFE_NATIVE_MODE)??parseMode(process.env.OPENCLAW_FS_SAFE_NATIVE_MODE)??rejectLegacyMode()}}function getNativeModeSetting(){if(A.mode!==void 0)return{mode:A.mode,source:`programmatic configuration`};for(let e of[`FS_SAFE_NATIVE_MODE`,`OPENCLAW_FS_SAFE_NATIVE_MODE`]){let t=parseMode(process.env[e]);if(t!==void 0)return{mode:t,source:e}}return{mode:rejectLegacyMode(),source:`default`}}function isFsSafeNativeRequired(){return(A.mode??parseMode(process.env.FS_SAFE_NATIVE_MODE)??parseMode(process.env.OPENCLAW_FS_SAFE_NATIVE_MODE)??rejectLegacyMode())===`require`}const j=y(new URL(`dist/native.js`,import.meta.resolve(`@openclaw/fs-safe/package.json`)).href),ne=O.snapshot();let M,N,P=!1,F=loadBundledBinding,resolvePackage=e=>j.resolve(e),I={reason:`not-probed`},L,R;function loadFailure(e,t){try{return classifyLoadFailure(e,t)}catch{return{reason:`load-failed`,code:`UNKNOWN`}}}function classifyLoadFailure(e,t){let n=typeof e==`object`&&e&&`code`in e?e.code:void 0;if(n===`MODULE_NOT_FOUND`&&e instanceof Error&&e.message.split(`
`,1)[0]===`Cannot find module '${t}'`)try{resolvePackage(t)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`MODULE_NOT_FOUND`&&e.message.split(`
`,1)[0]===`Cannot find module '${t}'`)return{reason:`package-missing`}}return{reason:`load-failed`,code:typeof n==`string`&&[`ERR_DLOPEN_FAILED`,`MODULE_NOT_FOUND`,`ERR_MODULE_NOT_FOUND`,`ERR_PACKAGE_PATH_NOT_EXPORTED`,`ERR_INVALID_PACKAGE_CONFIG`,`EACCES`,`EPERM`,`ENOENT`].includes(n)?n:`UNKNOWN`}}function getNativeFallbackDiagnostic(...e){let t=getNativeModeSetting(),n=R===void 0?bundledTarget():L,r=n===void 0?void 0:nativePackageForTarget(n),i=j("@openclaw/fs-safe/package.json"),a={target:R,packageName:r,packageVersion:r===void 0?void 0:i.optionalDependencies[r]};if(t.mode===`off`)return{...a,reason:`disabled`,source:t.source};let o=M;if(o){let t=e.filter(e=>typeof o[e]!=`function`);if(t.length)return{...a,reason:`capability-missing`,capabilities:t}}return{...a,...I}}function isMuslFilename(e){return e.includes(`libc.musl-`)||e.includes(`ld-musl-`)}function isMuslFromReport(){try{if(!process.report||typeof process.report.getReport!=`function`)return;let e=process.report.getReport();if(e.header?.glibcVersionRuntime)return!1;if(e.sharedObjects?.some(isMuslFilename))return!0}catch{}}function isMuslFromFilesystem(){for(let e of[`/lib`,`/usr/lib`])try{if(ee(e).some(isMuslFilename))return!0}catch{}}function readUInt(e,t,n,r){if(t<0||t+n>e.length)return;if(n===2)return r?e.readUInt16LE(t):e.readUInt16BE(t);if(n===4)return r?e.readUInt32LE(t):e.readUInt32BE(t);let i=r?e.readBigUInt64LE(t):e.readBigUInt64BE(t);return i<=BigInt(2**53-1)?Number(i):void 0}function isMuslFromElfInterpreter(){let e;try{e=S(process.execPath,`r`);let t=Buffer.alloc(64);if(C(e,t,0,t.length,0)<52||!t.subarray(0,4).equals(Buffer.from([127,69,76,70])))return;let n=t[4],r=t[5];if(n!==1&&n!==2||r!==1&&r!==2)return;let i=r===1,a=n===2,o=readUInt(t,a?32:28,a?8:4,i),s=readUInt(t,a?54:42,2,i),c=readUInt(t,a?56:44,2,i);if(o===void 0||s===void 0||c===void 0||s<(a?56:32)||c>1024)return;let l=Buffer.alloc(s);for(let t=0;t<c;t+=1){let n=o+t*s;if(C(e,l,0,s,n)!==s)return;if(readUInt(l,0,4,i)!==3)continue;let r=readUInt(l,a?8:4,a?8:4,i),c=readUInt(l,a?32:16,a?8:4,i);if(r===void 0||c===void 0||c<1||c>4096)return;let u=Buffer.alloc(c);return C(e,u,0,c,r)===c?isMuslFilename(u.toString(`utf8`)):void 0}}catch{return}finally{if(e!==void 0)try{x(e)}catch{}}}function isMusl(){if(process.platform!==`linux`)return!1;for(let e of[isMuslFromReport,isMuslFromElfInterpreter,isMuslFromFilesystem]){let t=e();if(t!==void 0)return t}return!1}function targetFor(e,t,n){if(e===`win32`&&(t===`x64`||t===`arm64`))return`win32-${t}-msvc`;if(e===`darwin`&&t===`x64`)return`darwin-x64`;if(e===`darwin`&&t===`arm64`)return`darwin-arm64`;if(e===`freebsd`&&(t===`x64`||t===`arm64`))return`freebsd-${t}`;if(e===`linux`&&(t===`x64`||t===`arm64`))return`linux-${t}-${n?`musl`:`gnu`}`}function bundledTarget(){let e=isMusl();return L=targetFor(process.platform,process.arch,e),R=L??`${process.platform}-${process.arch}${process.platform===`linux`?`-${e?`musl`:`gnu`}`:``}`,L}function nativePackageForTarget(e){return`@openclaw/fs-safe-${e}`}function loadBundledBinding(){let e=bundledTarget();if(!e)throw I={reason:`unsupported-target`},Error(`Unsupported OS or architecture: ${process.platform}-${process.arch}`);let t=ne(()=>j(nativePackageForTarget(e)));return typeof t.closeOwnedFd!=`function`&&(I={reason:`capability-missing`,capabilities:[`closeOwnedFd`]}),captureNativeFdClose(t),t}function selectNativeBinding(e,...t){if(!e)return;let n=t.filter(t=>typeof e[t]!=`function`);if(n.length===0)return e;if(getFsSafeNativeConfig().mode===`require`)throw new o(`helper-unavailable`,`native fs-safe capabilities unavailable: ${n.join(`, `)}`)}function assertNativeCapabilities(e,...t){let n=t.filter(t=>typeof e[t]!=`function`);if(n.length)throw new o(`helper-unavailable`,`native fs-safe capabilities unavailable: ${n.join(`, `)}`)}function getNativeBinding(...e){let{mode:t}=getFsSafeNativeConfig();if(t!==`off`){if(!P){P=!0;try{let e=F();typeof e.closeOwnedFd!=`function`&&(I={reason:`capability-missing`,capabilities:[`closeOwnedFd`]}),captureNativeFdClose(e),M=e,I={reason:`loaded`}}catch(e){N=e,I.reason===`not-probed`&&(L??=bundledTarget(),I=loadFailure(e,nativePackageForTarget(L??`${process.platform}-${process.arch}`)))}}if(M)return selectNativeBinding(M,...e);if(t===`require`)throw new o(`helper-unavailable`,`native fs-safe helper is unavailable`,{cause:N})}}function requireNativeBinding(...e){let t=getNativeBinding(...e);if(!t)throw new o(`helper-unavailable`,`native fs-safe helper is unavailable`,{cause:N});return t}function isWindowsAppContainer(e){if(e.isWindowsAppContainer)try{let t=e.isWindowsAppContainer();if(typeof t!=`boolean`)throw Error(`Invalid AppContainer membership`);return t}catch(e){throw new o(`permission-unverified`,`Windows process token membership could not be verified`,{cause:e})}}function assertWindowsHelperAllowed(){if(process.platform!==`win32`)return;let e=getNativeBinding();if(e&&isWindowsAppContainer(e))throw new o(`helper-unavailable`,`External Windows security helpers are unavailable inside an AppContainer`)}const z=process.versions.bun?E():void 0,B=z===`darwin`||z===`linux`?z:void 0;function resolve(e,t){if(t&&process.platform===`win32`)try{return b.realpathSync.native(e)}catch(t){if(t.code!==`EPERM`||t.syscall!==`realpath`)throw t;let n;try{n=getNativeBinding()}catch{n=void 0}if(!n||!isWindowsAppContainer(n))throw t;if(!n?.resolveWindowsCanonicalPath)throw new o(`helper-unavailable`,`Windows canonicalization after a denied DOS-name query requires the native binding`,{cause:t});let r;try{r=n.resolveWindowsCanonicalPath(e)}catch(e){throw new o(`path-mismatch`,`Windows canonical path cannot be verified safely`,{cause:e})}if(r===null)throw t;return r}if(B){if(e.includes(`\0`))throw Object.assign(/* @__PURE__ */ TypeError(`realpath input must not contain null bytes`),{code:`ERR_INVALID_ARG_VALUE`});let n=getNativeBinding();if(n?.canonicalizePath){let r=n.canonicalizePath(e,!t);if(r.path!==void 0)return r.path;let i=-r.errno,a=k(i);throw Object.assign(/* @__PURE__ */ Error(`${a}: realpath '${e}'`),{code:a,errno:i,syscall:`realpath`,path:e})}if(getFsSafeNativeConfig().mode===`require`)throw new o(`helper-unavailable`,`native fs-safe canonicalization is unavailable`)}return t?b.realpathSync.native(e):b.realpathSync(e)}const V=Object.assign(e=>resolve(e,!1),{native:e=>resolve(e,!0)});async function realpathNative(e){if(B)return V.native(e);try{return await T.realpath(e)}catch(t){if(process.platform!==`win32`||t.code!==`EPERM`||t.syscall!==`realpath`)throw t;return V.native(e)}}const H=/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/,U=/^[A-Za-z0-9._-]+$/,W=/^[A-Za-z]:(?![\\/])/,G=/(?:^|\/)[A-Za-z]:(?!\\)/;function isDriveRelativePath(e){return W.test(e)}function assertNoDriveRelativePathSegments(e,t){if(G.test(e))throw new o(`invalid-path`,`${t} must not contain a drive letter`);return e}function isSafePathSegment(e,t={}){return e!==``&&e!==`.`&&e!==`..`&&!e.includes(`/`)&&!e.includes(`\\`)&&!e.includes(`\0`)&&!p(e)&&(t.allowDotPrefix===!0||!e.startsWith(`.`))&&(t.allowDotPrefix===!0?U.test(e):H.test(e))}function assertSafePathSegment(e,t={}){if(!isSafePathSegment(e,t))throw new o(`invalid-path`,`${t.label??`path segment`} must be a safe path segment`);return e}function assertSafePathPrefix(e,t={}){return e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`)?assertSafePathSegment(e,{allowDotPrefix:!0,...t,label:t.label??`path prefix`}):assertSafePathSegment(e.replace(/[^A-Za-z0-9._-]+/g,`-`),{allowDotPrefix:!0,...t,label:t.label??`path prefix`})}function identityFromReceipt(e){if(`exactIdentity`in e){let t=e.exactIdentity,n=t?.dev,r=t?.ino;return typeof n==`bigint`&&typeof r==`bigint`?{dev:n,ino:r}:{dev:NaN,ino:NaN}}return e}function hasSafeFileIdentity(e){return isExactStatValue(e.dev)&&isExactStatValue(e.ino)}function isExactStatValue(e){return typeof e==`bigint`||Number.isSafeInteger(e)}function isZero(e){return e===0||e===0n}function sameStatValue(e,t){return typeof e==typeof t?e===t:BigInt(e)===BigInt(t)}function isStatValueProvablyDifferent(e,t,n){return sameStatValue(e,t)?!1:n!==`win32`||!isZero(e)&&!isZero(t)}function sha256Hex(e,t){let n=typeof e==`string`?Buffer.from(e,t??`utf8`):e;return D(`sha256`).update(n).digest(`hex`)}function sameFileIdentity(e,t,n=process.platform){e=identityFromReceipt(e),t=identityFromReceipt(t);let r=e.dev,i=e.ino,a=t.dev,o=t.ino;return isExactStatValue(r)&&isExactStatValue(i)&&isExactStatValue(a)&&isExactStatValue(o)&&!isStatValueProvablyDifferent(r,a,n)&&!isStatValueProvablyDifferent(i,o,n)}function sameCleanupStatValue(e,t){return!isExactStatValue(e)||!isExactStatValue(t)?!1:sameStatValue(e,t)}function sameFileIdentityForCleanup(e,t,n=process.platform){if(n!==`win32`)return sameCleanupStatValue(e.dev,t.dev)&&sameCleanupStatValue(e.ino,t.ino);let r=e.dev;if(isZero(r))return!1;let i=e.ino;if(isZero(i))return!1;let a=t.dev;if(isZero(a))return!1;let o=t.ino;return!isZero(o)&&sameCleanupStatValue(r,a)&&sameCleanupStatValue(i,o)}const K=/* @__PURE__ */ new Set([`ENOTEMPTY`,`EEXIST`]),q=/* @__PURE__ */ new Map([[`EACCES`,`permission denied`],[`EPERM`,`permission denied`],[`EROFS`,`read-only filesystem`],[`ENOSPC`,`no space left on device`]]);function fileNotFoundError(e,t){return e===void 0?new o(`not-found`,`file not found`,{details:t}):new o(`not-found`,`file not found`,{cause:e,details:t})}function outsideWorkspaceError(){return new o(`outside-workspace`,`file is outside workspace root`)}function pathTraversalPermissionError(e,t){if(e instanceof o)return e.code===`permission-denied`?e:void 0;if(!g(e,`EACCES`)&&!g(e,`EPERM`))return;let n=v(e)&&typeof e.path==`string`?e.path:t;return new o(`permission-denied`,`permission denied while resolving ${n}`,errorCauseOptions(e))}function rootPathChangedError(e){return new o(`path-mismatch`,`root path changed during operation`,{cause:e})}function directoryComponentNotDirectoryError(e){return e===void 0?new o(`not-file`,`directory component must be a directory`):new o(`not-file`,`directory component must be a directory`,{cause:e})}function hardlinkedPathNotAllowedError(){return new o(`hardlink`,`hardlinked path not allowed`)}function isAlreadyExistsError(e){return g(e,`EEXIST`)||/File exists|EEXIST/i.test(String(e))}function resourceExhaustion(e){let t=[e],n,r,i=/* @__PURE__ */ new Set;for(;t.length;){let e=t.pop();if(!(e instanceof Error)||i.has(e))continue;if(i.add(e),e instanceof o&&e.code!==`helper-failed`&&e.code!==`not-removable`)return;let a=e;e instanceof o&&(!n||e.details?.cleanup)&&(n=e.details??n),a.code===`EMFILE`||a.code===`ENFILE`?r&&r!==`ENOSPC`||(r=a.code):a.code===`ENOSPC`&&(r??=a.code),a.name===`SuppressedError`&&t.push(a.suppressed,a.error),e instanceof AggregateError&&t.push(...e.errors),t.push(e.cause)}if(!r||r===`ENOSPC`&&e instanceof o)return;let a=n?.cleanup,s=n?.publication,c=a?.status===`preserved`&&s?.status===`indeterminate`,l=r===`ENOSPC`?q.get(r):`filesystem write failed: too many open files`;return new o(r===`ENOSPC`?`invalid-path`:`helper-failed`,`${l} (${r})${c?`; publication outcome is indeterminate; staged file preserved`:``}`,{cause:e,details:n})}function normalizePinnedWriteError(e){let t=resourceExhaustion(e);if(t)return t;let n=e,r=/* @__PURE__ */ new Set;try{for(;n instanceof Error&&n.name===`SuppressedError`&&!r.has(n);)r.add(n),n=n.suppressed;if(n!==e&&n instanceof o&&n.details?.phase===`publish`)return new o(n.code,n.message,{cause:e,details:n.details})}catch{}if(e instanceof o)return e;if(l(e))return fileNotFoundError(e instanceof Error?e:void 0);let i=v(e)&&typeof e.code==`string`&&/^E[A-Z0-9_]+$/.test(e.code)?e.code:void 0,a=i?`${q.get(i)??`filesystem write failed`} (${i})`:`path is not a regular file under root`;return new o(`invalid-path`,a,errorCauseOptions(e))}function normalizePinnedPathError(e,t){return e instanceof o?e:new o(`path-alias`,`path is not under root`,{cause:e instanceof Error?e:void 0,details:t})}function normalizeRemoveGuardError(e,t){return e instanceof o?e:l(e)?fileNotFoundError(e instanceof Error?e:void 0,t):normalizePinnedPathError(e,t)}function normalizeRemovePathError(e,t){if(e instanceof o)return e;if(!v(e)||typeof e.code!=`string`)return normalizePinnedPathError(e,t);let n=e instanceof Error?e:void 0;return l(e)?fileNotFoundError(n,t):K.has(e.code)?new o(`not-empty`,`directory is not empty`,{cause:n,details:t}):new o(`not-removable`,`path could not be removed`,{cause:n,details:t})}function errorCauseOptions(e){return{cause:e instanceof Error?e:void 0}}function directoryEntryPath(e,t=process.platform){let n=t===`win32`;if(typeof e==`string`){let t=e[e.length-1];if(t!==`/`&&(!n||t!==`\\`))return e}let r=(n?w.win32:w.posix).parse(e).root.length;if(n&&/^[\\/]{2}[?.][\\/]UNC[\\/]/i.test(e)){let t=w.win32.parse(`\\\\${e.slice(8)}`).root;t.length>1&&(r=Math.max(r,t.length+6))}let i=e.length;for(;i>r&&(e[i-1]===`/`||n&&e[i-1]===`\\`);)i--;return i===r||i===e.length?e:e.slice(0,i)}function safeNumber(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function safeExpected(e){return typeof e.dev==`bigint`&&typeof e.ino==`bigint`&&e.dev>=0n&&e.ino>=0n&&e.dev<=9007199254740991n&&e.ino<=9007199254740991n}function observeStatSync(e,t,n,r=process.platform,i){if(r===`win32`||!n&&t&&!safeExpected(t)){let a=h(()=>{let t=n;return n=void 0,t??e(!0)},t,r);return i?{stat:a,identity:t??{dev:a.dev,ino:a.ino}}:a}let a=n??e(!1),{dev:o,ino:s}=a,c=safeNumber(o),l=safeNumber(s),u=c?BigInt(o):typeof o==`bigint`?o:void 0,f=l?BigInt(s):typeof s==`bigint`?s:void 0;if(t&&(u!==void 0&&u!==t.dev||f!==void 0&&f!==t.ino))throw d();if(c&&l)return i?{stat:a,identity:t??{dev:u,ino:f}}:a;let p=h(()=>{let t=e(!0);if(u!==void 0&&t.dev!==u||f!==void 0&&t.ino!==f)throw d();return t},t,r);return i?{stat:p,identity:t??{dev:p.dev,ino:p.ino}}:p}function inspectStatObservationSync(e,t,n,r=process.platform){return observeStatSync(e,t,n,r,!0)}function assertStatObservationSync(e,t,n,r=process.platform){return observeStatSync(e,t,n,r,!1)}const J=/* @__PURE__ */ new WeakMap;function assertDirectoryIdentitySync(e,t){let n=directoryOperationPath(e),r=t.dev,a=t.ino,s=t.realPath;if(s!==void 0&&i(s,`filesystem`),inspectDirectoryIdentityAtPathSync(n,{dev:r,ino:a}),s===void 0)return;let c=V.native(n);if(i(c,`filesystem`),c!==s)throw new o(`path-mismatch`,`directory changed during operation`)}async function createAsyncDirectoryGuard(e,t){return captureDirectoryGuard(e,`native`,t)}function captureDirectoryGuard(e,t,n){let r=directoryOperationPath(e),a=n?.bigint?inspectDirectoryIdentityAtPathSync(r,void 0,n.initial):b.lstatSync(r);if(a.isSymbolicLink()||!a.isDirectory())throw directoryComponentNotDirectoryError();let o;if(!hasSafeFileIdentity(a)){let e=b.lstatSync(r,{bigint:!0});if(e.isSymbolicLink()||!e.isDirectory())throw directoryComponentNotDirectoryError();o={dev:e.dev,ino:e.ino}}let s=t===`native`?V.native(r):V(r);i(s,`filesystem`);let c={dir:e,realPath:s,stat:a};return o&&J.set(c,o),c}async function assertAsyncDirectoryGuard(e){assertDirectoryGuard(e,`native`)}function assertSyncDirectoryGuard(e){assertDirectoryGuard(e,`normalized`)}function assertDirectoryGuard(e,t){let n=e.dir,r=directoryOperationPath(n),a=e.realPath;i(a,`filesystem`);let s=e.stat,c={dev:s.dev,ino:s.ino},l=J.get(e),u=l??c,d=typeof u.dev==`bigint`&&typeof u.ino==`bigint`?l?b.lstatSync(r,{bigint:!0}):inspectDirectoryIdentityAtPathSync(r,{dev:u.dev,ino:u.ino}):b.lstatSync(r);if(d.isSymbolicLink()||!d.isDirectory())throw directoryComponentNotDirectoryError();if(t===`native`&&!sameFileIdentity(d,u))throw new o(`path-mismatch`,`directory changed during operation`);let f=t===`native`||typeof c.ino==`bigint`?V.native(r):V(r);if(i(f,`filesystem`),t===`normalized`&&!sameFileIdentity(d,u)||f!==a)throw new o(`path-mismatch`,`directory changed during operation`)}async function createNearestExistingDirectoryGuard(e,t,n={bigint:!1}){i(e,`filesystem`),i(t,`filesystem`);let a=r(t),o=r(e);for(;a!==o;)try{return captureDirectoryGuard(a,`native`,n)}catch(e){if(!l(e))throw e;a=w.dirname(a)}return captureDirectoryGuard(o,`native`,n)}async function inspectDirectoryIdentity(e,t){return inspectDirectoryIdentitySync(e,t)}function directoryOperationPath(e){return i(e,`filesystem`),t(directoryEntryPath(e))}function inspectDirectoryIdentitySync(e,t,n,r=process.platform){return inspectDirectoryIdentityAtPathSync(directoryOperationPath(e),t===void 0?void 0:{dev:t.dev,ino:t.ino},n,r)}function inspectDirectoryIdentityAtPathSync(e,t,n,r=process.platform){return h(()=>{let t=n??b.lstatSync(e,{bigint:!0});if(n=void 0,t.isSymbolicLink()||!t.isDirectory())throw directoryComponentNotDirectoryError();return t},t,r)}function extendDirectoryObservationGuard(e,t,n){let r=e;return r.dir=t,r.realPath=n,r}function inspectDirectoryObservationSync(e,t){let n=directoryOperationPath(e);return inspectStatObservationSync(e=>{let t=e?b.lstatSync(n,{bigint:!0}):b.lstatSync(n);if(t.isSymbolicLink()||!t.isDirectory())throw directoryComponentNotDirectoryError();return t},t)}function assertDirectoryObservationSync(e,t){let n=directoryOperationPath(e);return assertStatObservationSync(e=>{let t=e?b.lstatSync(n,{bigint:!0}):b.lstatSync(n);if(t.isSymbolicLink()||!t.isDirectory())throw directoryComponentNotDirectoryError();return t},t)}function assertDirectoryObservationGuardSync(e){let t=e.dir,n=e.realPath;i(n,`filesystem`),assertDirectoryObservationSync(t,e.identity);let r=V.native(directoryOperationPath(t));if(i(r,`filesystem`),r!==n)throw new o(`path-mismatch`,`directory changed during operation`)}const Y=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/gu;function formatErrorDetail(e){return e.replace(Y,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function shortPath(e){let t=te.homedir(),n=t.endsWith(w.sep)?t:`${t}${w.sep}`;return formatErrorDetail(e===t?`~`:e.startsWith(n)?`~${w.sep}${e.slice(n.length)}`:e)}function sameNormalizedPathSpelling(e,t){return w.resolve(e)===w.resolve(t)}function windowsComparisonSpelling(e){return/^\\\\\?\\UNC\\/i.test(e)?`\\\\${e.slice(8)}`:e.startsWith(`\\\\?\\`)?e.slice(4):e}function trimWindowsTrailingSeparators(e){let t=w.win32.parse(e).root.length,n=e.length;for(;n>t&&e[n-1]===`\\`;)--n;return e.slice(0,n)}function trimWindowsLeadingSeparators(e){let t=0;for(;e[t]===`\\`;)t+=1;return e.slice(t)}function exactWindowsRootPrefix(e,t){let n=trimWindowsTrailingSeparators(e.replaceAll(`/`,`\\`)),r=t.replaceAll(`/`,`\\`),i;if(r===n)i=``;else{let e=n.endsWith(`\\`)?n:`${n}\\`;if(!r.startsWith(e))return;i=trimWindowsLeadingSeparators(r.slice(e.length))}return{admission:`exact`,candidateRootPath:n,path:i===``?n:`${n}${n.endsWith(`\\`)?``:`\\`}${i}`,relativePath:i}}function windowsRootPrefix(e,t){let n=exactWindowsRootPrefix(e,t);if(n)return n;let r=w.win32.normalize(e.replaceAll(`/`,`\\`)),i=windowsComparisonSpelling(r),a=t.replaceAll(`/`,`\\`),o=windowsComparisonSpelling(a),s=trimWindowsTrailingSeparators(r),c=trimWindowsTrailingSeparators(i);if(!w.win32.isAbsolute(a))return;let l,u,d;if(o===c)l=``,u=a,d=`exact`;else if(o.toLowerCase()===c.toLowerCase())l=``,u=a,d=`identity`;else{let e=c.endsWith(`\\`)?c:`${c}\\`,t=o.slice(0,e.length);if(t===e)d=`exact`;else if(t.toLowerCase()===e.toLowerCase())d=`identity`;else return;l=trimWindowsLeadingSeparators(o.slice(e.length)),u=a.slice(0,c.length+(a.length-o.length))}let f=l===``?s:`${s}${s.endsWith(`\\`)?``:`\\`}${l}`;return{candidateRootPath:u,path:f,relativePath:l,admission:d}}function exactRootIdentity(e,t){if(typeof t?.dev==`bigint`&&typeof t.ino==`bigint`)return{dev:t.dev,ino:t.ino};let n=inspectDirectoryIdentitySync(e);return{dev:n.dev,ino:n.ino}}function admitPathInsideRoot(e){if(process.platform!==`win32`||w.sep===`/`&&e.rootPath.startsWith(`/`)&&e.rootPath[1]!==`/`&&e.rootPath[1]!==`\\`){if(e.rootPath.startsWith(`/`)&&e.candidatePath.startsWith(`/`)&&!e.candidatePath.includes(`/..`)&&(e.candidatePath===e.rootPath||e.candidatePath.startsWith(e.rootPath)&&(e.rootPath.endsWith(`/`)||e.candidatePath[e.rootPath.length]===`/`))){let t=e.rootPath.endsWith(`/`)?e.rootPath.length:e.rootPath.length+1;return{admission:`exact`,path:e.candidatePath,relativePath:e.candidatePath===e.rootPath?``:e.candidatePath.slice(t)}}let t=w.resolve(e.rootPath),n=w.resolve(e.candidatePath),r=w.relative(t,n);return s(r)?void 0:{path:n,relativePath:r===`.`?``:r,admission:`exact`}}let t=windowsRootPrefix(e.rootPath,e.candidatePath);if(!t)return;let admitted=()=>({admission:t.admission,path:t.path,relativePath:t.relativePath});if(t.admission===`exact`)return admitted();let n=e.identityCache?.get(t.candidateRootPath);if(n!==void 0)return n?admitted():void 0;try{let n=exactRootIdentity(e.rootPath,e.rootIdentity),r=e.resolveCandidateRoot?V.native(t.candidateRootPath):t.candidateRootPath;return e.inspectCandidateRoot?e.inspectCandidateRoot(r,n):inspectDirectoryIdentitySync(r,n),e.identityCache?.set(t.candidateRootPath,!0),admitted()}catch{e.identityCache?.set(t.candidateRootPath,!1);return}}const X=process.platform===`win32`,Z=X?runSync:runAsync;function absolutePathWithRawSegments(e){if(w.sep!==`\\`){if(w.isAbsolute(e))return e;let t=process.cwd();return`${t}${t.endsWith(w.sep)?``:w.sep}${e}`}let t=w.sep===`\\`?e.replaceAll(`/`,`\\`):e,n=w.isAbsolute(t);if(n&&t[0]!==`\\`)return t;let r=w.parse(t).root;if(n&&r!==`\\`)return t;let i=r?w.resolve(r):process.cwd();return`${i}${i.endsWith(w.sep)?``:w.sep}${t.slice(r.length)}`}function*rawPathRelativeToCanonicalRoot(e,n,r={},s=!0){i(e),i(n);let c=absolutePathWithRawSegments(e),l=process.platform===`win32`?c.replaceAll(`/`,w.sep):c;if(a(l,[n]))return;let u=w.parse(l).root,d=l.slice(u.length).split(w.sep),f=d.findLastIndex(e=>e!==``&&e!==`.`),p=u,m=!1,h=process.platform===`win32`?/* @__PURE__ */ new Map:void 0;for(let a=0;a<d.length;a+=1){p+=`${p.endsWith(w.sep)?``:w.sep}${d[a]}`;let c,l=!1;try{let u=t(p),h=s?b.lstatSync(u):yield*wait(T.lstat(u));if(l=h.isSymbolicLink(),l&&r.rejectFinalSymlink&&a===f)throw new o(`symlink`,`final symlink not allowed`);if(!l&&!h.isDirectory()&&a<d.length-1||(m||=l,c=s?V.native(u):yield*wait(realpathNative(u)),i(c),l&&a<d.length-1&&!(s?b.statSync(t(c)):yield*wait(T.stat(t(c)))).isDirectory()))return;if(l&&!_(n,c)&&!_(c,n))throw new o(`outside-workspace`,`symlink prefix resolves outside the root ancestry: ${formatErrorDetail(e)}`)}catch(e){if(e instanceof o)throw e;if(l)return;continue}let u=admitPathInsideRoot({rootPath:n,candidatePath:c,rootIdentity:r.rootIdentity,identityCache:h});if(u){if(r.rejectSymlinks&&m)throw new o(`symlink`,`symlink path component not allowed`);return[u.relativePath,...d.slice(a+1)].filter(Boolean).join(w.sep)}}}function*pathExists(e,n){try{return(n?b.lstatSync(t(e),{throwIfNoEntry:!1}):yield*wait(T.lstat(t(e))))!==void 0}catch(e){if(l(e))return!1;throw e}}async function resolvePathViaExistingAncestor(e){return Z(resolveExistingAncestorProcedure(e,`native`,X))}function*ordinaryExists(e){return b.existsSync(t(e))}function resolvePathViaExistingAncestorSync(e){return resolveExistingAncestor(e,`ordinary`)}function resolveExistingAncestor(e,t,n=!1,r=64){return runSync(resolveExistingAncestorProcedure(e,t,!0,n,r))}function*resolveExistingAncestorProcedure(e,n,a,s=!1,c=64){let exists=e=>n===`native`||s?pathExists(e,a):ordinaryExists(e);i(e);let u=r(e);i(u);let d=s?absolutePathWithRawSegments(e):u,f=d,p=w.parse(d).root;for(;f!==p&&!(yield*exists(f));)f=w.dirname(f);if(!(yield*exists(f)))return u;let m;try{m=a?V.native(t(f)):yield*wait(realpathNative(t(f)))}catch(e){if(!s)return u;if(!l(e))throw e;m=yield*resolveSymlinkHopPath(f,n,!1,c,a)}i(m);let h=r(m);i(h);let g=d.slice(f.length);if(s&&g.split(w.sep).includes(`..`))throw new o(`symlink`,`symlink target has an unresolved parent component`);let _=f===d?h:w.resolve(h,`.${w.sep}${g}`);return i(_),_}function*resolveSymlinkHopPath(t,a,s,c=64,u=!0){try{let e=u?V.native(t):yield*wait(realpathNative(t));i(e,`filesystem`,`resolved symlink path uses a Windows filesystem namespace alias`);let n=r(e);return i(n,`filesystem`,`resolved symlink path uses a Windows filesystem namespace alias`),n}catch(d){if(e(d)||s&&l(d))throw new o(`symlink`,`symlink path could not be resolved`,errorCauseOptions(d));if(!l(d))throw d;if(c<=0)throw new o(`symlink`,`too many unresolved symlink hops`);let f=u?b.readlinkSync(t):yield*wait(T.readlink(t));i(f,`filesystem`,`symlink target uses a Windows filesystem namespace alias`);let p=r(w.dirname(t)),m=yield*resolveExistingAncestorProcedure(w.isAbsolute(f)?f:w.parse(f).root?n(p,f):`${p}${w.sep}${f}`,a,u,!0,c-1);return i(m,`filesystem`,`resolved symlink path uses a Windows filesystem namespace alias`),m}}const re=!!process.versions.bun&&E()===`win32`;function recursiveMkdirPath(e){return re?absolutePathWithRawSegments(e):e}const Q=2**31-1;function scheduleTimeout(e,t){let n;if(Number.isFinite(t)&&t>Q){let r=performance.now(),tick=()=>{let i=t-(performance.now()-r);i<=0?e():n=setTimeout(tick,Math.min(i,Q))};n=setTimeout(tick,Q)}else n=setTimeout(e,t);return()=>clearTimeout(n)}function sleep(e){return new Promise(t=>{scheduleTimeout(t,e)})}function sleepSync(e){e<=0||Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function assertExclusiveCreateStat(e,t){if(t.isSymbolicLink())throw Object.assign(/* @__PURE__ */ Error(`exclusive creation target already exists`),{code:`EEXIST`,syscall:`open`,path:e})}function assertExclusiveCreateLeaf(e){if(process.platform===`win32`)try{assertExclusiveCreateStat(e,b.lstatSync(e))}catch(e){if(!g(e,`ENOENT`))throw e}}function*wait(e){return yield e}async function runAsync(e){let t=e.next();for(;!t.done;){let n;try{n=await t.value}catch(n){t=e.throw(n);continue}t=e.next(n)}return t.value}function runSync(e){let t=e.next();for(;!t.done;)t=e.next(t.value);return t.value}function inspectAtomicIdentity(e,t,n,r=!1,i){return e.asynchronous&&!r?f(i?async()=>{let e=await t();return i(e),e}:t,n):h(i?()=>{let e=t();return i(e),e}:t,n)}var ie=class AtomicIo{asyncFs;syncFs;fchmodSync;asynchronous;constructor(e,t,n){this.asyncFs=e,this.syncFs=t,this.fchmodSync=n,this.asynchronous=e!==void 0}static async(e){return new AtomicIo(e,void 0)}static sync(e,t){return new AtomicIo(void 0,e,t)}wrap(e){return new AtomicFile(this,e)}*open(e,t,n){let r=arguments.length>2,i=b.constants.O_CREAT|b.constants.O_EXCL;if(process.platform===`win32`&&(typeof t==`string`?t.includes(`x`):(t&i)===i))try{assertExclusiveCreateStat(e,yield*this.lstat(e))}catch(e){if(!g(e,`ENOENT`))throw e}let a=this.asyncFs?yield*wait(r?this.asyncFs.open(e,t,n):this.asyncFs.open(e,t)):r?this.syncFs.openSync(e,t,n):this.syncFs.openSync(e,t);return this.wrap(a)}*lstat(e){return this.asyncFs?this.asyncFs===T?b.lstatSync(e):yield*wait(this.asyncFs.lstat(e)):this.syncFs.lstatSync(e)}lstatExact(e,t=!0){return this.asyncFs?t&&this.asyncFs===T?b.lstatSync(e,{bigint:!0}):this.asyncFs.lstat(e,{bigint:!0}):this.syncFs.lstatSync(e,{bigint:!0})}*mkdir(e,t){if(this.asyncFs){let n=this.asyncFs===T?recursiveMkdirPath(e):e;yield*wait(this.asyncFs.mkdir(n,{recursive:!0,mode:t}))}else{let n=this.syncFs===b?recursiveMkdirPath(e):e;this.syncFs.mkdirSync(n,{recursive:!0,mode:t})}}*mkdirExclusive(e,t){this.asyncFs?yield*wait(this.asyncFs.mkdir(e,{recursive:!1,mode:t})):this.syncFs.mkdirSync(e,{recursive:!1,mode:t})}*rename(e,t){this.asyncFs?yield*wait(this.asyncFs.rename(e,t)):this.syncFs.renameSync(e,t)}*remove(e){this.asyncFs?yield*wait(this.asyncFs.rm(e,{force:!0})):this.syncFs.rmSync(e,{force:!0})}*unlink(e){this.asyncFs?yield*wait(this.asyncFs.unlink(e)):this.syncFs.unlinkSync(e)}*delay(e){this.asynchronous?yield*wait(sleep(e)):sleepSync(e)}},AtomicFile=class{io;resource;constructor(e,t){this.io=e,this.resource=t}get fd(){return typeof this.resource==`number`?this.resource:this.resource.fd}*stat(){return typeof this.resource==`number`?this.io.syncFs.fstatSync(this.resource):this.io.asyncFs===T?b.fstatSync(this.resource.fd):yield*wait(this.resource.stat())}statExact(){return typeof this.resource==`number`?this.io.syncFs.fstatSync(this.resource,{bigint:!0}):this.io.asyncFs===T?b.fstatSync(this.resource.fd,{bigint:!0}):this.resource.stat({bigint:!0})}close(){if(typeof this.resource==`number`)this.io.syncFs.closeSync(this.resource);else return this.resource.close()}*sync(){typeof this.resource==`number`?this.io.syncFs.fsyncSync(this.resource):yield*wait(this.resource.sync())}*syncBestEffort(){try{yield*this.sync()}catch(e){if(e?.code!==`EPERM`)throw e}}chmod(e){if(typeof this.resource==`number`){let t=this.io.fchmodSync;t?.(this.resource,e)}else return this.resource.chmod(e)}writeFile(e,t=!1){if(typeof this.resource==`number`)this.io.syncFs.writeFileSync(this.resource,e);else if(t)return this.io.asyncFs.writeFile(this.resource,e);else return this.resource.writeFile(e)}*readFile(e){if(typeof this.resource!=`number`)return yield*wait(u(this.resource,1/0));if(e===void 0)return this.io.syncFs.readFileSync(this.resource);let t=this.resource,n=0;return m(1/0,(e,r)=>{let i=this.io.syncFs.readSync(t,e,0,r,n);return n+=i,i},{initialSize:Number.isSafeInteger(e)&&e>=0?e:void 0})}read(e,t,n,r){return typeof this.resource==`number`?this.io.syncFs.readSync(this.resource,e,t,n,r):this.resource.read(e,t,n,r)}write(e,t,n,r){if(typeof this.resource==`number`){let i=this.io.syncFs.writeSync(this.resource,e,t,n,r);if(i===0)throw Error(`Copy fallback write made no progress`);return i}return this.resource.write(e,t,n,r)}*truncate(e){typeof this.resource==`number`?this.io.syncFs.ftruncateSync(this.resource,e):yield*wait(this.resource.truncate(e))}};const $=/* @__PURE__ */ new WeakSet;function rootPathEscapeError(e){let t=Error(e);return $.add(t),t}function isRootPathEscapeError(e){return e instanceof Error&&$.has(e)}function sanitizeRootPathError(e){return e instanceof Error&&(e.message=formatErrorDetail(e.message)),e}function pathEscapeError(e){return rootPathEscapeError(`Path escapes ${e.boundaryLabel} (${shortPath(e.rootPath)}): ${shortPath(e.absolutePath)}`)}function symlinkEscapeError(e){return rootPathEscapeError(`Symlink escapes ${e.boundaryLabel} (${shortPath(e.rootCanonicalPath)}): ${shortPath(e.symlinkPath)}`)}function statIdentityFromNative(e){return e<=9223372036854775807n||process.versions.bun?e:BigInt.asIntN(64,e)}function isNativeStatIdentity(e){return typeof e==`bigint`&&e>=0n&&e<=18446744073709551615n}function getNativeDirectoryObservationBackend(e=!0){if(!e)return;let t=getNativeBinding(`observeDirectory`);return t&&typeof t.observeDirectory==`function`?t:void 0}function validateNativeDirectoryObservation(e){if(!e||!isNativeStatIdentity(e.dev)||!isNativeStatIdentity(e.ino)||typeof e.realPath!=`string`||e.realPath.includes(`\0`)||!w.isAbsolute(e.realPath)&&!w.win32.isAbsolute(e.realPath))throw new o(`path-mismatch`,`native directory observation is invalid`);let t=statIdentityFromNative(e.dev),n=statIdentityFromNative(e.ino);return t===e.dev&&n===e.ino?e:{...e,dev:t,ino:n}}function inspectNativeDirectoryObservation(e,t,n,r=process.platform){return h(()=>validateNativeDirectoryObservation(e.observeDirectory(t)),n,r)}function extendNativeDirectoryObservationGuard(e,t){let n=e;return n.dir=t,n.identity=n,n.nativeDirectoryObservation=!0,n}function isNativeDirectoryObservationGuard(e){return typeof e==`object`&&!!e&&e.nativeDirectoryObservation===!0}var RootPathObservationError=class extends Error{error;parentReceipt;traversalFailure;constructor(e,t,n=!1){super(`root path observation failed`,{cause:e}),this.error=e,this.parentReceipt=t,this.traversalFailure=n,this.name=`RootPathObservationError`}};function straightTraversalPath(e){if(e.length===0)return!1;let t=process.platform===`win32`,n=0;for(let r=0;r<=e.length;r+=1){if(!(r===e.length||e[r]===`/`||t&&e[r]===`\\`))continue;let i=r-n;if(i===0||i===1&&e.charCodeAt(n)===46||i===2&&e.charCodeAt(n)===46&&e.charCodeAt(n+1)===46)return!1;n=r+1}return!0}function createRootPathTraversalObservation(e,t){let{state:n}=e,r=n.finalComponentIndex<0&&(n.relativePath===``||n.relativePath===`.`);if(!t||!e.observationEligible||t.rootGuard.dir!==e.rootCanonicalPath||t.rootGuard.realPath!==e.rootCanonicalPath||e.rootPath!==e.rootCanonicalPath||!r&&!straightTraversalPath(n.relativePath)||!r&&n.finalComponentIndex!==n.segments.length-1)return;if(n.finalComponentIndex>=0){let e=t.kind===`stat`?n.finalComponentIndex-1:n.finalComponentIndex;return{enabled:!0,request:t,targetIndex:n.finalComponentIndex,directoryIndex:e,directoryGuard:e<0?t.rootGuard:void 0,directoryObserver:e<0?void 0:t.directoryObserver}}if(!r)return;let i=t.rootGuard,a=t.kind===`stat`?void 0:t.directoryObserver;if(t.kind===`directory`){if(a)try{let n=inspectNativeDirectoryObservation(a,t.rootGuard.dir,t.rootGuard.identity),r=admitPathInsideRoot({rootPath:e.rootCanonicalPath,candidatePath:n.realPath,rootIdentity:e.resolveParams.rootIdentity});if(!r||r.relativePath!==``)throw new o(`path-mismatch`,`root path changed during operation`);n.realPath=r.path,i=extendNativeDirectoryObservationGuard(n,t.rootGuard.dir)}catch(e){if(e instanceof o&&e.code===`path-mismatch`)throw new RootPathObservationError(e);a=void 0}if(!a)try{let n=admitPathInsideRoot({rootPath:e.rootCanonicalPath,candidatePath:V.native(t.rootGuard.dir),rootIdentity:e.resolveParams.rootIdentity});if(!n||n.relativePath!==``)throw new o(`path-mismatch`,`root path changed during operation`)}catch(e){throw new RootPathObservationError(e)}}return{enabled:!0,request:t,targetIndex:-1,directoryIndex:-1,directoryGuard:i,directoryObserver:a,targetPath:e.rootCanonicalPath,target:i}}function inspectRootPathTraversalEntry(e,t,n){if(t&&n.directoryObserver)try{return extendNativeDirectoryObservationGuard(inspectNativeDirectoryObservation(n.directoryObserver,e),e)}catch{n.directoryObserver=void 0}let r=process.platform===`win32`?b.lstatSync(e,{bigint:!0}):b.lstatSync(e);if(r.isSymbolicLink()||t&&!r.isDirectory())return{stat:r};try{return inspectStatObservationSync(t=>t?b.lstatSync(e,{bigint:!0}):b.lstatSync(e),void 0,r)}catch(e){throw e instanceof o&&e.code===`path-mismatch`?new RootPathObservationError(e):e}}function captureRootPathObservedDirectory(e,t,n,r,i,a){if(!isNativeDirectoryObservationGuard(t)&&!t.stat.isDirectory())return!1;let s;try{s=isNativeDirectoryObservationGuard(t)?t.realPath:V.native(r)}catch(e){throw new RootPathObservationError(e)}let c=admitPathInsideRoot({rootPath:i,candidatePath:s,rootIdentity:a});if(!c)throw new RootPathObservationError(new o(`outside-workspace`,`directory is outside workspace root`));return isNativeDirectoryObservationGuard(t)?(t.dir=n,t.realPath=c.path,e.directoryGuard=t):e.directoryGuard=extendDirectoryObservationGuard(t,n,c.path),!0}const ae={strict:Object.freeze({allowFinalSymlinkForUnlink:!1,allowFinalHardlinkForUnlink:!1}),unlinkTarget:Object.freeze({allowFinalSymlinkForUnlink:!0,allowFinalHardlinkForUnlink:!0})};async function resolveRootPath(e){return Z(resolveRootPathInternal(e))}async function resolveRootPathWithObservation(e,t){let n={request:t},r=X?runSync(resolveRootPathInternal(e,{observation:n})):await Z(resolveRootPathInternal(e,{observation:n}));return n.receipt?{resolved:r,receipt:n.receipt}:{resolved:r}}async function resolveRootPathForRemoval(e,t){return runSync(resolveRootPathInternal(e,{removalReceipts:t},!0))}function resolveRootPathSync(e){return runSync(resolveRootPathInternal(e,{mode:`ordinary`},!0))}function resolveRootPathSyncWithCanonicalRootObservation(e,t){return runSync(resolveRootPathInternal(e,{mode:`ordinary`,observeRoot:t},!0))}function*resolveRootPathInternal(e,t={},n=X){try{return yield*traverseRootPath(e,t,n)}catch(e){throw sanitizeRootPathError(e)}}function*prepareRootTraversal(e,t,n,i,o,s){let c=o,l=!1;if(a(c,[t,n]))throw pathEscapeError({rootPath:t,absolutePath:c,boundaryLabel:e.boundaryLabel});let u=admitRawPathInsideRoot(t,c,e.rootIdentity);if(u)c=u.path,l=u.admission===`identity`;else{let r=admitRawPathInsideRoot(n,c,e.rootIdentity),i=r?.relativePath??(yield*rawPathRelativeToCanonicalRoot(c,n,e,s));if(i===void 0)throw pathEscapeError({rootPath:t,absolutePath:c,boundaryLabel:e.boundaryLabel});l=r?.admission===`identity`,c=i===``?t:`${t}${w.sep}${i}`}return{params:e,rawAbsolutePath:c,rootPath:t,rootCanonicalPath:n,absolutePath:l?r(c):i,observationEligible:c===o&&!l}}function captureValidRootPathInputs(e){let t=e.rootPath;c(t,`root path contains a NUL byte`);let n=e.absolutePath;c(n,`absolute path contains a NUL byte`),i(t,`filesystem`,`root path uses a Windows filesystem namespace alias`),i(n,`filesystem`,`absolute path uses a Windows filesystem namespace alias`),assertNoEmbeddedDriveRelativeSegment(t,`root path`),assertNoEmbeddedDriveRelativeSegment(n,`absolute path`);let r=e.rootCanonicalPath;r!==void 0&&(c(r,`canonical root path contains a NUL byte`),i(r,`filesystem`,`canonical root path uses a Windows filesystem namespace alias`),assertNoEmbeddedDriveRelativeSegment(r,`canonical root path`));let a=e.policy,o=e.rootIdentity;return{rootPath:t,absolutePath:n,rootCanonicalPath:r,rootIdentity:o==null?void 0:{dev:o.dev,ino:o.ino},boundaryLabel:e.boundaryLabel,policy:a==null?void 0:{allowFinalSymlinkForUnlink:a.allowFinalSymlinkForUnlink},rejectSymlinks:e.rejectSymlinks,rejectFinalSymlink:e.rejectFinalSymlink,rejectUnresolvedSymlinks:e.rejectUnresolvedSymlinks}}function assertNoEmbeddedDriveRelativeSegment(e,t){if(process.platform!==`win32`)return;let n=w.parse(e).root;assertNoDriveRelativePathSegments(e.slice(n.length).replaceAll(`\\`,`/`),t)}function createLexicalTraversalContext(e){let t=admitRawPathInsideRoot(e.rootPath,e.rawAbsolutePath,e.params.rootIdentity)?.relativePath;if(t===void 0)throw Error(`Path traversal must begin at the root`);let n=splitTraversalSegments(t);return{state:{segments:n,relativePath:t,reuseLexicalCanonical:!1,finalComponentIndex:n.findLastIndex(e=>e!==`.`),allowFinalSymlink:e.params.policy?.allowFinalSymlinkForUnlink===!0,canonicalCursor:e.rootCanonicalPath,lexicalCursor:e.rootPath,preserveFinalSymlink:!1,missingDepth:0},resolveParams:e.params,rootPath:e.rootPath,rootCanonicalPath:e.rootCanonicalPath,absolutePath:e.absolutePath,observationEligible:e.observationEligible}}function createLexicalTraversalObservation(e,t){let n=createRootPathTraversalObservation(e,t);return n&&n.targetIndex>=0&&(e.state.reuseLexicalCanonical=!0),n}function splitTraversalSegments(e){let t=e.split(process.platform===`win32`?/[\\/]+/:/\/+/).filter(Boolean);return(e.endsWith(`/`)||process.platform===`win32`&&e.endsWith(`\\`))&&t.push(`.`),t}function admitRawPathInsideRoot(e,t,n){if(!w.isAbsolute(t))return;let r=e,i=process.platform===`win32`?t.replaceAll(`/`,w.sep):t;if(process.platform===`win32`)return admitPathInsideRoot({rootPath:r,candidatePath:i,rootIdentity:n});if(i===r)return{admission:`exact`,path:i,relativePath:``};let a=r.endsWith(w.sep)?r:`${r}${w.sep}`;return i.slice(0,a.length)===a?{admission:`exact`,path:i,relativePath:i.slice(a.length)}:void 0}function assertLexicalCursorInsideBoundary(e,t){return assertInsideBoundary({boundaryLabel:e.resolveParams.boundaryLabel,rootCanonicalPath:e.rootCanonicalPath,rootIdentity:e.resolveParams.rootIdentity,candidatePath:t,absolutePath:e.absolutePath})}function advanceCanonicalCursorForSegment(e,t){let r=e.state.reuseLexicalCanonical?e.state.lexicalCursor:n(e.state.canonicalCursor,t);e.state.canonicalCursor=assertLexicalCursorInsideBoundary(e,r)}function disableLexicalTraversalObservation(e,t){t.enabled=!1,e.state.reuseLexicalCanonical=!1}function finalizeLexicalResolution(e,t){return e.state.canonicalCursor=assertLexicalCursorInsideBoundary(e,e.state.canonicalCursor),{absolutePath:e.absolutePath,canonicalPath:e.state.canonicalCursor,rootPath:e.rootPath,rootCanonicalPath:e.rootCanonicalPath,relativePath:relativeInsideRoot(e.rootCanonicalPath,e.state.canonicalCursor),exists:t!==`missing`,kind:t}}function applyResolvedSymlinkHop(e,t){let n;try{n=assertLexicalCursorInsideBoundary(e,t)}catch{throw symlinkEscapeError({boundaryLabel:e.resolveParams.boundaryLabel,rootCanonicalPath:e.rootCanonicalPath,symlinkPath:e.state.lexicalCursor})}e.state.canonicalCursor=n,e.state.lexicalCursor=n}function applyParentTraversalStep(e){e.state.lexicalCursor=n(e.state.lexicalCursor,`..`),advanceCanonicalCursorForSegment(e,`..`),e.state.missingDepth>0&&--e.state.missingDepth}function assertDirectoryBeforeMoreSegments(e,t,n){if(!n&&!e.isDirectory())throw Object.assign(/* @__PURE__ */ Error(`Path component is not a directory: ${t}`),{code:`ENOTDIR`})}function*assertResolvedLinkDirectory(e,n,r){n||assertDirectoryBeforeMoreSegments(r?b.statSync(t(e)):yield*wait(T.stat(t(e))),e,n)}function*traverseRootPath(e,{mode:n=`native`,observation:a,observeRoot:s,removalReceipts:c},u){let d=captureValidRootPathInputs(e),f=absolutePathWithRawSegments(d.absolutePath),p=r(d.rootPath),m=r(f),h=d.rootCanonicalPath?r(d.rootCanonicalPath):yield*resolveExistingAncestorProcedure(p,n,u);i(p),i(m),i(h),s?.(h);let g=createLexicalTraversalContext(yield*prepareRootTraversal(d,p,h,m,f,u)),{state:_}=g,v=createLexicalTraversalObservation(g,a?.request);for(let e=0;e<_.segments.length;e+=1){let r=_.segments[e]??``,i=e===_.segments.length-1;if(r===`.`)continue;if(r===`..`){applyParentTraversalStep(g);continue}if(_.lexicalCursor=w.join(_.lexicalCursor,r),_.missingDepth>0){advanceCanonicalCursorForSegment(g,r),_.missingDepth+=1;continue}let a,s;try{if(c&&!i){let e=b.lstatSync(t(_.lexicalCursor),{bigint:!0});e.isDirectory()&&!e.isSymbolicLink()&&c.observeDirectory(_.lexicalCursor,e),a=e}else{let t=v?.enabled===!0&&e===v.directoryIndex,n=v?.enabled===!0&&e===v.targetIndex;(t||n)&&(s=inspectRootPathTraversalEntry(_.lexicalCursor,t,v)),a=isNativeDirectoryObservationGuard(s)?void 0:s?.stat??(u?b.lstatSync(_.lexicalCursor):yield*wait(T.lstat(_.lexicalCursor)))}}catch(t){if(v?.enabled&&v.request.kind===`stat`&&e===v.targetIndex&&v.directoryGuard){let e={kind:`stat-parent`,rootGuard:v.request.rootGuard,directoryGuard:v.directoryGuard,directoryObserver:v.directoryObserver,targetPath:_.lexicalCursor};throw new RootPathObservationError(t instanceof RootPathObservationError?t.error:sanitizeRootPathError(t),e,!(t instanceof RootPathObservationError))}if(!l(t))throw t;advanceCanonicalCursorForSegment(g,r),_.missingDepth=1;continue}if(isNativeDirectoryObservationGuard(s)){advanceCanonicalCursorForSegment(g,r),captureRootPathObservedDirectory(v,s,_.lexicalCursor,_.canonicalCursor,g.rootCanonicalPath,g.resolveParams.rootIdentity),e===v.targetIndex&&(v.targetPath=_.canonicalCursor,v.target=s);continue}if(!a)throw Error(`directory observation did not return metadata`);let d=a.isSymbolicLink();if(d||assertDirectoryBeforeMoreSegments(a,_.lexicalCursor,i),d&&(g.resolveParams.rejectFinalSymlink===!0&&e===_.finalComponentIndex||g.resolveParams.rejectSymlinks===!0&&i))throw new o(`symlink`,`symlink path component not allowed`);let f=d&&_.allowFinalSymlink&&i;if(!d||f){if(_.preserveFinalSymlink=f,advanceCanonicalCursorForSegment(g,r),v?.enabled&&d&&disableLexicalTraversalObservation(g,v),v?.enabled&&e===v.directoryIndex&&(s?.identity&&captureRootPathObservedDirectory(v,s,_.canonicalCursor,_.canonicalCursor,g.rootCanonicalPath,g.resolveParams.rootIdentity)||disableLexicalTraversalObservation(g,v)),v?.enabled&&e===v.targetIndex&&(v.targetPath=_.canonicalCursor,v.target=s?.identity?s:void 0),_.preserveFinalSymlink)break;continue}v?.enabled&&disableLexicalTraversalObservation(g,v);let p=yield*resolveSymlinkHopPath(_.lexicalCursor,n,g.resolveParams.rejectUnresolvedSymlinks,64,u);if(applyResolvedSymlinkHop(g,p),g.resolveParams.rejectSymlinks===!0)throw new o(`symlink`,`symlink path component not allowed`);yield*assertResolvedLinkDirectory(p,i,u)}let y=v?.enabled===!0&&v.directoryGuard!==void 0&&v.targetPath===_.canonicalCursor&&v.target!==void 0,x=y?isNativeDirectoryObservationGuard(v.target)?`directory`:toResolvedKind(v.target.stat):yield*getPathKind(_.canonicalCursor,_.preserveFinalSymlink,u);return y&&a&&(a.receipt={kind:v.request.kind,rootGuard:v.request.rootGuard,directoryGuard:v.directoryGuard,directoryObserver:v.directoryObserver,targetPath:v.targetPath,target:v.target}),finalizeLexicalResolution(g,x)}function*getPathKind(e,n,r){try{let i=t(e);return toResolvedKind(n?r?b.lstatSync(i):yield*wait(T.lstat(i)):r?b.statSync(i):yield*wait(T.stat(i)))}catch(e){if(l(e))return`missing`;throw e}}function toResolvedKind(e){return e.isFile()?`file`:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`other`}function relativeInsideRoot(e,t){let n=w.relative(r(e),r(t));return!n||n===`.`||s(n)?``:n}function assertInsideBoundary(e){let t=admitPathInsideRoot({rootPath:e.rootCanonicalPath,candidatePath:e.candidatePath,rootIdentity:e.rootIdentity});if(t)return t.path;throw Error(`Path resolves outside ${e.boundaryLabel} (${shortPath(e.rootCanonicalPath)}): ${shortPath(e.absolutePath)}`)}function readSymlinkResolution(e){return{rejectSymlinks:e!==`follow-within-root`&&e!==`follow-parents-within-root`,rejectFinalSymlink:e===`follow-parents-within-root`}}function mutationSymlinkResolution(e){if(e!==void 0&&e!==`reject`&&e!==`follow-parents-within-root`)throw RangeError(`mutationSymlinks must be reject or follow-parents-within-root`);return{rejectSymlinks:e===`reject`,rejectFinalSymlink:e!==void 0,resolveCanonical:e!==void 0}}function assertFinalSymlinkRejected(e,t,n){if(t)try{if(b.lstatSync(e).isSymbolicLink())throw new o(`symlink`,`final symlink not allowed`,{details:n})}catch(e){if(!l(e))throw e}}export{normalizePinnedPathError as $,admitPathInsideRoot as A,captureDirectoryGuard as B,sleep as C,getNativeModeSetting as Ct,resolveExistingAncestor as D,absolutePathWithRawSegments as E,assertDirectoryGuard as F,inspectDirectoryIdentitySync as G,createNearestExistingDirectoryGuard as H,assertDirectoryIdentitySync as I,directoryComponentNotDirectoryError as J,inspectDirectoryObservationSync as K,assertDirectoryObservationGuardSync as L,formatErrorDetail as M,shortPath as N,resolvePathViaExistingAncestor as O,assertAsyncDirectoryGuard as P,isAlreadyExistsError as Q,assertDirectoryObservationSync as R,assertExclusiveCreateLeaf as S,getFsSafeNativeConfig as St,recursiveMkdirPath as T,captureNativeFdClose as Tt,extendDirectoryObservationGuard as U,createAsyncDirectoryGuard as V,inspectDirectoryIdentity as W,fileNotFoundError as X,errorCauseOptions as Y,hardlinkedPathNotAllowedError as Z,ie as _,assertNativeCapabilities as _t,resolveRootPath as a,rootPathChangedError as at,runSync as b,requireNativeBinding as bt,resolveRootPathSyncWithCanonicalRootObservation as c,sameFileIdentity as ct,getNativeDirectoryObservationBackend as d,assertSafePathPrefix as dt,normalizePinnedWriteError as et,inspectNativeDirectoryObservation as f,isDriveRelativePath as ft,isRootPathEscapeError as g,assertWindowsHelperAllowed as gt,statIdentityFromNative as h,V as ht,ae as i,pathTraversalPermissionError as it,sameNormalizedPathSpelling as j,resolvePathViaExistingAncestorSync as k,resolveRootPathWithObservation as l,sameFileIdentityForCleanup as lt,isNativeStatIdentity as m,realpathNative as mt,mutationSymlinkResolution as n,normalizeRemovePathError as nt,resolveRootPathForRemoval as o,hasSafeFileIdentity as ot,isNativeDirectoryObservationGuard as p,isSafePathSegment as pt,assertStatObservationSync as q,readSymlinkResolution as r,outsideWorkspaceError as rt,resolveRootPathSync as s,identityFromReceipt as st,assertFinalSymlinkRejected as t,normalizeRemoveGuardError as tt,RootPathObservationError as u,sha256Hex as ut,inspectAtomicIdentity as v,getNativeBinding as vt,sleepSync as w,isFsSafeNativeRequired as wt,wait as x,selectNativeBinding as xt,runAsync as y,getNativeFallbackDiagnostic as yt,assertSyncDirectoryGuard as z};