openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 2.19 kB
JavaScript
import fs from"node:fs";import path from"node:path";
//!src/infra/directory-walk.ts
var DirectoryWalkLimitError=class extends Error{constructor(e,t,n){super(`Directory scan of ${e} exceeded ${t}=${n}; narrow the scan or raise its explicit limit.`);this.name=`DirectoryWalkLimitError`;this.code=`ERR_DIRECTORY_WALK_LIMIT`;this.limit=t;this.maximum=n}};function createWalk(e,t,n){const r=t.maxDepth??64;const i=t.maxEntries??1e5;for(const[e,t]of Object.entries({maxDepth:r,maxEntries:i}))if(!Number.isSafeInteger(t)||t<0)throw new RangeError(e+` must be a nonnegative safe integer`);let a=0;const o=[{relativePath:``,depth:1}];return{pending:o,add(s,c){if(c.depth>r)throw new DirectoryWalkLimitError(e,`maxDepth`,r);if(a>=i)throw new DirectoryWalkLimitError(e,`maxEntries`,i);a+=1;const l=path.join(c.relativePath,s.name);const u={relativePath:l,dirent:s};n(u);if(s.isDirectory()&&!t.skipDirectory?.(u))o.push({relativePath:l,depth:c.depth+1})}}}function compareEntries(e,t){return e.relativePath<t.relativePath?-1:e.relativePath>t.relativePath?1:0}async function listDirectoryTreeStrict(e,t={}){const n=[];const r=createWalk(e,t,e=>n.push(e));if((await fs.promises.lstat(path.resolve(e))).isSymbolicLink())throw Object.assign(/* @__PURE__ */ new Error(`Directory scan root must not be a symlink: `+e),{code:`ERR_DIRECTORY_WALK_ROOT_SYMLINK`});for(let t=r.pending.pop();t;t=r.pending.pop()){const n=await fs.promises.opendir(path.join(e,t.relativePath));for await(const e of n)r.add(e,t)}return n.toSorted(compareEntries)}function visitDirectoryTreeStrictSync(e,t,n={}){const r=createWalk(e,n,t);if(fs.lstatSync(path.resolve(e)).isSymbolicLink())throw Object.assign(/* @__PURE__ */ new Error(`Directory scan root must not be a symlink: `+e),{code:`ERR_DIRECTORY_WALK_ROOT_SYMLINK`});for(let t=r.pending.pop();t;t=r.pending.pop()){const n=fs.opendirSync(path.join(e,t.relativePath));try{for(let e=n.readSync();e;e=n.readSync())r.add(e,t)}finally{n.closeSync()}}}function listDirectoryTreeStrictSync(e,t={}){const n=[];visitDirectoryTreeStrictSync(e,e=>n.push(e),t);return n.toSorted(compareEntries)}export{listDirectoryTreeStrict as n,listDirectoryTreeStrictSync as r,DirectoryWalkLimitError as t};