UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 16.3 kB
import e from"node:fs";import t from"node:path";import{URL as n,fileURLToPath as r}from"node:url";import{AsyncLocalStorage as i}from"node:async_hooks";const a=/* @__PURE__ */ new Set([`helper-failed`,`helper-unavailable`,`not-empty`,`not-found`,`not-removable`,`permission-denied`,`permission-unverified`,`read-failed`,`timeout`,`unsupported-platform`]);function categorizeFsSafeError(e){return a.has(e)?`operational`:`policy`}var FsSafeError=class extends Error{code;category;details;constructor(e,t,n={}){super(t,n),this.name=`FsSafeError`,this.code=e,this.category=categorizeFsSafeError(e),this.details=n.details}};function normalizeNullableString(e){return typeof e==`string`&&e.trim()||null}function normalizeOptionalString(e){return normalizeNullableString(e)??void 0}function normalizeOptionalLowercaseString(e){return normalizeOptionalString(e)?.toLowerCase()}function normalizeLowercaseStringOrEmpty(e){return normalizeOptionalLowercaseString(e)??``}function isWindowsSeparator(e,t){let n=e.charCodeAt(t);return n===47||n===92}function hasWindowsDrivePrefix(e,t=0){let n=e.charCodeAt(t)|32;return n>=97&&n<=122&&e.charCodeAt(t+1)===58}function windowsNamespaceMarker(e){let t=e[2];return(t===`.`||t===`?`)&&isWindowsSeparator(e,0)&&isWindowsSeparator(e,1)&&isWindowsSeparator(e,3)?t:void 0}function rootedWindowsDriveColonIndex(e){let t=hasWindowsDrivePrefix(e)?1:windowsNamespaceMarker(e)!==void 0&&hasWindowsDrivePrefix(e,4)?5:-1;return t>=0&&isWindowsSeparator(e,t+1)?t:-1}function asciiLowercase(e){return e.replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32))}function windowsSegmentsClimbAbove(e){let t=0;for(let n of e)if(n!==``&&n!==`.`&&(t+=/^[. ]+$/.test(n)?-1:1,t<0))return!0;return!1}function windowsShareOrDeviceRoot(e){if(!isWindowsSeparator(e,0)||!isWindowsSeparator(e,1))return;let n=e.replaceAll(`/`,`\\`);if(windowsNamespaceMarker(n)===void 0)return asciiLowercase(t.win32.parse(n).root.replace(/\\+$/,``));let r=n.slice(4).split(`\\`),i=asciiLowercase(r[0]??``),a=i===`unc`?r.slice(0,3):r.slice(0,1);if(i===`globalroot`||i===`global`||a.length<(i===`unc`?3:1)||a.some(e=>e===``||/[. ]$/.test(e))||windowsSegmentsClimbAbove(r.slice(a.length)))return null;if(rootedWindowsDriveColonIndex(e)!==5)return asciiLowercase(i===`unc`?`\\\\${a[1]}\\${a[2]}`:`${n.slice(0,4)}${a[0]}`)}function isExactlyUnderWindowsPath(e,t){let n=e.replaceAll(`/`,`\\`).replace(/(?<=.)\\+$/,``),r=t.replaceAll(`/`,`\\`);return r!==n&&!r.startsWith(n.endsWith(`\\`)?n:`${n}\\`)?!1:!windowsSegmentsClimbAbove(r.slice(n.length).split(`\\`))}function isForeignWindowsShareOrDevicePath(e,t,n=process.platform){if(n!==`win32`)return!1;let r=windowsShareOrDeviceRoot(e);return r!==void 0&&!t.some(t=>t!==void 0&&(r!==null&&windowsShareOrDeviceRoot(t)===r||isExactlyUnderWindowsPath(t,e)))}function isBareWindowsNamespaceDrive(e){return e.length===6&&windowsNamespaceMarker(e)!==void 0&&hasWindowsDrivePrefix(e,4)}function anchorWindowsDriveRelativePath(e){if(process.platform!==`win32`||t.isAbsolute(e)||!hasWindowsDrivePrefix(e))return e;let n=e.slice(0,2);return`${t.resolve(n)}${t.sep}${e.slice(2)}`}function resolvePathPreservingWindowsRoot(e){return e.length===7&&process.platform===`win32`&&rootedWindowsDriveColonIndex(e)===5?e.includes(`/`)?e.replaceAll(`/`,`\\`):e:repairResolvedWindowsRoot(e,t.resolve(e))}function repairResolvedWindowsRoot(e,t){return t.length===6&&process.platform===`win32`&&isBareWindowsNamespaceDrive(t)&&!hasWindowsPathAlias(e,`filesystem`)?`${t}\\`:t}function resolvePathFromBasePreservingWindowsRoot(e,...n){let r=t.resolve(e,...n);return r.length!==6||process.platform!==`win32`||!isBareWindowsNamespaceDrive(r)||hasWindowsPathAlias(e,`filesystem`)||n.some(e=>hasWindowsPathAlias(e,`filesystem`))?r:`${r}\\`}function pathForWindowsFilesystem(e){if(process.platform!==`win32`||rootedWindowsDriveColonIndex(e)!==5)return e;if(e.length===7)return`${e[4]}:\\`;let n=t.resolve(e);return isBareWindowsNamespaceDrive(n)&&!hasWindowsPathAlias(e,`filesystem`)?`${n[4]}:\\`:e}function hasWindowsPathAlias(e,t,n=process.platform){if(n!==`win32`)return!1;let r=e.indexOf(`:`);return r===-1?!1:t===`relative`||r!==rootedWindowsDriveColonIndex(e)||e.indexOf(`:`,r+1)!==-1}function assertNoWindowsPathAliasForPlatform(e,t,n,r){if(hasWindowsPathAlias(e,t,r))throw new FsSafeError(`invalid-path`,n,{details:{reason:`windows-path-alias`}})}function assertNoWindowsPathAlias(e,t=`filesystem`,n=`path uses a Windows filesystem namespace alias`,r=process.platform){assertNoWindowsPathAliasForPlatform(e,t,n,r)}function admitStandalonePublicationPath(e,t){let n=anchorWindowsDriveRelativePath(e);return assertNoWindowsPathAlias(n,`filesystem`,t),n}const o=/%(?:2f|5c)/i,s=/^file:\/\//i;function isFileUrl(e){return s.test(e)}function hasEncodedFileUrlSeparator(e){return o.test(e)}function isWindowsNetworkPath(e,t=process.platform){return t===`win32`&&isWindowsSeparator(e,0)&&isWindowsSeparator(e,1)&&(windowsNamespaceMarker(e)!==`?`||rootedWindowsDriveColonIndex(e)!==5)}function safeFileURLToPath(e,t=process.platform){let i;try{i=new n(e)}catch{throw Error(`Invalid file:// URL: ${e}`)}if(i.protocol!==`file:`)throw Error(`Invalid file:// URL: ${e}`);let a=normalizeLowercaseStringOrEmpty(i.hostname);if(a!==``&&a!==`localhost`)throw Error(`file:// URLs with remote hosts are not allowed: ${e}`);if(hasEncodedFileUrlSeparator(i.pathname))throw Error(`file:// URLs cannot encode path separators: ${e}`);let o=r(i,{windows:t===`win32`});if(hasWindowsPathAlias(o,`filesystem`,t))throw Error(`Local file URL cannot use Windows filesystem namespace aliases: ${o}`);if(isWindowsNetworkPath(o,t))throw Error(`Local file URL cannot use Windows network paths: ${o}`);return o}function trySafeFileURLToPath(e,t=process.platform){try{return safeFileURLToPath(e,t)}catch{return}}const c=/* @__PURE__ */ new Set([`/dev/zero`,`/dev/random`,`/dev/urandom`,`/dev/full`,`/dev/stdin`,`/dev/stdout`,`/dev/stderr`,`/dev/tty`,`/dev/console`]),l=/* @__PURE__ */ new Set(/* @__PURE__ */ `CON.PRN.AUX.NUL.CLOCK$.CONIN$.CONOUT$.COM1.COM2.COM3.COM4.COM5.COM6.COM7.COM8.COM9.COM¹.COM².COM³.LPT1.LPT2.LPT3.LPT4.LPT5.LPT6.LPT7.LPT8.LPT9.LPT¹.LPT².LPT³`.split(`.`));function trimTrailingWindowsSeparators(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===92;)--t;return t===e.length?e:e.slice(0,t)}function trimTrailingWindowsIgnoredChars(e){let t=e.length;for(;t>0;){let n=e.charCodeAt(t-1);if(n!==32&&n!==46)break;--t}return t===e.length?e:e.slice(0,t)}function candidateReadPaths(e,t){if(!isFileUrl(e))return[e];let n=trySafeFileURLToPath(e,t);return n===void 0?[e]:[e,n]}function normalizePosixPath(e,n){if(t.posix.isAbsolute(e))return t.posix.normalize(e);let r=n&&t.posix.isAbsolute(n)?n:process.cwd();return t.posix.resolve(r,e)}function matchPosixDeviceReadPath(e,t){let n=normalizePosixPath(e,t);if(c.has(n))return{path:n,reason:`posix-device`};if(n===`/dev/fd`||n.startsWith(`/dev/fd/`)||/^\/proc\/(?:self|thread-self|\d+)\/fd(?:\/|$)/.test(n))return{path:n,reason:`posix-fd`}}function normalizeWindowsDeviceBaseName(e){let t=trimTrailingWindowsSeparators(e.replace(/\//g,`\\`)),n=t.lastIndexOf(`\\`)+1,r=t.indexOf(`:`,n),i=t.indexOf(`.`,n),a=Math.min(r<0?t.length:r,i<0?t.length:i);return trimTrailingWindowsIgnoredChars(t.slice(n,a)).toUpperCase()}function isWindowsReservedDeviceName(e){return e.length>0&&l.has(normalizeWindowsDeviceBaseName(e))}function matchWindowsDeviceReadPath(e){let t=e.replace(/\//g,`\\`);if(/^\\\\\.\\/.test(t)||/^\\\\\?\\GLOBALROOT\\Device\\/i.test(t))return{path:t,reason:`windows-device`};let n=normalizeWindowsDeviceBaseName(e);if(l.has(n))return{path:t,reason:`windows-device`}}function matchUnsafeDeviceReadPath(e,t={}){let n=t.platform??process.platform;for(let r of candidateReadPaths(e,n)){let e=n===`win32`?matchWindowsDeviceReadPath(r):matchPosixDeviceReadPath(r,t.cwd);if(e)return e}}function isUnsafeDeviceReadPath(e,t){return matchUnsafeDeviceReadPath(e,t)!==void 0}function assertNoUnsafeDeviceReadPath(e,t){if(matchUnsafeDeviceReadPath(e,t))throw new FsSafeError(`device-path`,`file reads from unsafe device paths are not allowed: ${e}`)}const u=/* @__PURE__ */ new Set([`ENOENT`,`ENOTDIR`]),d=/* @__PURE__ */ new Set([`ELOOP`,`EINVAL`,`ENOTSUP`]);function normalizeWindowsPathForComparison(e){let n=t.win32.normalize(e);return n.startsWith(`\\\\?\\`)&&(n=n.slice(4),n.toUpperCase().startsWith(`UNC\\`)&&(n=`\\\\${n.slice(4)}`)),n.replaceAll(`/`,`\\`).toLowerCase()}function resolveWindowsPathForComparison(e){let n=t.win32.resolve(e);return n[1]===`:`&&t.win32.isAbsolute(n)?n.toLowerCase():normalizeWindowsPathForComparison(n.length===6?resolvePathPreservingWindowsRoot(e):n)}function isNodeError(e){return!!(e&&typeof e==`object`&&`code`in e)}function hasNodeErrorCode(e,t){return isNodeError(e)&&e.code===t}function assertNoNulPathInput(e,t=`path contains a NUL byte`){if(e.includes(`\0`))throw new FsSafeError(`invalid-path`,t)}function isNotFoundPathError(e){return isNodeError(e)&&typeof e.code==`string`&&u.has(e.code)}function isSymlinkOpenError(e){return isNodeError(e)&&typeof e.code==`string`&&d.has(e.code)}function isPathInside(e,n){if(process.platform===`win32`){if(isForeignWindowsShareOrDevicePath(n,[e]))return!1;let r=resolveWindowsPathForComparison(e),i=resolveWindowsPathForComparison(n);if(r[1]===`:`&&t.win32.isAbsolute(r)&&!i.includes(`:`,2)&&(i===r||i.startsWith(r)&&(r.endsWith(`\\`)||i[r.length]===`\\`)))return!0;let a=t.win32.relative(r,i),o=a.split(t.win32.sep)[0];return a===``||o!==`..`&&!t.win32.isAbsolute(a)}if(e.length>0&&e.charCodeAt(0)===47&&n.length>=e.length&&n.charCodeAt(0)===47&&!n.includes(`/..`)&&(n===e||n.startsWith(e)&&(e.charCodeAt(e.length-1)===47||n.charCodeAt(e.length)===47)))return!0;let r=t.resolve(e),i=t.resolve(n),a=t.relative(r,i),o=a.split(t.posix.sep)[0];return a===``||o!==`..`&&!t.isAbsolute(a)}function isPathRelativeEscape(e){if(t.isAbsolute(e))return!0;let n=0,r=e.split(process.platform===`win32`?/[/\\]/:/\//);for(let e of r)if(e===`..`){if(n===0)return!0;--n}else e!==``&&e!==`.`&&(n+=1);return!1}function safeStatSync(t){try{return e.statSync(pathForWindowsFilesystem(t))}catch{return null}}const f=new i;function recordFileObservationFailure(e,t){let n=f.getStore();if(!n)return;let r=n.get(e);r||n.set(e,r=/* @__PURE__ */ new Set),r.add(t)}function isFileObservationFailure(e,t){return f.getStore()?.get(e)?.has(t)===!0}function fileObservation(){let e=/* @__PURE__ */ new Map;return{run(t){return f.run(e,t)},has(t,n){return e.get(t)?.has(n)===!0}}}function fileIdentityMismatchError(){let e=new FsSafeError(`path-mismatch`,`file identity changed or could not be verified`);return recordFileObservationFailure(e,`identity`),e}function identityCheck(e,t){let n={},check=e=>{let r=!0;for(let i of[`dev`,`ino`]){let a=e[i];if(typeof a!=`bigint`)throw fileIdentityMismatchError();if(t===`win32`&&a===0n)r=!1;else{if(n[i]!==void 0&&n[i]!==a)throw fileIdentityMismatchError();n[i]=a}}return r};if(e&&!check(e))throw fileIdentityMismatchError();return check}async function inspectFileIdentity(e,t,n=process.platform){let r=identityCheck(t,n);for(let t=0;t<2;t++){let t=await e();if(r(t))return t}throw fileIdentityMismatchError()}function inspectFileIdentitySync(e,t,n=process.platform,r=fileIdentityMismatchError){let i,a;if(t&&(i=t.dev,typeof i!=`bigint`||(a=t.ino,typeof a!=`bigint`)||n===`win32`&&(i===0n||a===0n)))throw r();for(let t=0;t<2;t++){let t=e(),o=!0,s=t.dev;if(typeof s!=`bigint`)throw r();if(n===`win32`&&s===0n)o=!1;else{if(i!==void 0&&i!==s)throw r();i=s}let c=t.ino;if(typeof c!=`bigint`)throw r();if(n===`win32`&&c===0n)o=!1;else{if(a!==void 0&&a!==c)throw r();a=c}if(o)return t}throw r()}function normalizeMaxBytes(e,t={}){let n=e===void 0?t.defaultValue:e;if(n===void 0||n===1/0)return n;if(!Number.isSafeInteger(n)||n<0)throw RangeError(`maxBytes must be a non-negative safe integer or Infinity`);return n}const p=65536;function createInitialBuffer(e,t,n=Buffer.allocUnsafe){return n(Math.min(e,t,16777216)+1)}function createScratchBuffer(e,t=Buffer.allocUnsafe){return t(Math.min(p,e+1))}function growReadBuffer(e,t,n=Buffer.allocUnsafe){let r=n(Math.min(t+1,Math.max(p,e.length*2)));return e.copy(r),r}function finishReadBuffer(e,t,n){if(t===0)return Buffer.alloc(0);let r=e.subarray(0,t);if(t>=e.length/2)return r;if(!n)return Buffer.from(r);let i=n(t);return r.copy(i),i}function addReadBytes(e,t,n,r){let i=e+t;if(i>n)throw r?r():new FsSafeError(`too-large`,`file exceeds limit of ${n} bytes (got at least ${i})`);return i}async function readBoundedAsync(e,t,n={}){normalizeMaxBytes(e);let r=0,{observeRegularFileSize:i,createLimitError:a}=n,o=n.unpooled?Buffer.allocUnsafeSlow:void 0,s=n.initialSize??i?.(),c=s===void 0?createScratchBuffer(e,o):createInitialBuffer(e,s,o);if(s!==void 0){let n=await t(c,c.length);if(n===0)return finishReadBuffer(c,0,o);let s=n<c.length?i?.():void 0;if(r=addReadBytes(r,n,e,a),s!==void 0&&s>0&&n>=s)return finishReadBuffer(c,r,o)}for(;;){r===c.length&&(c=growReadBuffer(c,e,o));let n=c.subarray(r),i=await t(n,n.length);if(i===0)return finishReadBuffer(c,r,o);r=addReadBytes(r,i,e,a)}}async function readFileHandleBounded(e,t){return await readFileHandleBoundedWithSize(e,t)}function readFileHandleBoundedWithSize(e,t,n){normalizeMaxBytes(t);let r=`fd`in e&&typeof e.fd==`number`?e.fd:void 0;return readBoundedAsync(t,async(t,n)=>(await e.read(t,0,n,null)).bytesRead,{initialSize:n,observeRegularFileSize:r===void 0?void 0:()=>regularFileSize(r)})}function regularFileSize(t){try{let n=e.fstatSync(t);return n.isFile()&&Number.isSafeInteger(n.size)&&n.size>=0?n.size:void 0}catch{return}}function readBoundedSync(e,t,n={}){normalizeMaxBytes(e);let r=0,{observeRegularFileSize:i,createLimitError:a}=n,o=n.initialSize??i?.(),s=o===void 0?createScratchBuffer(e):createInitialBuffer(e,o);if(o!==void 0){let n=t(s,s.length);if(n===0)return finishReadBuffer(s,0);let o=n<s.length?i?.():void 0;if(r=addReadBytes(r,n,e,a),o!==void 0&&o>0&&n>=o)return finishReadBuffer(s,r)}for(;;){r===s.length&&(s=growReadBuffer(s,e));let n=s.subarray(r),i=t(n,n.length);if(i===0)return finishReadBuffer(s,r);r=addReadBytes(r,i,e,a)}}function readFileDescriptorBoundedSync(t,n){return readBoundedSync(n,(n,r)=>e.readSync(t,n,0,r,null),{initialSize:n<=p?n:void 0,observeRegularFileSize:()=>regularFileSize(t)})}function exactFileIdentity(e){let{dev:t,ino:n}=e;if(typeof t!=`bigint`&&!Number.isSafeInteger(t)||typeof n!=`bigint`&&!Number.isSafeInteger(n))throw new FsSafeError(`path-mismatch`,`file identity is not exact`);return Object.freeze({dev:BigInt(t),ino:BigInt(n)})}function numberStatScalar(e){return Number(typeof e==`bigint`?BigInt.asUintN(64,e):e)}function numberStats(t){let n=Object.create(e.Stats.prototype);for(let e of[`dev`,`mode`,`nlink`,`uid`,`gid`,`rdev`,`blksize`,`ino`,`size`,`blocks`])n[e]=numberStatScalar(t[e]);for(let e of[`atime`,`mtime`,`ctime`,`birthtime`]){let r=t[`${e}Ns`],i=(r%1000000000n+1000000000n)%1000000000n;n[`${e}Ms`]=Number((r-i)/1000000000n)*1e3+Number(i)/1e6}return n}function resolveReadOpenFlags(t){let n=t?.constants??e.constants,r=process.platform!==`win32`&&t?.followSymlinks!==!0&&typeof n.O_NOFOLLOW==`number`?n.O_NOFOLLOW:0,i=process.platform!==`win32`&&typeof n.O_NONBLOCK==`number`?n.O_NONBLOCK:0;return n.O_RDONLY|r|i}export{admitStandalonePublicationPath as A,isSymlinkOpenError as C,assertNoUnsafeDeviceReadPath as D,l as E,pathForWindowsFilesystem as F,resolvePathFromBasePreservingWindowsRoot as I,resolvePathPreservingWindowsRoot as L,assertNoWindowsPathAlias as M,hasWindowsPathAlias as N,isUnsafeDeviceReadPath as O,isForeignWindowsShareOrDevicePath as P,FsSafeError as R,isPathRelativeEscape as S,safeStatSync as T,assertNoNulPathInput as _,readBoundedAsync as a,isNotFoundPathError as b,readFileHandleBounded as c,fileIdentityMismatchError as d,inspectFileIdentity as f,recordFileObservationFailure as g,isFileObservationFailure as h,numberStats as i,anchorWindowsDriveRelativePath as j,isWindowsReservedDeviceName as k,readFileHandleBoundedWithSize as l,fileObservation as m,exactFileIdentity as n,readBoundedSync as o,inspectFileIdentitySync as p,numberStatScalar as r,readFileDescriptorBoundedSync as s,resolveReadOpenFlags as t,normalizeMaxBytes as u,hasNodeErrorCode as v,normalizeWindowsPathForComparison as w,isPathInside as x,isNodeError as y};