UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 85.1 kB
import{Et as e,Jt as t,Lt as n,Nt as r,a as i,kt as a,r as o}from"./sqlite-readonly-subsystem-Bfq7Sewc.mjs";import{Ct as s,Et as c,Gt as l,Ht as u,I as d,Jt as f,K as p,Lt as m,O as h,Ot as g,Pt as _,S as v,St as y,Tt as b,Ut as x,Vt as S,W as C,Wt as w,Xt as T,Zt as ee,an as E,at as D,b as O,cn as k,ct as te,d as ne,dt as re,en as A,fn as ie,gt as ae,ht as oe,in as j,it as M,k as se,kt as ce,ln as N,mn as le,mt as P,pn as F,qt as I,rn as ue,sn as de,tn as fe,tt as L,un as pe,ut as R,v as z,wt as me,y as he}from"./sqlite-readonly-runtime-process-manifest-DDSkIpjb.mjs";import{a as ge,c as B,i as _e,n as ve,t as ye}from"./sqlite-readonly-file-open-error-B05Kb3Yo.mjs";import{c as be,l as xe,n as Se,r as Ce}from"./sqlite-readonly-file-descriptor-XY1-VkqF.mjs";import{$ as we,A as V,Dn as Te,En as Ee,On as De,Ot as Oe,Pt as ke,Tn as H,ct as Ae,it as je,ln as Me,r as Ne}from"./sqlite-readonly-sqlite-database-admission-Bj6bmeyX.mjs";import{t as Pe}from"./sqlite-readonly-usingCtx-03vOGQ3v.mjs";import{K as Fe,n as Ie,t as Le}from"./sqlite-readonly-node-sqlite-C-jA8uc4.mjs";import{i as Re,t as ze}from"./sqlite-readonly-retained-operation-CV17ZGcz.mjs";import{t as Be}from"./sqlite-readonly-error-graph-internal-c5T0xDg9.mjs";import U from"node:path";import{randomUUID as Ve}from"node:crypto";import W from"node:fs";import G from"node:fs/promises";import He from"node:os";import{fileURLToPath as Ue}from"node:url";import{promisify as We,types as Ge}from"node:util";import{execFile as Ke,spawn as qe,spawnSync as Je}from"node:child_process";function admitUncachedCopyPath(e,t=!1,n){if(!U.isAbsolute(e.rootPath)||!U.isAbsolute(e.absolutePath))throw new N(`invalid-path`,`copy roots and paths must be absolute`);let r=n??D(I.native(e.rootPath),`native`,{bigint:!0}),i=n?.realPath,resolve=()=>{let n=t?v({...e,rootCanonicalPath:i,absolutePath:U.dirname(e.absolutePath),boundaryLabel:`copy parent`,rejectSymlinks:!0,rejectFinalSymlink:!0}):void 0,r=v({...e,rootCanonicalPath:i,boundaryLabel:`copy`,rejectSymlinks:!t,rejectFinalSymlink:!t,policy:t?he.unlinkTarget:void 0});if(n&&U.dirname(r.canonicalPath)!==n.canonicalPath)throw new N(`path-mismatch`,`copy destination parent changed`);return r},a=resolve(),o=D(U.dirname(a.canonicalPath),`native`,{bigint:!0}),assertCurrent=()=>{M(r),M(o);let e=resolve();if(e.rootCanonicalPath!==r.realPath||e.canonicalPath!==a.canonicalPath)throw new N(`path-mismatch`,`copy path changed during operation`);M(r),M(o)};return assertCurrent(),{path:a.canonicalPath,parent:o,assertCurrent,rootCanonicalPath:void 0}}function createCopyPathAdmissionCache(){let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,assertParent=({root:e,parent:t,chain:n})=>{M(e);for(let e of n)e!==t&&R(e.dir,{dev:BigInt(e.stat.dev),ino:BigInt(e.stat.ino)});t!==e&&M(t),M(e)};return{admit:(r,i=!1)=>{if(process.platform===`win32`&&(!/^[a-z]:\\/iu.test(r.rootPath)||u(r.rootPath,`filesystem`)||u(r.absolutePath,`filesystem`)||r.absolutePath.slice(3).split(`\\`).some(e=>/[. ]$/u.test(e)||e.includes(`~`)))||!U.isAbsolute(r.rootPath)||!U.isAbsolute(r.absolutePath)||r.rootPath.includes(`\0`)||r.absolutePath.includes(`\0`)||U.resolve(r.rootPath)!==r.rootPath||U.resolve(r.absolutePath)!==r.absolutePath||!r.absolutePath.startsWith(r.rootPath.endsWith(U.sep)?r.rootPath:`${r.rootPath}${U.sep}`))return admitUncachedCopyPath(r,i);let a=e.get(r.rootPath);if(!a){let t=I.native(r.rootPath);if(t!==r.rootPath)return admitUncachedCopyPath(r,i);a=D(t,`native`,{bigint:!0}),e.set(r.rootPath,a)}M(a);let o=U.dirname(r.absolutePath),s=t.get(r.rootPath),c=s?.get(o);if(!c){let e=admitUncachedCopyPath(r,i,a),l=[],u=r.rootPath,d=U.relative(r.rootPath,o);for(let e of d?d.split(U.sep):[]){u=U.join(u,e);let t=n.get(u);t||(t=D(u,`native`,{bigint:!0}),n.set(u,t)),l.push(t)}if(c={root:a,parent:l.at(-1)??a,chain:l},assertParent(c),e.path!==r.absolutePath||e.parent.realPath!==o||!F(e.parent.stat,c.parent.stat))throw new N(`path-mismatch`,`copy path changed during admission`);s??=/* @__PURE__ */ new Map,s.set(o,c),t.set(r.rootPath,s)}let l=c,assertCurrent=()=>{if(assertParent(l),!i&&W.lstatSync(r.absolutePath,{throwIfNoEntry:!1})?.isSymbolicLink())throw admitUncachedCopyPath(r,i),new N(`symlink`,`symlink not allowed`)};return assertCurrent(),{path:r.absolutePath,parent:l.parent,assertCurrent,rootCanonicalPath:l.root.realPath}},clear(){e.clear(),t.clear(),n.clear()}}}function resolveCopyCloneMode(e,t){let n=e===void 0?t:e;if(n!==`auto`&&n!==`always`&&n!==`never`)throw new N(`invalid-path`,`copy clone policy must be auto, always, or never`);return n}function ownFileDescriptorSync(e,t=W.closeSync){let n=!0,r={fd:e,close(){n&&(n=!1,t(e))},[Symbol.dispose](){r.close()}};return Object.freeze(r)}var NativePolicyDirectoryMismatch=class extends N{constructor(e){super(`path-mismatch`,`staging directory pathname changed`,{cause:e})}};function nativePolicyDirectoryObserver(e,t,n){if(!e||process.platform===`win32`||process.versions.bun)return;let r=e.observeDirectoryFd;if(typeof r!=`function`)return;let i=A().mode,a=!1;return Object.assign(()=>{if(a)throw new NativePolicyDirectoryMismatch;if(A().mode!==i)return;let o;try{o=r.call(e,t,n)}catch(e){if(e?.code===`OBSERVATION_UNAVAILABLE`)return;throw e?.code===`OBSERVATION_REDIRECTED`?new N(`path-mismatch`,`staging directory pathname redirected`):e?.code===`path-mismatch`?new NativePolicyDirectoryMismatch(e instanceof Error?e:void 0):e}if(A().mode===i&&!(!o||!h(o.dev)||!h(o.ino)||typeof o.mode!=`bigint`||o.mode<0n||o.mode>4294967295n||typeof o.nlink!=`bigint`||o.nlink<0n||o.nlink>18446744073709551615n||typeof o.realPath!=`string`||o.realPath.includes(`\0`)||!U.isAbsolute(o.realPath))){if((o.mode&61440n)!=16384n||o.nlink===0n||o.realPath!==n)throw new NativePolicyDirectoryMismatch;return Object.freeze({canonicalPath:o.realPath,identity:Object.freeze({dev:se(o.dev),ino:se(o.ino),mode:o.mode,nlink:o.nlink})})}},{dispose(){a=!0}})}function nativeGuidance(e,t){switch(e){case`disabled`:return`If native loading is intended, ${t===`programmatic configuration`?`call configureFsSafeNative({ mode: "auto" }) or configureFsSafeNative({ mode: "require" })`:`set ${t}=auto or ${t}=require`}; keep intentional off settings.`;case`unsupported-target`:return`Portable mode is expected on this target.`;case`package-missing`:return`Reinstall with optional dependencies included: npm --include=optional, or pnpm without --no-optional / optional=false. Check the lockfile and registry mirror.`;case`load-failed`:return`Check Node architecture, Linux libc compatibility, package dependencies, and OS code-integrity policy. Reinstalling identical bytes may not help.`;case`capability-missing`:return`Use matching fs-safe and platform-package versions; some targets intentionally provide only a subset of capabilities.`;default:return}}const Ye=/* @__PURE__ */ new Set;function fallbackReason(e){let t=ee(...e),n=t.packageName===void 0?`No native package is published for ${t.target}.`:`Expected ${t.packageName}@${t.packageVersion}.`,r=nativeGuidance(t.reason,fe().source);switch(t.reason){case`disabled`:return`native support is disabled by ${t.source} (disabled). ${n} ${r}`;case`unsupported-target`:return`the target ${t.target} is unsupported (unsupported-target). ${n} ${r}`;case`package-missing`:return`the selected native package could not be resolved (package-missing). ${n} ${r}`;case`load-failed`:return`the native package could not be loaded (load-failed: ${t.code}). ${n} ${r}`;case`capability-missing`:return`the native package lacks requested functions (capability-missing: ${t.capabilities.join(`, `)}). ${n} ${r}`;default:return`the requested native operation is unavailable (${t.reason}). ${n}`}}function warnNativeFallback(e,t,...n){Ye.has(e)||(Ye.add(e),process.emitWarning(`${e} is using its portable fallback because ${fallbackReason(n)} ${t}`,{code:`FS_SAFE_NATIVE_FALLBACK`,type:`FsSafeWarning`}))}function windowsSecurityHelperPath(){return Ue(new URL(`./windows-security-helper.exe`,new URL(`dist/windows-security-helper.js`,import.meta.resolve(`@openclaw/fs-safe/package.json`)).href))}function explainWindowsSecurityHelperFailure(e){e.message+=`; Windows security helper could not complete; rebuild with pnpm build:windows-helper or reinstall @openclaw/fs-safe`}We(Ke);const K=3e4;function formatPermissionErrorDetail(e){let t=p(e.slice(0,401));return t.length>400?`${t.slice(0,399)}…`:t}const Xe=Ge.isUint8Array,Ze=Uint8Array,q=Object.getPrototypeOf(Ze.prototype),Qe=Object.getOwnPropertyDescriptor(q,`buffer`).get,$e=Object.getOwnPropertyDescriptor(q,`byteOffset`).get,et=Object.getOwnPropertyDescriptor(q,`byteLength`).get,tt=Object.getOwnPropertyDescriptor(q,`set`).value,nt=TextDecoder.prototype.decode,rt=new TextDecoder(`utf-8`,{fatal:!1,ignoreBOM:!0}),it=1600;function isInspectableCaughtObject(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return!1;try{return!Ge.isProxy(e)}catch{return!1}}function dataProperty(e,t){let n=e;for(let e=0;n!==null&&e<4;e+=1){if(!isInspectableCaughtObject(n))return;let e;try{e=Object.getOwnPropertyDescriptor(n,t)}catch{return}if(e)return Object.hasOwn(e,`value`)?e:void 0;try{n=Object.getPrototypeOf(n)}catch{return}}}function formatBoundedCaughtDetail(e,t=!1){let n=t||e.length>400,r=formatPermissionErrorDetail(e.slice(0,400));return!n||r.endsWith(`…`)?r:`${r.slice(0,399)}…`}function safeStderr(e){if(typeof e==`string`)return formatBoundedCaughtDetail(e);try{if(!Xe(e))return``;let t=Reflect.apply(Qe,e,[]),n=Reflect.apply($e,e,[]),r=Reflect.apply(et,e,[]),i=r<it?r:it,a=new Ze(t,n,i),o=new Ze(i);return Reflect.apply(tt,o,[a,0]),formatBoundedCaughtDetail(Reflect.apply(nt,rt,[o]),r>i)}catch{return``}}function commandFailureFields(e){let t=dataProperty(e,`killed`),n=dataProperty(e,`code`),r=dataProperty(e,`signal`),i=dataProperty(e,`stderr`);return{found:!!(t||n||r||i),timedOut:t?.value===!0&&r?.value===`SIGKILL`,exitCode:typeof n?.value==`number`?n.value:null,signal:typeof r?.value==`string`?r.value:null,stderr:i?safeStderr(i.value):``}}var PermissionCommandError=class extends Error{command;durationMs;timedOut;exitCode;signal;stderr;constructor(e,t,n,r=K){let i=commandFailureFields(n);super(i.timedOut?`Windows permission inspection timed out after ${r}ms`:`Windows permission command ${formatPermissionErrorDetail(U.win32.basename(e))} failed (exit code ${i.exitCode}, signal ${formatPermissionErrorDetail(i.signal??`none`)})`,{cause:n}),this.name=`PermissionCommandError`,this.command=e,this.durationMs=Math.round(t),this.timedOut=i.timedOut,this.exitCode=i.exitCode,this.signal=i.signal,this.stderr=i.stderr}};function unverified(e,t){throw new N(`permission-unverified`,e,t===void 0?{}:{cause:t})}const at=1048576,ot=/^[0-9a-f]{16}:[0-9a-f]{32}$/;function isFullIdentity(e){return typeof e==`string`&&e.length===49&&ot.test(e)}function assertIdentity(e){if(!isFullIdentity(e))throw TypeError(`Windows security operation requires a complete file identity`)}function command(e,t){let n=t.targetPath??``;if(n.includes(`\0`))throw Object.assign(/* @__PURE__ */ Error(`Windows path contains a NUL byte`),{code:`EINVAL`});if((t.fd!==void 0||e===`descriptor`||e===`protect-file`||e===`verify-file`)&&(typeof t.fd!=`number`||!Number.isInteger(t.fd)||t.fd<0||t.fd>2147483647)&&unverified(`Windows security inspection requires a valid descriptor`),t.expectedParentIdentity!==void 0&&assertIdentity(t.expectedParentIdentity),t.expectedFileIdentity!==void 0&&assertIdentity(t.expectedFileIdentity),t.expectedLinks!==void 0&&(!Number.isInteger(t.expectedLinks)||t.expectedLinks<1||t.expectedLinks>4294967295))throw TypeError(`Windows security operation requires a positive uint32 link count`);return{file:windowsSecurityHelperPath(),args:[e],env:{...process.env,FS_SAFE_WINDOWS_SECURITY_PATH:n,FS_SAFE_WINDOWS_SECURITY_REQUIRE_PRIVATE:t.requirePrivate?`1`:`0`,FS_SAFE_WINDOWS_SECURITY_PARENT_IDENTITY:t.expectedParentIdentity??``,FS_SAFE_WINDOWS_SECURITY_FILE_IDENTITY:t.expectedFileIdentity??``,FS_SAFE_WINDOWS_SECURITY_EXPECTED_LINKS:String(t.expectedLinks??1)}}}function record(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function parseReply(e,t){try{return parseReplyValue(e,t)}catch(e){throw t===`create`&&e instanceof Error&&e.code!==`EEXIST`&&Object.assign(e,{creationOutcome:`unconfirmed`}),e}}function parseReplyValue(e,t){let n;try{n=JSON.parse(e.trim())}catch(e){unverified(`Windows security command returned invalid data`,e)}if(record(n)&&typeof n.ok==`boolean`||unverified(`Windows security command returned an incomplete response`),!n.ok){if(t===`paths`&&(n.code===`helper-unavailable`||n.code===`too-large`)&&typeof n.message==`string`)throw new N(n.code,n.message);let e=/* @__PURE__ */ new Set([`EACCES`,`EPERM`,`EEXIST`,`ENOENT`,`ENOTSUP`,`EIO`,`EBADF`,`ELOOP`,`ENOTDIR`,`EINVAL`,`ENOSPC`,`EBUSY`]);typeof n.code==`string`&&e.has(n.code)&&typeof n.message==`string`||unverified(`Windows security command returned an invalid failure`),n.errno!==void 0&&(typeof n.errno!=`number`||!Number.isInteger(n.errno)||n.errno<0||n.errno>4294967295)&&unverified(`Windows security command returned an invalid native error number`);let r=Object.assign(Error(n.message),{code:n.code});throw n.errno!==void 0&&Object.defineProperty(r,"errno",{value:n.errno,enumerable:!0,configurable:!0,writable:!0}),r}return t!==`create`||record(n.result)&&n.result.created===!0&&isFullIdentity(n.result.identity)||unverified(`Windows security command did not verify private-directory creation`),n.result}function explainHelperFailure(e,t){t.endsWith(`windows-security-helper.exe`)&&explainWindowsSecurityHelperFailure(e)}function executeSync(e,t){f();let{file:n,args:r,env:i}=command(e,t),a=performance.now(),o=Je(n,r,{encoding:`utf8`,windowsHide:!0,env:i,stdio:[t.fd??`ignore`,`pipe`,`pipe`],timeout:K,killSignal:`SIGKILL`,maxBuffer:at});if(o.error||o.status!==0){let t=new PermissionCommandError(n,performance.now()-a,{cause:o.error,code:o.status,signal:o.error?.code===`ETIMEDOUT`?`SIGKILL`:o.signal,stderr:o.stderr,killed:o.error?.code===`ETIMEDOUT`,...e===`create`?{creationOutcome:`unconfirmed`}:{}});throw explainHelperFailure(t,n),e===`create`&&Object.assign(t,{creationOutcome:`unconfirmed`}),t}return parseReply(o.stdout,e)}var WindowsSecurityCommandError=class extends PermissionCommandError{timedOut;creationOutcome;processExitConfirmed;constructor(e,t,n,r,i=K){super(e,t,n,i),this.timedOut=r,r||explainHelperFailure(this,e),this.creationOutcome=n.creationOutcome,this.processExitConfirmed=n.processExitConfirmed,r&&(this.message=`Windows permission inspection timed out after ${i}ms`),n.processExitConfirmed?n.outputClosed||(this.message+=`; command output did not close`):this.message+=`; process exit was not confirmed`,n.creationOutcome&&(this.message+=`; private-directory creation outcome is unconfirmed`)}};function hasUnsettledWindowsSecurityCommand(e){let t=[e],n=/* @__PURE__ */ new Set;for(let e=0;t.length&&e<32;e++){let e=t.pop();if(typeof e==`object`&&e&&!n.has(e)){n.add(e);try{if(e instanceof WindowsSecurityCommandError&&!e.processExitConfirmed)return!0;let n=Object.getOwnPropertyDescriptor(e,`cause`);if(n&&`value`in n&&t.push(n.value),e instanceof AggregateError){let n=Object.getOwnPropertyDescriptor(e,`errors`);n&&`value`in n&&Array.isArray(n.value)&&t.push(...n.value.slice(0,32))}}catch{return!0}}}return t.length>0}function ignoreLateError(){}async function execute(e,t,n){f();let{file:r,args:i,env:a,input:o,timeoutMs:s=K,maxOutputBytes:c=at}=n??command(e,t),l=performance.now();return await new Promise((n,u)=>{let d=qe(r,i,{windowsHide:!0,env:a,stdio:[o===void 0?t.fd??`ignore`:`pipe`,`pipe`,`pipe`]}),f=[],p=[],m=0,h,g=!1,_=!1,v=!1,y=!1,b=!1,x=null,S=null,C,w,T,ee,deadlineError=()=>/* @__PURE__ */ Error(`Windows security command exceeded its inspection deadline`),E=setTimeout(()=>{_=!0,fail(deadlineError())},s),finish=t=>{if(y)return;y=!0,clearTimeout(E),clearTimeout(T),clearImmediate(ee),d.removeListener(`exit`,onExit),d.removeListener(`close`,onClose),d.removeListener(`error`,onChildError),d.on(`error`,ignoreLateError);let i=[];if(o!==void 0&&d.stdin&&(d.stdin.removeListener(`error`,fail),d.stdin.on(`error`,ignoreLateError),!t))try{d.stdin.destroy()}catch(e){i.push(e)}for(let[e,n]of[[d.stdout,D],[d.stderr,O]])if(e&&(e.removeListener(`data`,n),e.removeListener(`error`,fail),e.on(`error`,ignoreLateError),!t))try{e.destroy()}catch(e){i.push(e)}if(!t&&!b)try{d.unref()}catch(e){i.push(e)}if(g||x!==0||!t)u(new WindowsSecurityCommandError(r,performance.now()-l,{cause:h,pid:d.pid??null,code:x,signal:S,stderr:Buffer.concat(p),processExitConfirmed:b,outputClosed:t,terminationSignalSent:C,terminationError:w,cleanupErrors:i,...e===`create`?{creationOutcome:`unconfirmed`}:{}},_,s));else try{n(parseReply(Buffer.concat(f).toString(`utf8`),e))}catch(e){u(e)}f.length=0,p.length=0},fail=e=>{if(!y&&(g||(g=!0,h=e),!v&&(v=!0,clearTimeout(E),T=setTimeout(()=>finish(!1),1e3),!b)))try{C=d.kill(`SIGKILL`)}catch(e){w??=e}},collect=e=>t=>{g||y||(m+=t.length,m<=c?e.push(t):fail(/* @__PURE__ */ Error(`Windows security command exceeded its output budget`)))},D=collect(f),O=collect(p),onChildError=e=>{y||(v?w??=e:fail(e))},onExit=(e,t)=>{b=!0,x=e,S=t},onClose=(e,t)=>{onExit(e,t),!g&&performance.now()-l>=s&&(_=!0,g=!0,h=deadlineError()),finish(!0)};if(d.on(`error`,onChildError),d.once(`exit`,onExit),d.once(`close`,onClose),d.stdout?.on(`error`,fail),d.stderr?.on(`error`,fail),d.stdout?.on(`data`,D),d.stderr?.on(`data`,O),d.stdout&&d.stderr&&(o===void 0||d.stdin)||(ee=setImmediate(()=>{!g&&!y&&fail(/* @__PURE__ */ Error(`Windows security command output pipes are unavailable`))})),o!==void 0&&d.stdin){d.stdin.on(`error`,fail);try{d.stdin.end(o,`utf8`)}catch(e){fail(e)}}})}async function createPrivateWindowsDirectoryCommand(e,t){return fullIdentityReceipt(await execute(`create`,{targetPath:e,expectedParentIdentity:t}))}function createPrivateWindowsDirectoryCommandSync(e,t){return fullIdentityReceipt(executeSync(`create`,{targetPath:e,expectedParentIdentity:t}))}function fullIdentityReceipt(e,t){if(record(e)&&isFullIdentity(e.identity)||unverified(`Windows security command returned an incomplete file identity`),t!==void 0&&e.identity!==t)throw new N(`path-mismatch`,`Windows security command observed a different file`);return{identity:e.identity}}function inspectWindowsDirectoryCommandSync(e,t){return fullIdentityReceipt(executeSync(`directory`,{targetPath:e,requirePrivate:t}))}async function inspectWindowsDirectoryCommand(e,t){return fullIdentityReceipt(await execute(`directory`,{targetPath:e,requirePrivate:t}))}function protectPrivateWindowsFileCommandSync(e,t,n){return assertIdentity(n),fullIdentityReceipt(executeSync(`protect-file`,{fd:e,targetPath:t,expectedParentIdentity:n}))}async function protectPrivateWindowsFileCommand(e,t,n){return assertIdentity(n),fullIdentityReceipt(await execute(`protect-file`,{fd:e,targetPath:t,expectedParentIdentity:n}))}function verifyPrivateWindowsFileCommandSync(e,t,n,r,i=1){assertIdentity(n),assertIdentity(r),fullIdentityReceipt(executeSync(`verify-file`,{fd:e,targetPath:t,expectedFileIdentity:n,expectedParentIdentity:r,expectedLinks:i}),n)}async function verifyPrivateWindowsFileCommand(e,t,n,r,i=1){assertIdentity(n),assertIdentity(r),fullIdentityReceipt(await execute(`verify-file`,{fd:e,targetPath:t,expectedFileIdentity:n,expectedParentIdentity:r,expectedLinks:i}),n)}function resolveCreationPermissions(e,t){let n=e.private,r=e.mode;if(n!==void 0&&typeof n!=`boolean`)throw TypeError(`private must be a boolean`);if(r!==void 0&&(!Number.isInteger(r)||r<0||r>4095))throw RangeError(`mode must contain only permission bits`);if(n&&r!==void 0&&r&3647)throw new N(`insecure-permissions`,`private creation requires owner-only permission bits`);return n&&assertDarwinPrivateCreationAvailable(),n&&t&&assertDarwinPrivateDirectoryMode(r??448),{private:n===!0,mode:r??(n?t?448:384:void 0)}}function assertPrivatePosixDirectory(e){if(typeof process.getuid!=`function`||e.uid!==BigInt(process.getuid()))throw new N(`not-owned`,`private directory must belong to the current user`);if((e.mode&3647n)!=0n)throw new N(`insecure-permissions`,`existing directory is not private`)}function unavailable(){throw new N(`helper-unavailable`,`private Windows creation requires an up-to-date native helper`)}function assertPrivateFileCreationAvailable(){let e=T();process.platform===`win32`&&A().mode===`require`&&(typeof e?.createPrivateDirectoryWithParentIdentity!=`function`||typeof e.inspectWindowsDirectory!=`function`||typeof e.protectPrivateWindowsFile!=`function`||typeof e.verifyPrivateWindowsFile!=`function`)&&unavailable()}function commandFallback(e){A().mode===`require`&&unavailable(),warnNativeFallback(`windows-private-creation`,`Private Windows creation launches the packaged .NET helper for each check or creation.`,e)}function creationOperation(e){let t=T(),n=t?.[e];if(typeof n==`function`)return n.bind(t);commandFallback(e)}function inspectCreationDirectorySync(e,t){S(e,`filesystem`);let n=creationOperation(`inspectWindowsDirectory`);return(n?n(e,t):inspectWindowsDirectoryCommandSync(e,t)).identity}async function inspectCreationDirectory(e,t){S(e,`filesystem`);let n=creationOperation(`inspectWindowsDirectory`);return(n?n(e,t):await inspectWindowsDirectoryCommand(e,t)).identity}function assertPrivateDirectorySync(e){let t=R(e);process.platform===`win32`?inspectCreationDirectorySync(e,!0):(assertPrivatePosixDirectory(t),assertDarwinCreationDirectoryAcl(e,t)),R(e,t)}async function assertPrivateDirectory(e){let t=R(e);process.platform===`win32`?await inspectCreationDirectory(e,!0):(assertPrivatePosixDirectory(t),assertDarwinCreationDirectoryAcl(e,t)),R(e,t)}function protectCreatedFileSync(e,t,n){let r=creationOperation(`protectPrivateWindowsFile`);return(r?r(e,t,n):protectPrivateWindowsFileCommandSync(e,t,n)).identity}async function protectCreatedFile(e,t,n){let r=creationOperation(`protectPrivateWindowsFile`);return(r?r(e,t,n):await protectPrivateWindowsFileCommand(e,t,n)).identity}function verifyCreatedFileSync(e,t,n,r,i=1){let a=creationOperation(`verifyPrivateWindowsFile`);a?a(e,t,n,r,i):verifyPrivateWindowsFileCommandSync(e,t,n,r,i)}async function verifyCreatedFile(e,t,n,r,i=1){let a=creationOperation(`verifyPrivateWindowsFile`);a?a(e,t,n,r,i):await verifyPrivateWindowsFileCommand(e,t,n,r,i)}function inspector(){let e=T();if(typeof e?.inspectDarwinAcl!=`function`)throw new N(`helper-unavailable`,`private Darwin creation requires native descriptor ACL inspection`);return e.inspectDarwinAcl.bind(e)}function assertDarwinPrivateCreationAvailable(){process.platform===`darwin`&&inspector()}function assertDarwinPrivateDirectoryMode(e){if(process.platform===`darwin`&&!(e&~process.umask()&320))throw new N(`helper-unavailable`,`private Darwin directory ACL inspection requires owner read or search permission`)}function assertDarwinCreationAcl(e,t){if(process.platform!==`darwin`)return;let n=inspector()(e,t)?.state;if(n===`present`)throw new N(`insecure-permissions`,t?`private creation parent has inheritable Darwin ACL entries`:`private creation object has Darwin ACL entries`);if(n!==`absent`&&n!==`empty`)throw new N(`helper-unavailable`,`native Darwin ACL inspection returned incomplete facts`)}function assertDarwinCreationDirectoryAcl(e,t,n){if(process.platform!==`darwin`)return;assertDarwinPrivateCreationAvailable();let r;try{r=W.openSync(e,_e())}catch(t){if(t.code!==`EACCES`)throw t;let n=ge();if(!n)throw t;try{r=W.openSync(e,n.flags|W.constants.O_DIRECTORY|W.constants.O_NOFOLLOW|W.constants.O_NONBLOCK)}catch(e){throw e.code===`EACCES`?new N(`helper-unavailable`,`private Darwin directory ACL inspection requires owner read or search permission`,{cause:e}):e}}try{if(!E(()=>W.fstatSync(r,{bigint:!0}),t).isDirectory())throw new N(`path-mismatch`,`ACL target is not the admitted directory`);assertDarwinCreationAcl(r,n),R(e,t)}finally{W.closeSync(r)}}function assertCreationFile(e,t,n){let r=E(()=>W.fstatSync(e,{bigint:!0}),n),i=E(()=>W.lstatSync(t,{bigint:!0}),r);if(!r.isFile()||!i.isFile()||i.isSymbolicLink()||r.nlink!==1n||i.nlink!==1n)throw new N(`path-mismatch`,`created file is not the expected single-linked regular file`);return r}function assertPrivateCreationFile(e,t){if(process.platform!==`win32`){if(typeof process.getuid!=`function`||e.uid!==BigInt(process.getuid()))throw new N(`not-owned`,`created private file must belong to the current user`);if((e.mode&3647n)!=0n)throw new N(`insecure-permissions`,`created private file is not owner-only`);assertDarwinCreationAcl(t)}}function assertRecordedFile(e,t){if(!e.isFile()||e.isSymbolicLink()||!le(e,t))throw new N(`path-mismatch`,`created file cleanup preserved a replacement`)}function removeRecordedCreationFileSync(e,t,n){n();let r;try{r=W.lstatSync(e,{bigint:!0})}catch(e){if(e?.code===`ENOENT`)return;throw e}assertRecordedFile(r,t),W.unlinkSync(e)}async function removeRecordedCreationFile(e,t,n){n();let r;try{r=await G.lstat(e,{bigint:!0})}catch(e){if(e?.code===`ENOENT`)return;throw e}n(),assertRecordedFile(r,t),assertRecordedFile(W.lstatSync(e,{bigint:!0}),t),await G.unlink(e)}function creationPublicationAfterFailure(e,t){if(e instanceof N){let t=e.details?.publication;if(t&&typeof t==`object`&&`status`in t&&t.status===`indeterminate`)return`indeterminate`}return t}function hasPreservedCreationArtifacts(e){if(!(e instanceof N))return!1;if(e.details?.cleanup===`preserved`||e.details?.cleanup===`failed`)return!0;let t=e.details?.publication;return typeof t==`object`&&!!t&&`status`in t&&(t.status===`published`||t.status===`indeterminate`)}function rethrowPrivateStageCreationFailure(e,t,n){if(e instanceof N&&e.code===`already-exists`)throw new N(`helper-failed`,`private file staging path already exists`,{cause:e,details:{publication:{status:`not-published`},path:t,stageDirectory:n}});let r=e instanceof N?e.details?.publication:void 0,i=e instanceof N&&e.details?.path===n&&typeof r==`object`&&!!r&&`status`in r&&r.status===`published`,a=hasUnsettledWindowsSecurityCommand(e);if(e!==null&&(typeof e==`object`||typeof e==`function`))try{let t=Object.getOwnPropertyDescriptor(e,`creationOutcome`);a||=!!(t&&`value`in t&&t.value===`unconfirmed`)}catch{a=!0}throw i||a?privateFileSettlementFailure({primary:e,cleanup:[],publication:`not-published`,path:t,stageDirectory:n,preserved:!0}):e}function privateFileSettlementFailure(e){return new N(`helper-failed`,`file creation or staging settlement failed`,{cause:e.cleanup.length?AggregateError([e.primary,...e.cleanup],`file creation and cleanup failed`):e.primary,details:{publication:{status:e.publication},path:e.path,stageDirectory:e.stageDirectory,cleanup:e.preserved||e.publication===`indeterminate`?`preserved`:e.cleanup.length?`failed`:`removed`}})}function assertBeforeCreation(e,t,n,r){t.private&&assertDarwinCreationDirectoryAcl(e.parent.dir,e.parent.stat,r),B(n?.(),`assertBeforeMutation`),(n!==void 0||t.private)&&e.assertParent(),t.private&&r===`directory`&&assertDarwinPrivateDirectoryMode(t.mode),t.private&&assertDarwinCreationDirectoryAcl(e.parent.dir,e.parent.stat,r)}function creationAdmissionFromParent(e){let{dev:t,ino:n}=e.stat;if(typeof t!=`bigint`||typeof n!=`bigint`)throw new N(`path-mismatch`,`private creation requires an exact parent identity`);let r=R(e.dir,{dev:t,ino:n});return{expectedParentIdentity:{dev:r.dev,ino:r.ino,realPath:e.realPath}}}function prepareCreationPath(e,t){if(t&&={dev:t.dev,ino:t.ino,realPath:t.realPath},b(e),S(e,`filesystem`),process.platform===`win32`&&e.replaceAll(`/`,`\\`).split(`\\`).some(e=>e.endsWith(`.`)||e.endsWith(` `)))throw new N(`invalid-path`,`creation path contains an ambiguous Windows component`);let n=l(e),r=U.dirname(n);if(n===r||e.length===0)throw new N(`invalid-path`,`creation requires a child name`);t&&L(r,t);let i=R(r),a=I.native(r),o={dir:r,realPath:a,stat:i},assertParent=()=>{L(r,{dev:i.dev,ino:i.ino,realPath:a}),t&&L(r,t)};return assertParent(),{target:n,parent:o,assertParent}}function creationCollision(e){return e?.code===`EEXIST`?new N(`already-exists`,`creation target already exists`,{cause:e}):e}function removeCreationDirectory(e,t,n){n();try{L(e,t),W.rmdirSync(e)}catch(e){if(e?.code!==`ENOENT`)throw e}}async function removeCreationDirectoryAsync(e,t,n){n();try{L(e,t),await G.rmdir(e)}catch(e){if(e?.code!==`ENOENT`)throw e}}const st=/* @__PURE__ */ new Set([`EACCES`,`EPERM`,`EXDEV`,`ENOTSUP`,`EOPNOTSUPP`,`ENOSYS`]);function isHardlinkFallbackError(e){return st.has(e?.code??``)}function pathMismatch(e){return new N(`path-mismatch`,e)}function assertInitialSource(e){if(e.isSymbolicLink())throw new N(`path-alias`,`isolated producer output must not be a symlink`);if(!e.isFile())throw new N(`not-file`,`isolated producer output must be a regular file`);if(e.nlink!==1n)throw new N(`hardlink`,`isolated producer output must have exactly one link`)}function inspectLinkedFile(e,t,n,r){return E(()=>{let t=e();if(t.isSymbolicLink()||!t.isFile()||t.nlink!==n)throw pathMismatch(`${r} changed during isolated producer handoff`);return t},t)}function assertParents(e){e.assertTargetParent(),e.assertSourceParent()}function normalizeLinkError(e){return e?.code===`EEXIST`?new N(`already-exists`,`isolated producer sibling already exists`,P(e)):isHardlinkFallbackError(e)?new N(`helper-unavailable`,`atomic isolated producer handoff is unavailable`,P(e)):e}function removeSiblingIfOwned(e){if(!e.state.siblingOwned)return;e.assertTargetParent();let t;try{t=W.lstatSync(e.targetPath,{bigint:!0})}catch(t){if(t?.code===`ENOENT`){e.state.siblingOwned=!1;return}throw t}if(t.isSymbolicLink()||!t.isFile()||t.nlink!==1n&&t.nlink!==2n||!le(t,e.identity))throw pathMismatch(`isolated producer sibling changed before cleanup`);W.unlinkSync(e.targetPath),e.state.siblingOwned=!1,e.assertTargetParent()}function combinedFailure(e,t){return t.length===0?e:AggregateError([e,...t],`isolated producer handoff and settlement failed`)}function hasCode(e,t){return!(e instanceof N)&&t.includes(e?.code??``)}async function throwAfterClosing(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let e of t)if(e&&!r.has(e)){r.add(e);try{await e.close()}catch(e){n.push(e)}}throw combinedFailure(e,n)}function inspectSourceDescriptor(e,t,n=1n){return inspectLinkedFile(()=>W.fstatSync(e.fd,{bigint:!0}),t,n,`isolated producer descriptor`)}function historicalOpenFlags(e){return(e?W.constants.O_RDWR:W.constants.O_RDONLY)|z()}async function openHistoricalSource(e,t,n,r){let i;try{return i=await G.open(e,historicalOpenFlags(n)),inspectSourceDescriptor(i,t,r),i}catch(e){if(i)return await throwAfterClosing(e,[i]);throw e}}async function openProducerSource(e,t,n=1n){if(process.platform!==`win32`)return await openHistoricalSource(e.sourcePath,t,e.readWrite,n);let r;try{r=await G.open(e.sourcePath,W.constants.O_WRONLY)}catch(r){if(!hasCode(r,[`EACCES`,`EPERM`,`EBUSY`]))throw r;return await openHistoricalSource(e.sourcePath,t,e.readWrite,n)}try{return inspectSourceDescriptor(r,t,n),r}catch(e){if(!hasCode(e,[`EACCES`,`EPERM`]))return await throwAfterClosing(e,[r])}let i;try{i=await G.open(e.sourcePath,historicalOpenFlags(e.readWrite)),inspectSourceDescriptor(i,t,n),inspectLinkedFile(()=>W.lstatSync(e.sourcePath,{bigint:!0}),t,n,`isolated producer path`),assertParents(e)}catch(e){return await throwAfterClosing(e,[i,r])}try{await r.close()}catch(e){return await throwAfterClosing(e,[i])}return i}var FileHandoff=class{paths;identity;createdLabels;siblingOwned=!1;publication=`not-published`;cleanup=`preserved`;closeFailed=!1;constructor(e,t,n=!1){this.paths=e,this.identity=t,this.createdLabels=n}inspect(e,t){assertParents(this.paths);let n=inspectLinkedFile(()=>W.fstatSync(e.fd,{bigint:!0}),this.identity,t,this.createdLabels?`created file descriptor`:`isolated producer descriptor`);return this.cleanup!==`removed`&&inspectLinkedFile(()=>W.lstatSync(this.paths.sourcePath,{bigint:!0}),this.identity,t,this.createdLabels?`created file stage`:`isolated producer path`),{opened:n,named:this.publication===`published`?inspectLinkedFile(()=>W.lstatSync(this.paths.targetPath,{bigint:!0}),this.identity,t,this.createdLabels?`created file destination`:`isolated producer sibling`):void 0}}publish(){this.publication=`indeterminate`;try{W.linkSync(this.paths.sourcePath,this.paths.targetPath)}catch(e){let t=normalizeLinkError(e);throw t instanceof N&&(t.code===`already-exists`||t.code===`helper-unavailable`)&&(this.publication=`not-published`),t}this.publication=`published`}retireSource(){this.cleanup=`failed`,W.unlinkSync(this.paths.sourcePath),this.cleanup=`removed`}failure(e,t){let n=e[0];return new N(this.closeFailed||e.length>1?`helper-failed`:n instanceof N?n.code:`helper-failed`,`created file publication failed`,{cause:e.length===1?n:AggregateError(e,t),details:{publication:{status:this.publication},cleanup:this.cleanup,resources:this.closeFailed?`close-failed`:`closed`,path:this.paths.targetPath,dev:this.identity.dev,ino:this.identity.ino}})}};async function handoffFile(e){let t=`source`in e?e:void 0,n=t?.identity??E(()=>{assertParents(e);let t=W.lstatSync(e.sourcePath,{bigint:!0});return assertInitialSource(t),t}),r=t?.source,i=new Set(r?[r]:[]),a=[],o,s=new FileHandoff(e,n);async function close(e){t&&i.delete(e);try{await e.close(),i.delete(e)}catch(e){throw s.closeFailed=!0,e}}try{assertInitialSource(n),r||(r=await openProducerSource({...e,readWrite:`readWrite`in e&&e.readWrite},n),i.add(r)),s.inspect(r,1n),t?.verifyDescriptor&&await t.verifyDescriptor(r.fd,e.sourcePath,1),t||(o=ve(e.targetPath,{cleanupSync:()=>removeSiblingIfOwned({assertTargetParent:e.assertTargetParent,identity:n,state:s,targetPath:e.targetPath})})),B(t?.assertBeforeMutation?.(),`assertBeforeMutation`),s.inspect(r,1n),s.publish(),s.siblingOwned=!t;try{B(t?.onPublished?.(),`onPublished`)}catch(e){a.push(e)}if(s.inspect(r,2n),process.platform===`win32`){let a=t?await G.open(e.targetPath,historicalOpenFlags(!0)):await openProducerSource({...e,sourcePath:e.targetPath,readWrite:`readWrite`in e&&e.readWrite},n,2n);i.add(a),s.inspect(a,2n),t?.verifyDescriptor&&await t.verifyDescriptor(a.fd,e.targetPath,2),s.inspect(a,2n),inspectSourceDescriptor(r,n,2n),await close(r),r=a,s.inspect(r,2n)}t?.verifyDescriptor&&await t.verifyDescriptor(r.fd,process.platform===`win32`?e.targetPath:e.sourcePath,2),B(t?.assertBeforeMutation?.(),`assertBeforeMutation`),s.inspect(r,2n),s.retireSource(),t?.verifyDescriptor&&await t.verifyDescriptor(r.fd,e.targetPath,1);let{opened:c,named:l}=s.inspect(r,1n),u=n.mode&511n;if(!t&&process.platform===`win32`&&(u&128n)==0n&&((c.mode&511n)!==u||(l.mode&511n)!==u)){assertParents(e),W.fchmodSync(r.fd,Number(u));let t=s.inspect(r,1n);if((t.opened.mode&511n)!==u||(t.named.mode&511n)!==u)throw pathMismatch(`isolated producer read-only mode could not be restored`)}if(!t){let e=o,release=(()=>{s.siblingOwned=!1,e()});return release.setIdentity=e.setIdentity,{handle:r,identity:n,unregister:release}}}catch(e){a.push(e)}if(a.length===0)return r;if(o)try{removeSiblingIfOwned({assertTargetParent:e.assertTargetParent,identity:n,state:s,targetPath:e.targetPath}),o()}catch(e){a.push(e)}for(let e of[...i].reverse())try{await close(e)}catch(e){a.push(e)}throw t?s.failure(a,`isolated producer handoff and settlement failed`):combinedFailure(a[0],a.slice(1))}function handoffCreatedFile(e){return handoffFile(e)}function handoffCreatedFileSync(e){let t=e.source,n=/* @__PURE__ */ new Set([t]),r=[],i=new FileHandoff(e,e.identity,!0);function close(e){n.delete(e);try{e.close()}catch(e){throw i.closeFailed=!0,e}}function verifyCurrent(t,n,r){i.inspect(t,r),e.verifyDescriptor?.(t.fd,n,Number(r))}try{assertInitialSource(e.identity),verifyCurrent(t,e.sourcePath,1n),B(e.assertBeforeMutation?.(),`assertBeforeMutation`),i.inspect(t,1n),i.publish();try{e.onPublished?.()}catch(e){r.push(e)}if(process.platform===`win32`){verifyCurrent(t,e.sourcePath,2n);let r=ownFileDescriptorSync(W.openSync(e.targetPath,W.constants.O_RDWR|z()));n.add(r),verifyCurrent(r,e.targetPath,2n),inspectLinkedFile(()=>W.fstatSync(t.fd,{bigint:!0}),e.identity,2n,`created file descriptor`),close(t),t=r}let a=process.platform===`win32`?e.targetPath:e.sourcePath;verifyCurrent(t,a,2n),B(e.assertBeforeMutation?.(),`assertBeforeMutation`),i.inspect(t,2n),i.retireSource(),verifyCurrent(t,e.targetPath,1n)}catch(e){r.push(e)}if(r.length===0)return t;for(let e of n)try{close(e)}catch(e){r.push(e)}throw i.failure(r,`created file publication and settlement failed`)}function createPrivateWindowsFile(e,t,n){let r=t.assertBeforeMutation;if(W.lstatSync(e.target,{throwIfNoEntry:!1}))throw new N(`already-exists`,`creation target already exists`);let i=inspectCreationDirectorySync(e.parent.dir,!1);e.assertParent();let a=U.join(e.parent.dir,`.fs-safe-create-${Ve()}`),o;try{o=createDirectoryWithReceiptSync(a,{private:!0,assertBeforeMutation:r},{expectedParentIdentity:e.parent.stat})}catch(t){rethrowPrivateStageCreationFailure(t,e.target,a)}let s=o.windowsIdentity,c=U.join(a,`file`),assertStage=()=>{e.assertParent(),L(a,o.stat)},l,u,f,p=`not-published`;try{if(inspectCreationDirectorySync(a,!0)!==s)throw new N(`path-mismatch`,`private staging directory changed before file creation`);return B(r?.(),`assertBeforeMutation`),assertStage(),d(c),l=ownFileDescriptorSync(W.openSync(c,W.constants.O_RDWR|W.constants.O_CREAT|W.constants.O_EXCL|z(),384)),u=assertCreationFile(l.fd,c),B(r?.(),`assertBeforeMutation`),assertStage(),assertCreationFile(l.fd,c,u),f=protectCreatedFileSync(l.fd,c,s),assertStage(),l=handoffCreatedFileSync({source:l,sourcePath:c,targetPath:e.target,identity:u,assertSourceParent:assertStage,assertTargetParent:e.assertParent,assertBeforeMutation:r,verifyDescriptor:(e,t,n)=>verifyCreatedFileSync(e,t,f,t===c?s:i,n),onPublished:()=>{p=`published`}}),W.fchmodSync(l.fd,n),e.assertParent(),u=assertCreationFile(l.fd,e.target,u),verifyCreatedFileSync(l.fd,e.target,f,i),removeCreationDirectory(a,o.stat,e.assertParent),l}catch(t){p=creationPublicationAfterFailure(t,p);let n=[];if(l)try{l.close()}catch(e){n.push(e)}if(p!==`indeterminate`){if(u)try{removeRecordedCreationFileSync(c,u,assertStage)}catch(e){n.push(e)}try{removeCreationDirectory(a,o.stat,e.assertParent)}catch(e){n.push(e)}}throw p===`not-published`&&n.length===0?creationCollision(t):privateFileSettlementFailure({primary:t,cleanup:n,publication:p,path:e.target,stageDirectory:a})}}function createFileSync(e,t={}){return createFileWithAdmissionSync(e,t)}function createFileWithAdmissionSync(e,t={},n={}){let r=resolveCreationPermissions(t,!1),i=t.assertBeforeMutation,a=prepareCreationPath(e,n.expectedParentIdentity);if(r.private&&process.platform===`win32`)return assertPrivateFileCreationAvailable(),createPrivateWindowsFile(a,{...r,assertBeforeMutation:i},r.mode);assertBeforeCreation(a,r,i,`file`);let o;try{d(a.target),o=ownFileDescriptorSync(W.openSync(a.target,W.constants.O_RDWR|W.constants.O_CREAT|W.constants.O_EXCL|z(),r.mode??438))}catch(e){throw creationCollision(e)}try{let e=assertCreationFile(o.fd,a.target);return a.assertParent(),r.private&&assertPrivateCreationFile(e,o.fd),o}catch(e){let t=e;try{o.close()}catch(n){t=AggregateError([e,n],`created file admission and close failed`)}throw new N(`helper-failed`,`created file admission failed`,{cause:t,details:{publication:{status:`published`},path:a.target,cleanup:`preserved`}})}}async function createFileHandle(e,t={},n={}){let r=resolveCreationPermissions(t,!1),i=t.assertBeforeMutation;if(process.platform!==`win32`||!r.private){let t=prepareCreationPath(e,n.expectedParentIdentity);assertBeforeCreation(t,r,i,`file`);try{d(t.target)}catch(e){throw creationCollision(e)}let a=await G.open(t.target,W.constants.O_RDWR|W.constants.O_CREAT|W.constants.O_EXCL|z(),r.mode??438).catch(e=>{throw creationCollision(e)});try{let e=assertCreationFile(a.fd,t.target);return t.assertParent(),r.private&&assertPrivateCreationFile(e,a.fd),a}catch(e){let n=e;try{await a.close()}catch(t){n=AggregateError([e,t],`created file admission and close failed`)}throw new N(`helper-failed`,`created file handle admission failed`,{cause:n,details:{publication:{status:`published`},path:t.target,cleanup:`preserved`}})}}return assertPrivateFileCreationAvailable(),await createPrivateWindowsFileHandle(prepareCreationPath(e,n.expectedParentIdentity),{mode:r.mode,assertBeforeMutation:i})}function directoryAdoptionFailure(e,t,n){return new N(`helper-failed`,`created directory admission failed`,{cause:e,details:{publication:{status:`published`},path:t,cleanup:`preserved`,...n===void 0?{}:{windowsIdentity:n}}})}function privateDirectoryBackend(){let e=T();if(typeof e?.createPrivateDirectoryWithParentIdentity==`function`)return e.createPrivateDirectoryWithParentIdentity.bind(e);if(A().mode===`require`)throw new N(`helper-unavailable`,`private directory creation requires an up-to-date native parent identity capability`);warnNativeFallback(`windows-private-directory`,`Private Windows directory creation launches the packaged .NET helper for each check or creation.`,`createPrivateDirectoryWithParentIdentity`)}async function createDirectoryWithAdmission(e,t={},n={}){await createDirectoryWithReceipt(e,t,n)}async function createDirectoryWithReceipt(e,t={},n={}){let r=resolveCreationPermissions(t,!0),i=t.assertBeforeMutation,a=prepareCreationPath(e,n.expectedParentIdentity),o=r.private&&process.platform===`win32`?privateDirectoryBackend():void 0,s=r.private&&process.platform===`win32`?await inspectCreationDirectory(a.parent.dir,!1):void 0;assertBeforeCreation(a,r,i,`directory`);let c=!1,l;try{if(s!==void 0){let e=o?o(a.target,s):await createPrivateWindowsDirectoryCommand(a.target,s);if(c=!0,l=e.identity,await inspectCreationDirectory(a.target,!0)!==e.identity)throw new N(`path-mismatch`,`created private directory changed before adoption`)}else await G.mkdir(a.target,{mode:r.mode}),c=!0,r.private&&await assertPrivateDirectory(a.target);return a.assertParent(),{stat:R(a.target),windowsIdentity:l}}catch(e){throw c?directoryAdoptionFailure(e,a.target,l):creationCollision(e)}}function createDirectorySync(e,t={}){createDirectoryWithReceiptSync(e,t,{})}function createDirectoryWithReceiptSync(e,t={},n={}){let r=resolveCreationPermissions(t,!0),i=t.assertBeforeMutation,a=prepareCreationPath(e,n.expectedParentIdentity),o=r.private&&process.platform===`win32`?privateDirectoryBackend():void 0,s=r.private&&process.platform===`win32`?inspectCreationDirectorySync(a.parent.dir,!1):void 0;assertBeforeCreation(a,r,i,`directory`);let c=!1,l;try{if(s!==void 0){let e=o?o(a.target,s):createPrivateWindowsDirectoryCommandSync(a.target,s);if(c=!0,l=e.identity,inspectCreationDirectorySync(a.target,!0)!==e.identity)throw new N(`path-mismatch`,`created private directory changed before adoption`)}else W.mkdirSync(a.target,{mode:r.mode}),c=!0,r.private&&assertPrivateDirectorySync(a.target);return a.assertParent(),{stat:R(a.target),windowsIdentity:l}}catch(e){throw c?directoryAdoptionFailure(e,a.target,l):creationCollision(e)}}async function createPrivateWindowsFileHandle(e,t){let n=t.assertBeforeMutation,r=await G.lstat(e.target).catch(e=>{if(e.code!==`ENOENT`)throw e});if(e.assertParent(),r)throw new N(`already-exists`,`creation target already exists`);let i=await inspectCreationDirectory(e.parent.dir,!1);e.assertParent();let a=U.join(e.parent.dir,`.fs-safe-create-${Ve()}`),o;try{o=await createDirectoryWithReceipt(a,{private:!0,assertBeforeMutation:n},{expectedParentIdentity:e.parent.stat})}catch(t){rethrowPrivateStageCreationFailure(t,e.target,a)}let s=o.windowsIdentity,c=U.join(a,`file`),assertStage=()=>{e.assertParent(),L(a,o.stat)},l,u,f=`not-published`;try{if(await inspectCreationDirectory(a,!0)!==s)throw new N(`path-mismatch`,`private staging directory changed before file creation`);B(n?.(),`assertBeforeMutation`),assertStage(),d(c),l=await G.open(c,W.constants.O_RDWR|W.constants.O_CREAT|W.constants.O_EXCL|z(),384),assertStage(),u=assertCreationFile(l.fd,c),B(n?.(),`assertBeforeMutation`),assertStage(),assertCreationFile(l.fd,c,u);let r=await protectCreatedFile(l.fd,c,s);assertStage(),assertCreationFile(l.fd,c,u);let p=l;return l=void 0,l=await handoffCreatedFile({source:p,sourcePath:c,targetPath:e.target,identity:u,assertSourceParent:assertStage,assertTargetParent:e.assertParent,assertBeforeMutation:n,verifyDescriptor:(e,t,n)=>verifyCreatedFile(e,t,r,t===c?s:i,n),onPublished:()=>{f=`published`}}),B(n?.(),`assertBeforeMutation`),e.assertParent(),assertCreationFile(l.fd,e.target,u),await verifyCreatedFile(l.fd,e.target,r,i),e.assertParent(),assertCreationFile(l.fd,e.target,u),await l.chmod(t.mode),await verifyCreatedFile(l.fd,e.target,r,i),e.assertParent(),assertCreationFile(l.fd,e.target,u),await removeCreationDirectoryAsync(a,o.stat,e.assertParent),e.assertParent(),assertCreationFile(l.fd,e.target,u),l}catch(t){f=creationPublicationAfterFailure(t,f);let n=f===`indeterminate`||hasUnsettledWindowsSecurityCommand(t),r=[];if(l){let e=l;l=void 0;try{await e.close()}catch(e){r.push(e)}}if(!n){if(u)try{await removeRecordedCreationFile(c,u,assertStage)}catch(e){r.push(e)}try{await removeCreationDirectoryAsync(a,o.stat,e.assertParent)}catch(e){r.push(e)}}throw f===`not-published`&&r.length===0&&!n?creationCollision(t):privateFileSettlementFailure({primary:t,cleanup:r,publication:f,path:e.target,stageDirectory:a,preserved:n})}}async function writeAllToFile(e,t,n={}){let r=typeof t==`string`?Buffer.from(t,n.encoding??`utf8`):t,i=0;for(;i<r.byteLength;){let t=Math.min(524288,r.byteLength-i),a=n.position===void 0?null:n.position+i;n.assertBeforeMutation?.();let o=typeof e==`number`?await new Promise((n,o)=>{W.write(e,r,i,t,a,(e,t)=>{e?o(e):n(t)})}):(await e.write(r,i,t,a)).bytesWritten;if(o<=0)throw new N(`helper-failed`,`file write made no progress`);i+=o}}const ct=Object.freeze([]);function createTransferBuffer(e,t){return Buffer.allocUnsafe(Math.min(524288,Math.max(65536,e),t+1))}function copyFileDescriptorSync(e,t,n={}){let r=n.signal;r?.throwIfAborted();let i=pe(n.maxBytes),a=n.onChunk,o=n.assertBeforeMutation,s=E(()=>(r?.throwIfAborted(),W.fstatSync(e,{bigint:!0})));if(!s.isFile())throw new N(`not-file`,`copy source descriptor must be a regular file`);if(i!==void 0&&Number.isFinite(i)&&s.size>BigInt(i))throw new N(`too-large`,`file exceeds limit of ${i} bytes`);let c=E(()=>(r?.throwIfAborted(),W.fstatSync(t,{bigint:!0})));if(!c.isFile())throw new N(`not-file`,`copy target descriptor must be a regular file`);if(s.dev===c.dev&&s.ino===c.ino)throw new N(`path-alias`,`copy source and target descriptors refer to the same file`);let l=i??1/0,u=createTransferBuffer(Number(s.size),l),d=0;for(;;){r?.throwIfAborted();let n=W.readSync(e,u,0,Math.min(u.length,l-d+1),d);if(n>l-d)throw new N(`too-large`,`file exceeds limit of ${l} bytes`);if(n===0)return d;let i=u.subarray(0,n);B(a?.(i),`onChunk`);let s=0;for(;s<n;){r?.throwIfAborted(),B(o?.(),`assertBeforeMutation`),r?.throwIfAborted();let e=W.writeSync(t,i,s,n-s,d+s);if(e<=0)throw new N(`helper-failed`,`file write made no progress`);s+=e}d+=n}}function transferFileHandle(e,t,n){try{let r=n.maxBytes,i=n.sizeHint,a=n.targetPosition,o=n.signal,s=n.onChunk,c=n.assertBeforeMutation;return transferFileHandleCore(e,t,i,r,a,o,s,o===void 0&&c===void 0?void 0:()=>{o?.throwIfAborted(),c&&Reflect.apply(c,n,ct)},n)}catch(e){return Promise.reject(e)}}async function transferFileHandleCore(e,t,n,r,i,a,o,s,c){let l=r??1/0,u=createTransferBuffer(n,l),d=0;for(;;){a?.throwIfAborted();let{bytesRead:n}=await e.read(u,0,Math.min(u.length,l-d+1),d);if(a?.throwIfAborted(),n>l-d)throw new N(`too-large`,`file exceeds limit of ${l} bytes`);if(n===0)return d;let r=u.subarray(0,n);if(o){let e=Function.prototype.call.call(o,c,r);B(e,`onChunk`)}await writeAllToFile(t,r,{position:i===void 0?void 0:i+d,assertBeforeMutation:s}),d+=n}}function recordFileOpenFailure(e,t){throw k(e,`open:${t}`),e}function recordExclusiveCreateFailure(e,t){throw k(e,`exclusive-create:${t}`),e}function openedPathResolutionError(e=new N(`path-mismatch`,`unable to resolve opened file path`)){return k(e,`resolution`),e}async function recordPreOpenFileChange(e,t,n,r,i){if(de(e,`identity`)&&r?.isFile()&&i?.isFile()&&[0n,1n].includes(r.nlink)&&[0n,1n].includes(i.nlink))try{await j(async()=>r);let a=await j(()=>W.fstatSync(t.fd,{bigint:!0}),i);a.isFile()&&[0n,1n].includes(a.nlink)&&(r.dev!==a.dev||r.ino!==a.ino)&&k(e,`changed:${n}`)}catch{}}async function recordOpenedFileFailure(e,t,n,r){if(!(!de(e,`resolution`)&&!de(e,`identity`)||!r.isFile()||r.nlink>1n))try{let i=await j(()=>W.fstatSync(t.fd,{bigint:!0}),r);i.isFile()&&i.nlink===0n&&k(e,`unlinked:${n}`)}catch{}}const ensureTrailingSep=e=>e.endsWith(U.sep)?e:e+U.sep;function assertValidRootRelativePath(e){b(e,`relative path contains a NUL byte`),S(e,`filesystem`,`relative path uses a Windows filesystem namespace alias`)}function assertValidRootDestinationPath(e){if(assertValidRootRelativePath(e),_(e))throw new N(`invalid-path`,`relative path must not start with a drive letter`)}let J;const lt=/(?:^|\/)\.\.(?:\/|$)/,ut=/(?:^|[\\/])\.\.(?:[\\/]|$)/;async function expandRelativePathWithHome(e){let t=e===`~`,n=e.startsWith(`~/`)||U.sep===`\\`&&e.startsWith(`~\\`);if(!t&&!n)return S(e,`filesystem`,`relative path uses a Windows filesystem namespace alias`),e;let r=process.env.HOME||process.env.USERPROFILE||He.homedir();if(S(r,`filesystem`,`home path uses a Windows filesystem namespace alias`),J?.raw!==r){let e=r;try{e=I.native(x(r))}catch{}J={raw:r,real:e}}if(t)return S(J.real,`filesystem`,`home path uses a Windows filesystem namespace alias`),J.real;let i=`${ensureTrailingSep(J.real)}${e.slice(2)}`;return S(i,`filesystem`,`expanded path uses a Windows filesystem namespace alias`),i}async function resolveRootContext(e){b(e,`root dir contains a NUL byte`),S(e,`filesystem`,`root dir uses a Windows filesystem namespace alias`);let t=l(e);S(t,`filesystem`,`root dir uses a Windows filesystem namespace alias`);let n,r,i;try{n=I.native(x(e)),S(n,`filesystem`,`canonical root path uses a Windows filesystem namespace alias`),r=await j(()=>{let e=W.statSync(n,{bigint:!0});if(!e.isDirectory())throw new N(`invalid-path`,`root dir is not a directory`);return e}),i={dev:r.dev,ino:r.ino}}catch(e){throw e instanceof N?e:g(e)?new N(`not-found`,`root dir not found`):e}return{rootDir:t,rootGuard:{dir:n,realPath:n,stat:r},rootIdentity:i,rootReal:n,rootWithSep:ensureTrailingSep(n)}}function rootRelativeReadPath(e,t){if(!U.isAbsolute(t))return t;let n=process.platform===`win32`?t.replaceAll(`/`,U.sep):t,r=e.rootDir===e.rootReal?[e.rootReal]:[e.rootDir,e.rootReal];for(let t of r){if(process.platform===`win32`){let r=C({rootPath:t,candidatePath:n,rootIdentity:e.rootIdentity,resolveCandidateRoot:t===e.rootDir&&e.rootDir!==e.rootReal});if(r)return`.${U.sep}${r.relativePath}`;continue}let r=ensureTrailingSep(t);if(n.startsWith(r)){let e=r.length;for(;n[e]===U.sep;)e+=1;return`.${U.sep}${n.slice(e)}`}}return n}function assertRootIdentityCurrentSync(e,t){try{let n=R(e.rootReal,{dev:e.rootIdentity.dev,ino:e.rootIdentity.ino});t?.(n)}catch(e){throw me(e instanceof Error?e:void 0)}}async function assertRootIdentityCurrent(e,t){assertRootIdentityCurrentSync(e,t)}async function createRootObservationGuard(e){let t=e.rootIdentity;if(typeof t?.dev!=`bigint`||typeof t.ino!=`bigint`)throw me();try{let n=await re(e.rootReal,t);return te(n,e.rootReal,e.rootReal)}catch(e){throw me(e instanceof Error?e:void 0)}}async function resolvePathInRoot(e,t,n){assertValidRootRelativePath(t),await assertRootIdentityCurrent(e);let r=await expandRelativePathWithHome(t);S(r,`filesystem`,`expanded path uses a Windows filesystem namespace alias`);let i=w(e.rootWithSep,r);if(S(i,`filesystem`,`resolved path uses a Windows filesystem namespace alias`),!n?.resolveCanonical&&!ce(e.rootWithSep,i))throw y();n?.rejectUnsafeDeviceReads===!0&&m(i);let a=U.isAbsolute(r)?r:`${e.rootWithSep}${r}`;S(a,`filesystem`,`resolved path uses a Windows filesystem namespace alias`);try{let t={absolutePath:a,rootPath:e.rootReal,rootCanonicalPath:e.rootReal,rootIdentity:e.rootIdentity,boundaryLabel:`root`,policy:n?.allowFinalSymlink?he.unlinkTarget:void 0,rejectSymlinks:n?.rejectSymlinks,rejectFinalSymlink:n?.rejectFinalSymlink},o=await O(t),s=process.platform===`win32`?ut:lt;if(n?.rejectAmbiguousParents&&s.test(r)&&U.relative(o.canonicalPath,i)!==``){let e=await O({...t,absolutePath:i});if(U.relative(o.canonicalPath,e.canonicalPath)!==``)throw new N(`path-alias`,`parent traversal resolves differently through a symlink`)}if(n?.resolveCanonical)i=o.canonicalPath;else{let t=C({rootPath:e.rootReal,candidatePath:o.absolutePath,rootIdentity:e.rootIdentity});if(!t)throw y();i=t.path}}catch(e){let t=s(e,a);if(t)throw t;if(e instanceof N&&e.code===`symlink`)throw e;if(c(e,`ENAMETOOLONG`))throw new N(`invalid-path`,`relative path is too long`,P(e));let r=n?.aliasErrorCode??`outside-workspace`;throw new N(r,r===`path-alias`?`path alias escape blocked`:`file is outside workspace root`,P(e))}return{rootReal:e.rootReal,rootWithSep:e.rootWithSep,resolved:i}}function resolveFinalOpenedRealPath(e){try{return I.native(e)}catch(e){throw process.platform===`win32`&&e instanceof Error&&[`EPERM`,`EBADF`].includes(e.code??``)?openedPathResolutionError(e):e}}function inspectOpenedPathIdentitySync(e,t){let n=t===`follow-within-root`?W.statSync(e,{bigint:!0}):W.lstatSync(e,{bigint:!0});if(n.isSymbolicLink()&&t!==`follow-within-root`)throw new N(`symlink`,`symlink not allowed`);return n}async function admitRootReadHandle(e){try{if(e.hardlinks!==`allow`&&e.opened.stat.nlink>1)throw ae();e.beforeFinalFence&&await e.beforeFinalFence(e.filePath,e.opened.handle);try{assertRootIdentityCurrentSync(e.root);let t;try{let n=E(()=>inspectOpenedPathIdentitySync(e.filePath,e.symlinks),e.identity);if(e.hardlinks!==`allow`&&n.nlink>1n)throw ae();let r=resolveFinalOpenedRealPath(e.filePath);S(r,`filesystem`,`resolved file path uses a Windows filesystem namespace alias`);let i=C({rootPath:e.root.rootReal,candidatePath:r,rootIdentity:e.root.rootIdentity});if(!i)throw openedPathResolutionError(y());let a=E(()=>inspectOpenedPathIdentitySync(r,void 0),e.identity);if(e.hardlinks!==`allow`&&a.nlink>1n)throw ae();t=i.path}catch(e){throw g(e)?openedPathResolutionError(oe()):e}return e.afterPathIdentityCheck?.(e.filePath,e.opened.handle),assertRootIdentityCurrentSync(e.root),{...e.opened,realPath:t}}catch(t){throw e.identity.nlink<=1n&&await recordOpenedFileFailure(t,e.opened.handle,e.filePath,e.identity),t}}catch(t){throw await e.opened.handle.close().catch(()=>{}),t}}const dt=Symbol(`checked mutation directory observation`),ft=/* @__PURE__ */ new WeakMap;function identity(e){return Object.freeze({dev:e.dev,ino:e.ino,mode:e.mode,nlink:e.nlink})}function sameIdentity(e,t,n=!1){return e.dev===t.dev&&e.ino===t.ino&&e.mode===t.mode&&(n||e.nlink===t.nlink)}function directoryMode(e){return(e&61440n)==16384n}function absent(e){try{return W.lstatSync(e,{throwIfNoEntry:!1})===void 0}catch(e){return g(e)&&e.code===`ENOENT`}}function missingMutationSegments(e){return e.missingSegments.length-e.missingOffset}function nextMissingMutationPath(e){let t=e.missingSegments[e.missingOffset];return t===void 0?void 0:U.join(e.ancestor,t)}function checkedMutationDirectory(e,t,n,r){if(!directoryMode(n.mode))throw TypeError(`mutation directory evidence must describe a real directory`);let i=Object.freeze({path:e,canonicalPath:t,identity:identity(n),[dt]:!0});return r&&ft.set(i,r),i}function checkedDirectory(e){return e[dt]===!0&&U.isAbsolute(e.path)&&U.isAbsolute(e.canonicalPath)&&directoryMode(e.identity.mode)}function mutationObservationUsesDirectory(e,t){return checkedDirectory(t)&&e.ancestor===t.path&&e.canonicalAncestor===t.canonicalPath&&sameIdentity(e.entry,t.identity)&&sameIdentity(e.identity,t.identity)}function observeMutationPath(e){try{let t=e,n=[];for(;absent(t);){let e=U.dirname(t);if(e===t)return;n.push(U.basename(t)),t=e}n.reverse();let r=Object.freeze(n),i=E(()=>W.lstatSync(t,{bigint:!0})),a=I.native(t),o=a===t?i:E(()=>W.lstatSync(a,{bigint:!0}));if(o.isSymbolicLink()||r.length>0&&!o.isDirectory())return;let s=Object.freeze({path:e,ancestor:t,canonicalAncestor:a,canonicalPath:U.join(a,...r),entry:identity(i),identity:identity(o),missingSegments:r,missingOffset:0});return mutationObservationCurrent(s)?s:void 0}catch{return}}function mutationObservationCurrent(e){try{let t=E(()=>W.lstatSync(e.ancestor,{bigint:!0}));if(!sameIdentity(e.entry,t,t.isDirectory())||I.native(e.ancestor)!==e.canonicalAncestor)return!1;let n=e.canonicalAncestor===e.ancestor?t:E(()=>W.lstatSync(e.canonicalAncestor,{bigint:!0}));return sameIdentity(e.identity,n,n.isDirectory())&&(missingMutationSegments(e)===0||n.isDirectory()&&absent(nextMissingMutationPath(e)))}catch{return!1}}function mutationObservationsCurrent(e,t){let n=/* @__PURE__ */ new Map,groupFor=e=>{let t=n.get(e);return t||(t={observations:[],directories:[]},n.set(e,t)),t};try{for(let t of e)if(t.ancestor!==t.canonicalAncestor){if(!mutationObservationCurrent(t))return!1}else groupFor(t.ancestor).observations.push(t);for(let e of t){if(!checkedDirectory(e))return!1;groupFor(e.path).directories.push(e)}let current=(e,t)=>{let n=new Set(t.observations.flatMap(e=>{let t=nextMissingMutationPath(e);return t===void 0?[]:[t]}));if(t.directories.length&&![...n].every(absent))return!1;let r=t.directories.length?ft.get(t.directories[0])?.():void 0,i=r?.identity??E(()=>W.lstatSync(e,{bigint:!0})),a=r?.canonicalPath??I.native(e),o=directoryMode(i.mode);return!t.observations.every(e=>a===e.canonicalAncestor&&sameIdentity(e.entry,i,o)&&sameIdentity(e.identity,i,o)&&(missingMutationSegments(e)===0||o))||!t.directories.every(e=>o&&sameIdentity(e.identity,i)&&a===e.canonicalPath)?!1:t.directories.length>0||[...n].every(absent)};for(let[e,t]of n)if(!t.directories.length&&!current(e,t))return!1;let r=/* @__PURE__ */ new Set;for(let e of t)if(!r.has(e.path)){if(!current(e.path,n.get(e.path)))return!1;r.add(e.path)}return!0}catch{return!1}}function advanceMutationObservation(e,t,n){let r=nextMissingMutationPath(e);if(r===void 0||r!==n.path)return e;if(checkedDirectory(t)&&checkedDirectory(n)&&e.ancestor===t.path&&e.canonicalAncestor===t.canonicalPath&&sameIdentity(e.entry,t.identity,!0)&&sameIdentity(e.identity,t.identity,!0)&&t.path===t.canonicalPath&&n.path===n.canonicalPath&&U.dirname(n.path)===t.path)return Object.freeze({...e,ancestor:n.path,canonicalAncestor:n.canonicalPath,entry:n.identity,identity:n.identity,missingOffset:e.missingOffset+1})}function exactIdentityMatches(e,t){return[`dev`,`ino`].every(n=>{let r=e[n];return(typeof r==`bigint`||Number.isSafeInteger(r))&&BigInt(r)===t[n]})}function describeStagedDirectory(e,t){let n=W.fstatSync(e,{bigint:!0});if(!n.isDirectory())throw new N(`not-file`,`staging parent must be a directory`);let r=Object.freeze({path:l(t),realPath:I(t),identity:Object.freeze({dev:n.dev,ino:n.ino})});return assertStagedDirectoryCurrent(r),r}function assertStagedDirectoryCurrent(e){let t=W.lstatSync(e.path,{bigint:!0});if(!t.isDirectory()||!exactIdentityMatches(e.identity,t)||I(e.path)!==e.realPath)throw new N(`path-mismatch`,`staging directory pathname changed`);return t}function assertNativeStagedDirectoryCurrent(e,t,n){if(typeof e.stagedDirectoryMatches==`function`&&n.path===n.realPath)try{if(!e.stagedDirectoryMatches(t,n.path,n.identity.dev,n.identity.ino))throw new N(`path-mismatch`,`staging directory pathname changed`);return}catch(e){if(e?.code!==`OBSERVATION_UNAVAILABLE`)throw e}assertStagedDirectoryCurrent(n)}function describeNativeStagedDirectory(e,t,n){let r=W.fstatSync(t,{bigint:!0});if(!r.isDirectory())throw new N(`not-file`,`staging parent must be a directory`);let i=l(n),a=Object.freeze({path:i,realPath:i,identity:Object.freeze({dev:r.dev,ino:r.ino})});return assertNativeStagedDirectoryCurrent(e,t,a),{directory:a,stat:r}}function sameDirectoryMetadata(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.mode===t.mode&&e.nlink===t.nlink}function describePolicyStagedDirectory(e,t,n){let r=U.resolve(t),i=W.fstatSync(e,{bigint:!0});if(!i.isDirectory())throw new N(`not-file`,`staging parent must be a directory`);let a=nativePolicyDirectoryObserver(n,e,r),o=a?.();if(o){if(!sameDirectoryMetadata(i,o.identity))throw new NativePolicyDirectoryMismatch;let e=Object.freeze({path:r,realPath:o.canonicalPath,identity:Object.freeze({dev:i.dev,ino:i.ino})});return Object.freeze({directory:e,observation:checkedMutationDirectory(r,o.canonicalPath,o.identity,a),stat:i,observeCurrent:a,disposeObservation:a.dispose})}let s=R(r),c=U.resolve(I.native(r)),l=R(r,i);if(c!==r||!sameDirectoryMetadata(i,s)||!sameDirectoryMetadata(i,l)||U.resolve(I.native(r))!==c)throw new N(`path-mismatch`,`staging directory pathname changed`);let u=Object.freeze({path:r,realPath:c,identity:Object.freeze({dev:i.dev,ino:i.ino})});return Object.freeze({directory:u,observation:checkedMutationDirectory(r,c,l),stat:l})}function assertPolicyStagedDirectoryCurrent(e){let t=e.observeCurrent?.();if(t){if(!sameDirectoryMetadata(e.stat,t.identity)||t.canonicalPath!==e.directory.realPath)throw new N(`path-mismatch`,`staging directory pathname changed`);return e.stat}let n=R(e.directory.path,e.directory.identity);if(!sameDirectoryMetadata(e.stat,n)||U.resolve(I.native(e.directory.path))!==e.directory.realPath)throw new N(`path-mismatch`,`staging directory pathname changed`);return n}function refreshPolicyStagedDirectoryObservation(e){let t=e.observeCurrent?.();if(t){if(!exactIdentityMatches(e.directory.identity,t.identity)||t.canonicalPath!==e.directory.realPath)throw new N(`path-mismatch`,`staging directory pathname changed`);return checkedMutationDirectory(e.directory.path,t.canonicalPath,t.identity,e.observeCurrent)}let n=R(e.directory.path,e.directory.identity),r=U.resolve(I.native(e.directory.path));if(r!==e.directory.realPath)throw new N(`path-mismatch`,`staging directory pathname changed`);return checkedMutationDirectory(e.directory.path,r,n)}function openStagedDirectory(e){let t=typeof e==`string`?void 0:be(xe(e)),n=l(typeof e==`string`?e:t.path),r=W.lstatSync(n,{bigint:!0});if(!r.isDirectory())throw new N(`not-file`,`staging parent must be a real directory`);if(t&&(!exactIdentityMatches(t.identity,r)||I(n)!==t.realPath))throw new N(`path-mismatch`,`stale staging directory receipt`);let i=W.openSync(n,W.constants.O_RDONLY|W.constants.O_DIRECTORY|W.constants.O_NOFOLLOW|W.constants.O_NONBLOCK);try{let e=describeStagedDirectory(i,n);if(!exactIdentityMatches(r,e.identity))throw new N(`path-mismatch`,`staging directory changed while opening`);return{fd:i,receipt:e}}catch(e){try{W.closeSync(i)}catch(t){throw AggregateError([e,t],`staging directory admission and close failed`)}throw e}}function copyError(e){if(e instanceof N)return e;let t=e?.code;return new N(t===`EEXIST`?`already-exists`:t===`ENOENT`?`not-found`:t===`too-large`?`too-large`:[`ENOTSUP`,`EOPNOTSUPP`,`ENOSYS`,`EXDEV`,`EINVAL`].includes(t??``)?`unsupported-platform`:`helper-failed`,`guarded synchronous file copy failed`,{cause:e})}function copyRootFileSync(e){return copyRootFileWithAdmissionSync(e,createCopyPathAdmissionCache())}function copyRootFileWithAdmissionSync(e,t){let n=e.source,r={rootPath:n.rootPath,absolutePath:n.absolutePath},i=e.destination,a={rootPath:i.rootPath,absolutePath:i.absolutePath},o=e.expectedSourceIdentity,s=o===void 0?void 0:ie(o),c=s&&{dev:s.dev,ino:s.ino},l=resolveCopyCloneMode(e.clone,`never`),u=pe(e.maxBytes),f=e.mode,p=e.preserveSourceMode,m=e.sourceHardlinks??`reject`;if(f!==void 0&&(!Number.isInteger(f)||f<0||f>511))throw new N(`invalid-path`,`copy mode must be an integer from 0 to 0o777`);if(m!==`allow`&&m!==`reject`)throw new N(`invalid-path`,`invalid copy source hardlink policy`);let h,g,_,v=!1,y,b,x=process.platform===`win32`?T():T(`copyFileExclusiveSync`,`removeStagedFile`),S=process.platform!==`win32`&&x?.copyFileExclusiveSync&&x.removeStagedFile?x.copyFileExclusiveSync.bind(x):void 0;try{let e=t.admit(r);if(y=t.admit(a,!0),d(a.absolutePath),W.lstatSync(y.path,{throwIfNoEntry:!1}))throw new N(`already-exists`,`copy destination already exists`);let n=ne({...r,rootRealPath:e.rootCanonicalPath,boundaryLabel:`copy source`,maxBytes:u,rejectHardlinks:m!==`allow`});if(!n.ok)throw n.error??new N(`helper-failed`,`copy source admission failed`);h=ownFileDescriptorSync(n.fd);let i=E(()=>W.fstatSync(n.fd,{bigint:!0}),c),verifySource=()=>{e.assertCurrent();for(let t of[()=>W.fstatSync(n.fd,{bigint:!0}),()=>inspectOpenedPathIdentitySync(e.path,void 0)]){let e=E(t,i);if(!e.isFile())throw new N(`not-file`,`copy source must be a regular file`);if(m!==`allow`&&e.nlink>1n)throw new N(`hardlink`,`copy source must not be hardlinked`)}},o=f??(p?Number(i.mode&511n):384&~process.umask()),s;if(verifySource(),y.assertCurrent(),S){let e=ue(x),t=openStagedDirectory(y.parent.realPath);_=ownFileDescriptorSync(t.fd),v=!0,E(()=>W.fstatSync(t.fd,{bigint:!0}),{dev:BigInt(y.parent.stat.dev),ino:BigInt(y.parent.stat.ino)}),y.assertCurrent();try{s=S(n.fd,t.fd,U.basename(y.path),l,u!==void 0&&Number.isFinite(u)?u:void 0)}catch(e){throw ye(e,y.path),e}g=ownFileDescriptorSync(s.fd,e)}else{if(l===`always`)throw new N(`unsupported-platform`,`synchronous native file cloning is unavailable`);g=createFileWithAdmissionSync(y.path,{mode:384,assertBeforeMutation:y.assertCurrent},creationAdmissionFromParent(y.parent))}b=E(()=>W.fstatSync(g.fd,{bigint:!0}));let verifyTarget=()=>{y.assertCurrent();let e=E(()=>W.fstatSync(g.fd,{bigint:!0}),b),t=E(()=>inspectOpenedPathIdentitySync(y.path,void 0),b);if(!e.isFile()||e.nlink!==1n||!t.isFile()||t.nlink!==1n)throw new N(`path-mismatch`,`copy destination changed`);return e};if(verifyTarget(),s?.errorCode)throw copyError(Object.assign(Error(s.errorMessage),{code:s.errorCode}));let C=s?s.method:`copy`;if(C!==`clone`&&C!==`copy-file-range`&&C!==`copy`)throw new N(`helper-failed`,`native copy returned an unknown method`);s||copyFileDescriptorSync(n.fd,g.fd,{maxBytes:u}),verifySource();let w=verifyTarget();if(u!==void 0&&Number.isFinite(u)&&w.size>BigInt(u))throw new N(`too-large`,`copy exceeds maxBytes`);return W.fchmodSync(g.fd,o),verifySource(),verifyTarget(),h.close(),v=!1,_?.close(),Object.freeze({...g,path:y.path,bytes:Number(w.size),method:C,identity:Object.freeze({dev:b.dev,ino:b.ino}),sourceIdentity:Object.freeze({dev:i.dev,ino:i.ino})})}catch(e){let t=copyError(e),n=[];if(g&&y)try{if(v){if(x.removeStagedFile(_.fd,U.basename(y.path),g.fd)===`preserved`)throw new N(`path-mismatch`,`copy cleanup preserved a replacement`)}else b&&removeRecordedCreationFileSync(y.path,b,y.assertCurrent)}catch(e){n.push(e)}for(let e of[g,h,_])try{e?.close()}catch(e){n.push(e)}throw n.length?new N(t.code,t.message,{cause:AggregateError([t,...n],`copy and cleanup failed`),details:{path:y?.path,cleanup:`failed`}}):t}}const pt=/* @__PURE__ */ new WeakSet;function markPrivateDirectoryCreationRefused(e){return typeof e==`object`&&e&&pt.add(e),e}function isPrivateDirectoryCreationRefused(e){return typeof e==`object`&&!!e&&pt.has(e)}function assertExpectedContent(e,t,n){if(e.sizeBytes!==t.sizeBytes)throw Error(`SQLite snapshot size mismatch for ${n}: expected ${t.sizeBytes}, got ${e.sizeBytes}`);if(e.sha256!==t.sha256)throw Error(`SQLite snapshot hash mismatch for ${n}: expected ${t.sha256}, got ${e.sha256}`)}function assertPublishedFileIdentitySync(e,t,n){let r=W.lstatSync(e,{bigint:!0});if(!r.isFile()||!sameFileStatFingerprint(t,r))throw Error(`SQLite snapshot file changed: ${e}`);(t.mtimeMs!==r.mtimeMs||t.ctimeMs!==r.ctimeMs)&&assertExpectedContent(hashPublishedFileSync(e,t),n,e)}function assertOpenFileIdentitySync(e,t,n){let r=W.fstatSync(e,{bigint:!0}),i=W.lstatSync(t,{bigint:!0});if(!r.isFile()||!i.isFile()||!F(n,r)||!F(n,i))throw Error(`SQLite snapshot file changed: ${t}`)}function hashPublishedFileSync(e,t,n=Se){let r=W.openSync(e,`r`);try{assertOpenFileIdentitySync(r,e,t);let i=W.fstatSync(r,{bigint:!0}),a=n(r),o=W.fstatSync(r,{bigint:!0});if(!Ce(i,o)){if(!sameFileStatFingerprint(i,o))throw Error(`SQLite snapshot file changed while reading: ${e}`);assertExpectedContent(n(r),a,e)}return assertOpenFileIdentitySync(r,e,t),a}finally{W.closeSync(r)}}function sameFileStatFingerprint(e,t){return F(e,t)&&e.size===t.size}const Y=[`owner.sqlite`,`owner.sqlite-journal`,`owner.sqlite-wal`,`owner.sqlite-shm`];var SqliteStagingRetiredError=class extends Error{constructor(){super(`SQLite snapshot parent retired; aborting snapshot allocation`)}};function acquireSqliteStagingToken(e,t,n={}){let r=Ae,acquire=()=>acquireStagingToken(e,t,n),i=t===`create`?acquire():r(acquire),a=Object.assign(e=>r(()=>i(e)),{beginRetirement:()=>(r(()=>i.beginRetirement()),a)});return a}function acquireStagingToken(e,n,r){let i=U.join(e,Y[0]),readIdentity=(e,t)=>{let n=W.lstatSync(e,{bigint:!0});if(!(t===`directory`?n.isDirectory():n.isFile())||process.platform===`win32`&&(n.dev===0n||n.ino===0n))throw Error(`SQLite staging ownership is unknown`);return n},a=readIdentity(e,`directory`),o=Y.map(t=>W.lstatSync(U.join(e,t),{throwIfNoEntry:!1})),s=o[0];if(o.some(e=>e&&(!e.isFile()||process.getuid&&e.uid!==process.getuid()))||!s&&n!==`create`&&!r.allowMissing)throw Error(`SQLite snapshot token ownership is unknown`);n===`create`&&!s&&W.writeFileSync(i,``,{flag:`wx`,mode:420});let c=s!==void 0||n===`create`,l=c?readIdentity(i,`file`):void 0;if(r.expectedIdentity){if(!l)throw Error(`SQLite staging ownership is unknown`);Me(l,r.expectedIdentity)}let u=je(()=>Le(c?Ie(i):i,{timeout:0},l&&ke(l))),d,read=e=>Fe(u,e,[],e=>e.get()),f=n===`reclaim`||n===`create`&&r.exclusiveCreate===!0,p=!1,assertIdentity=()=>{let t=readIdentity(e,`directory`);if(a.dev!==t.dev||a.ino!==t.ino)throw Error(`SQLite staging ownership changed before retirement`);let n=readIdentity(i,`file`);if(d.dev!==n.dev||d.ino!==n.ino)throw Error(`SQLite staging ownership changed before retirement`)},beginRetirement=()=>(assertIdentity(),u.isTransaction&&f||(u.isTransaction&&u.exec(`ROLLBACK`),u.exec(`BEGIN EXCLUSIVE`),f=!0),m),release=(e=!1)=>{u.isOpen&&(e?(beginRetirement(),p||u.exec(`PRAGMA user_version=1`),u.exec(`COMMIT`),p=!0):u.isTransaction&&u.exec(`ROLLBACK`),u.close(),e&&V(i))},m=Object.assign(release,{beginRetirement});try{if(d=l??readIdentity(i,`file`),f?u.exec(`BEGIN EXCLUSIVE`):n===`create`?u.exec(`BEGIN IMMEDIATE`):u.exec(`BEGIN`),n!==`create`||s){let e=read(`PRAGMA journal_mode`);if(!t(e)||e.journal_mode!==`delete`)throw Error(`SQLite snapshot token journal mode is unknown`);let r=read(`PRAGMA user_version`),i=t(r)?r.user_version:void 0;if(i!==0&&(n!==`reclaim`||i!==1))throw new SqliteStagingRetiredError;p=i===1}return assertIdentity(),m}catch(e){throw release(),e}}const mt=`openclaw-sqlite-readonly-v2-`,ht=`(?:[A-Za-z0-9]{6}|[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12})$`,gt=RegExp(`^openclaw-sqlite-readonly-[1-9]\\d*-${ht}`,`u`),_t=RegExp(`^${mt}${ht}`,`u`),vt=/^\.fs-safe-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.tmp$/u,yt=864e5;function releaseTokens(e){let t=Be(e,e=>e());if(t.length)throw AggregateError(t,`SQLite snapshot retirement token release failed`)}const isSqliteSnapshotStagingName=e=>gt.test(e)||_t.test(e);function acquireSqliteSnapshotToken(e,t){return acquireSqliteStagingToken(e,t,{allowMissing:gt.test(U.basename(e))})}function beginSqliteSnapshotRetirement(e,t={}){let n=[],r=[],release=()=>releaseTokens(n.filter(e=>e!==t.token));if(!W.existsSync(e))return t.token?.(),{bytes:0,payload:r,release,retire:()=>{}};function inspect(i,a,o=``,s=!0){let c=W.lstatSync(i);if(!c.isDirectory()||process.getuid&&c.uid!==process.getuid())throw Error(`Snapshot directory ownership is unknown`);let l=!o&&gt.test(U.basename(i));if(!o&&t.allowLegacy===!1&&!_t.test(U.basename(i)))throw Error(`Legacy or unrecognized snapshot requires offline operator cleanup`);let u=t.cutoff!==void 0&&l?Math.min(a,Date.now()-yt):a,d=l?`Legacy snapshot contains activity newer than 24 hours`:`Snapshot contains activity within the reclamation grace period`;if(c.mtimeMs>=u)throw Error(d);l&&s&&t.cutoff!==void 0&&inspect(i,u,o,!1),!o&&s&&n.push(i===e&&t.token?t.token.beginRetirement():acquireSqliteSnapshotToken(i,`reclaim`));let f=0,p=c.mtimeMs;for(let e of W.readdirSync(i,{withFileTypes:!0})){let n=U.join(i,e.name),a=W.lstatSync(n);if(process.getuid&&a.uid!==process.getuid())throw Error(`Snapshot file ownership is unknown`);if(o&&t.cutoff!==void 0||!a.isFile()||!Y.some(t=>t===e.name)){if(p=Math.max(p,a.mtimeMs),a.isDirectory()){let r=isSqliteSnapshotStagingName(e.name),i=r?``:[o,e.name].filter(Boolean).join(`/`);if(t.cutoff!==void 0&&(!r&&![`openclaw`,`openclaw-state`,`openclaw-state/state`].includes(i)&&!/^openclaw\/sqlite-[a-f0-9]{24}$/u.test(i)||r&&o!==``&&o!==`openclaw`&&!/^openclaw\/sqlite-[a-f0-9]{24}$/u.test(o)))throw Error(`Unrecognized snapshot directory`);let a=inspect(n,u,i,s);f+=a.bytes,p=Math.max(p,a.newest)}else if(t.cutoff===void 0||a.isFile()&&(o===`openclaw-state/state`?/^openclaw\.sqlite(?:-wal|-shm|-journal)?$/u.test(e.name):!o&&(/^(?:first|database\.sqlite(?:\.partial)?(?:-wal|-shm|-journal)?)$/u.test(e.name)||e.name===`schema-discovery-ownership.json`||vt.test(e.name)||/^inspection-result-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.json$/u.test(e.name))))f+=a.size,s&&r.push(n);else throw Error(`Unrecognized snapshot artifact`)}}if(p>=u)throw Error(d);return{bytes:f,newest:p}}try{let{bytes:i}=inspect(e,t.cutoff??1/0);return{bytes:i,payload:r,release,retire:()=>{for(let e of n)e(!0)}}}catch(e){throw release(),e}}function deferSqliteSnapshotCleanupAfterRead(e,t){let n=e instanceof Ee?e:e instanceof H?e.cause:void 0;if(!(n instanceof Ee))return!1;try{o({subsystem:`infra/sqlite-snapshot`}).warn({path:t,errorCode:a(n.cause)},`SQLite snapshot cleanup deferred until open files are released.`)}catch{}return!0}function settleSqliteSnapshotRequest(e){return e.result.catch(async t=>{let n=t;try{await e.startClose().result}catch(e){if(e!==t){let r=De([t,e],`SQLite snapshot allocation and cleanup failed`,t);n=t instanceof H?new H(t.message,{cause:r}):r}}throw we(n),n})}const X=n(Symbol.for(`openclaw.sqliteSnapshotCleanup`),()=>({directories:/* @__PURE__ */ new Map,activeWork:/* @__PURE__ */ new Map,exitHandlerInstalled:!1,pendingSignalCleanup:void 0,signalCleanup:cleanupSnapshotOperations})),Z=X.directories,Q=X.activeWork;function snapshotDirectory(e){let t=Z.get(e);return t||(t={readers:/* @__PURE__ */ new Set},Z.set(e,t)),t}function completeSnapshotDirectoryRemoval(e){return Z.delete(e),!0}function cleanupSnapshotOperations(){return X.pendingSignalCleanup??=(async()=>{let e=Z.entries();for(;;){for(;Q.size>0;){for(let e of Q.values())e();await Promise.allSettled(Q.keys())}let t=e.next();if(t.done)break;let[n]=t.value;await removeTempDirectoryAsync(n,e=>emitSnapshotCleanupFailure({cleanupRoot:n,operation:`rm`,code:a(e)}))}})().finally(()=>{X.pendingSignalCleanup=void 0}),X.pendingSignalCleanup}function retainSnapshotWork(e,t=()=>{}){registerSnapshotCleanup(),Q.set(e,t);let release=()=>Q.delete(e);return e.then(release,release),e}function registerSnapshotTempDirectory(e,t){let n=snapshotDirectory(e);n.release=t??n.release,registerSnapshotCleanup()}function registerSnapshotCleanup(){X.exitHandlerInstalled||(X.exitHandlerInstalled=!0,i(()=>{for(let e of Q.values())e();if(Q.size===0)for(let e of Z.keys())removeTempDirectory(e)})),r(X.signalCleanup)}function registerRetainedSnapshotTempDirectory(e,t){snapshotDirectory(e).releaseRetained=t,registerSnapshotCleanup()}function retainSnapshotTempDirectory(e){registerSnapshotTempDirectory(e);let t=snapshotDirectory(e);if(t.retirementStarted)throw new H(`SQLite snapshot retirement has started`);let n=Symbol(`sqlite.snapshot.reader`);return t.readers.add(n),()=>t.readers.delete(n)}function releaseSnapshotTempDirectory(e){let t=Z.get(e);if(assertSnapshotReadersRetired(t),t?.releaseRetained)throw new H(`SQLite snapshot requires asynchronous cleanup`);t?.release?.(!1),Z.delete(e)}const $={force:!0,maxRetries:3,recursive:!0,retryDelay:20};function emitSnapshotCleanupFailure(e,t){if(t)try{t(e);return}catch{}try{o({subsystem:`infra/sqlite-snapshot`}).warn({path:e.cleanupRoot,operation:e.operation,errorCode:e.code},`SQLite read-only snapshot cleanup failed. Check directory permissions and available storage before retrying.`)}catch{}}function assertSnapshotReadersRetired(e){if(e?.readers.size)throw new H(`SQLite snapshot still belongs to an active reader`)}function prepareSnapshotRetirement(e,t){if(assertSnapshotReadersRetired(t),t?.releaseRetained)throw new H(`SQLite snapshot requires asynchronous cleanup`);if(!(t?.retired||!t?.release&&!W.existsSync(U.join(e,Y[0]))))return t&&(t.retirementStarted=!0),beginSqliteSnapshotRetirement(e,{token:t?.release})}function*shrinkSnapshotPayload(e){let t=W.lstatSync(e,{throwIfNoEntry:!1});if(t?.isDirectory())for(let t of W.readdirSync(e))yield*shrinkSnapshotPayload(U.join(e,t));else if(t?.isFile()&&t.nlink>1)W.unlinkSync(e);else if(t?.isFile()&&t.nlink===1&&t.size>64*1024**2){let n=W.openSync(e,W.constants.O_RDWR|W.constants.O_NOFOLLOW);try{for(let e=t.size;e>64*1024**2;)e-=64*1024**2,yield{fd:n,size:e}}finally{W.closeSync(n)}}}async function shrinkSnapshotPayloadAsync(e){for(let{fd:t,size:n}of shrinkSnapshotPayload(e))await retainSnapshotWork(new Promise((e,r)=>{W.ftruncate(t,n,t=>t?r(t):e())}))}function*retireSqliteSnapshotPayload(e){for(let t of e.payload){V(t);for(let{fd:e,size:n}of shrinkSnapshotPayload(t))W.ftruncateSync(e,n),yield;W.rmSync(t,$)}e.retire()}function removeTempDirectory(e,t){let n=Z.get(e);n&&(n.cleanupFailure=void 0);try{let t=prepareSnapshotRetirement(e,n);try{if(t){for(let e of retireSqliteSnapshotPayload(t));n=snapshotDirectory(e),n.release=void 0,n.retired=!0}else if(!n?.retired)for(let{fd:t,size:n}of shrinkSnapshotPayload(e))W.ftruncateSync(t,n);try{W.rmSync(e,$)}catch(t){throw Te(e,t)}}finally{t?.release()}return completeSnapshotDirectoryRemoval(e)}catch(n){return registerSnapshotTempDirectory(e),snapshotDirectory(e).cleanupFailure=n,t?.(n),!1}}async function removeTempDirectoryAsync(e,t){let n=Z.get(e);if(n?.releaseRetained){let r=await startRemoveTempDirectory(e,t,n).result;return r&&Z.delete(e),r}n&&(n.cleanupFailure=void 0);try{let t=prepareSnapshotRetirement(e,n);try{for(let e of t?.payload??[])V(e),await shrinkSnapshotPayloadAsync(e),await retainSnapshotWork(W.promises.rm(e,$));t?(t.retire(),n=snapshotDirectory(e),n.release=void 0,n.retired=!0):n?.retired||await shrinkSnapshotPayloadAsync(e);try{await retainSnapshotWork(W.promises.rm(e,$))}catch(t){throw Te(e,t)}}finally{t?.release()}return completeSnapshotDirectoryRemoval(e)}catch(n){return registerSnapshotTempDirectory(e),snapshotDirectory(e).cleanupFailure=n,t?.(n),!1}}function startRemoveTempDirectory(e,t,n=Z.get(e)){if(n?.retiringRetained)return n.retiringRetained;let r,i=ze(()=>{if(!r||i.operation.read().status!==`pending`)return;r.service();let a=r.read();a.status!==`pending`&&(n&&(n.retiringRetained=void 0),a.status===`rejected`?(snapshotDirectory(e).cleanupFailure=a.error,t?.(a.error),i.resolve(!1)):i.resolve(completeSnapshotDirectoryRemoval(e)))});try{if(n&&(n.cleanupFailure=void 0),sealRetainedSnapshotTempDirectory(e),!n?.releaseRetained)throw new H(`SQLite snapshot has no retained cleanup owner`);n.retiringRetained=i.operation,r=n.releaseRetained(),r.result.then(()=>i.operation.service(),()=>i.operation.service()),i.operation.service()}catch(r){snapshotDirectory(e).cleanupFailure=r,n&&(n.retiringRetained=void 0),t?.(r),i.resolve(!1)}return i.operation}function sealRetainedSnapshotTempDirectory(e,t){let n=Z.get(e);if(!n?.releaseRetained)throw new H(`SQLite snapshot has no retained cleanup owner`);if(t?.requireRequested&&!n.retirementStarted)throw new H(`SQLite snapshot is still owned; cleanup has not been requested`);let r=[...Z].filter(([t])=>ce(e,t));for(let[,e]of r)assertSnapshotReadersRetired(e);for(let[,e]of r)e.retirementStarted=!0;let i=/* @__PURE__ */ new Set([...Oe().map(({location:e})=>e),...Ne()]);for(let t of i)ce(e,t)&&V(t)}function preparationCleanupError(t,n){return De(t,`${n} and cleanup failed: ${e(t[0])}`,t[0])}function discardPreparedCopyPayload(e,t){try{for(let t of[`database.sqlite`,`database.sqlite.partial`])for(let n of[``,`-wal`,`-shm`,`-journal`]){let r=U.join(e,`${t}${n}`);V(r);for(let{fd:e,size:t}of shrinkSnapshotPayload(r))W.ftruncateSync(e,t);W.rmSync(r,{force:!0})}}catch(e){throw preparationCleanupError([t,e],`SQLite snapshot preparation`)}}async function cleanupFailedSnapshotPreparation(e,t,n,r){if(r)discardPreparedCopyPayload(e,t);else{let r=[t];if(!await removeTempDirectoryAsync(e,e=>r.push(e)))throw preparationCleanupError(r,n)}throw t}function publishPreparedCopy(e,t){let n=U.join(e,`database.sqlite`);for(let t of[`-wal`,`-shm`,`-journal`,``]){let i=`${n}.partial${t}`;if(W.existsSync(i)){let a=`${n}${t}`;try{W.renameSync(i,a)}catch(t){try{var r=Pe();if(!c(t,`EXDEV`))throw t;let n=r.u(copyRootFileSync({source:{rootPath:e,absolutePath:i},destination:{rootPath:e,absolutePath:a},mode:384}));W.fsyncSync(n.fd);for(let{fd:e,size:t}of shrinkSnapshotPayload(i))W.ftruncateSync(e,t);W.rmSync(i,{force:!0})}catch(e){r.e=e}finally{r.d()}}}}let i;if(t){let e=W.lstatSync(n,{bigint:!0});assertExpectedContent(hashPublishedFileSync(n,e),t,n),i={...t,identity:e}}return{...adoptPreparedLocation(n,e),journalFreeContent:i}}function adoptPreparedLocation(e,t,n=!1,r){let i=t??U.dirname(e);registerSnapshotTempDirectory(i);let o=!0,s,c,l=!1,reportFailure=e=>{!n&&!l&&(l=!0,emitSnapshotCleanupFailure({cleanupRoot:i,operation:`rm`,code:a(e)},r))},complete=e=>{if(e)o=!1,Z.delete(i);else if(n)throw new H(`SQLite read-only worker snapshot cleanup failed: ${i}`,{cause:Z.get(i)?.cleanupFailure});return e},startCleanup=()=>{if(c?.read().status===`pending`)return c;if(!o){let e=ze(()=>{});return e.resolve(complete(!0)),c=e.operation}return c=Re(startRemoveTempDirectory(i,reportFailure),complete)};return{location:e,cleanupRoot:i,cleanup:()=>s||c?.read().status===`pending`?n?complete(!1):!1:complete(!o||removeTempDirectory(i,reportFailure)),cleanupAsync:()=>Z.get(i)?.releaseRetained||c?startCleanup().result:s||(o?(s=Promise.resolve().then(()=>removeTempDirectoryAsync(i,reportFailure)).then(complete).finally(()=>{s=void 0}),s):Promise.resolve(complete(!0))),startCleanup}}const bt=`SqliteSnapshotCapacityError`;var SqliteSnapshotCapacityError=class extends Error{constructor(e,t){super(e,t),this.name=bt}};function hasSqliteSnapshotCapacityCode(e){let{code:t,errcode:n}=e;return t===`ENOSPC`||t===`EDQUOT`||n===13}function isSqliteSnapshotCapacityError(e){return e instanceof Error&&!(e instanceof AggregateError)&&e.name===bt}export{assertValidRootDestinationPath as $,markPrivateDirectoryCreationRefused as A,refreshPolicyStagedDirectoryObservation as B,mt as C,creationAdmissionFromParent as Ct,hashPublishedFileSync as D,nativePolicyDirectoryObserver as Dt,assertPublishedFileIdentitySync as E,NativePolicyDirectoryMismatch as Et,describeNativeStagedDirectory as F,mutationObservationUsesDirectory as G,checkedMutationDirectory as H,describePolicyStagedDirectory as I,observeMutationPath as J,mutationObservationsCurrent as K,describeStagedDirectory as L,assertNativeStagedDirectoryCurrent as M,assertPolicyStagedDirectoryCurrent as N,sameFileStatFingerprint as O,resolveCopyCloneMode as Ot,assertStagedDirectoryCurrent as P,assertRootIdentityCurrentSync as Q,exactIdentityMatches as R,yt as S,assertPrivateFileCreationAvailable as St,beginSqliteSnapshotRetirement as T,resolveCreationPermissions as Tt,missingMutationSegments as U,advanceMutationObservation as V,mutationObservationCurrent as W,inspectOpenedPathIdentitySync as X,admitRootReadHandle as Y,assertRootIdentityCurrent as Z,retainSnapshotWork as _,createFileSync as _t,cleanupFailedSnapshotPreparation as a,resolveRootContext as at,settleSqliteSnapshotRequest as b,assertPrivateCreationFile as bt,discardPreparedCopyPayload as c,recordExclusiveCreateFailure as ct,registerRetainedSnapshotTempDirectory as d,recordPreOpenFileChange as dt,assertValidRootRelativePath as et,registerSnapshotTempDirectory as f,transferFileHandle as ft,retainSnapshotTempDirectory as g,createFileHandle as gt,removeTempDirectoryAsync as h,createDirectoryWithAdmission as ht,adoptPreparedLocation as i,resolvePathInRoot as it,copyRootFileSync as j,isPrivateDirectoryCreationRefused as k,preparationCleanupError as l,recordFileOpenFailure as lt,removeTempDirectory as m,createDirectorySync as mt,hasSqliteSnapshotCapacityCode as n,ensureTrailingSep as nt,cleanupSnapshotOperations as o,rootRelativeReadPath as ot,releaseSnapshotTempDirectory as p,writeAllToFile as pt,nextMissingMutationPath as q,isSqliteSnapshotCapacityError as r,expandRelativePathWithHome as rt,deferSqliteSnapshotCleanupAfterRead as s,openedPathResolutionError as st,SqliteSnapshotCapacityError as t,createRootObservationGuard as tt,publishPreparedCopy as u,recordOpenedFileFailure as ut,retireSqliteSnapshotPayload as v,isHardlinkFallbackError as vt,acquireSqliteSnapshotToken as w,hasPreservedCreationArtifacts as wt,startRemoveTempDirectory as x,assertPrivateDirectory as xt,sealRetainedSnapshotTempDirectory as y,assertDarwinCreationAcl as yt,openStagedDirectory as z};