@bemoje/fs 0.0.11 → 0.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @bemoje/fs v0.0.
|
|
2
|
+
* @bemoje/fs v0.0.12
|
|
3
3
|
* (c) Benjamin Møller Jensen
|
|
4
4
|
* Released under the MIT License.
|
|
5
5
|
*/"use strict";var string=require("@bemoje/string"),path=require("path"),getAppDataPath=require("appdata-path"),EventEmitter=require("events"),fs=require("fs"),readline=require("readline"),child_process=require("child_process"),readLastLines=require("read-last-lines"),extract=require("extract-zip");function absoluteToRelativePath(absolute,workingDirectory=process.cwd()){return path.normalize(absolute).replace(new RegExp(string.regexEscapeString(path.normalize(workingDirectory)+path.sep),"i"),"")}function __awaiter(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function __values(o){var s="function"==typeof Symbol&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&"number"==typeof o.length)return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")}function __await(v){return this instanceof __await?(this.v=v,this):new __await(v)}function __asyncGenerator(thisArg,_arguments,generator){function verb(n){g[n]&&(i[n]=function(v){return new Promise(function(a,b){1<q.push([n,v,a,b])||resume(n,v)})})}function resume(n,v){try{step(g[n](v))}catch(e){settle(q[0][3],e)}}function step(r){r.value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f,v){(f(v),q.shift(),q.length)&&resume(q[0][0],q[0][1])}if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,g=generator.apply(thisArg,_arguments||[]),q=[];return i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i}function __asyncValues(o){function verb(n){i[n]=o[n]&&function(v){return new Promise(function(resolve,reject){v=o[n](v),settle(resolve,reject,v.done,v.value)})}}function settle(resolve,reject,d,v){Promise.resolve(v).then(function(v){resolve({value:v,done:d})},reject)}if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,m=o[Symbol.asyncIterator];return m?m.call(o):(o="function"==typeof __values?__values(o):o[Symbol.iterator](),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i)}function __classPrivateFieldGet(receiver,state,kind,f){if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===kind?f:"a"===kind?f.call(receiver):f?f.value:state.get(receiver)}function __classPrivateFieldSet(receiver,state,value,kind,f){if("m"===kind)throw new TypeError("Private method is not writable");if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===kind?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value}"function"==typeof SuppressedError?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e};function readJsonFileSync(filepath){return JSON.parse(fs.readFileSync(filepath,"utf8"))}function writeJsonFileSync(filepath,data,pretty=!1){fs.writeFileSync(filepath,JSON.stringify(data,null,pretty?2:void 0))}var _JsonFile_data;class JsonFile extends EventEmitter{get data(){return JSON.parse(JSON.stringify(__classPrivateFieldGet(this,_JsonFile_data,"f")))}constructor(filepath,prettyPrint=!1){super(),_JsonFile_data.set(this,void 0),this.filepath=filepath,__classPrivateFieldSet(this,_JsonFile_data,{},"f"),this.prettyPrint=prettyPrint,this.ensureDirectoryExists(),fs.existsSync(this.filepath)?this.loadFile():writeJsonFileSync(this.filepath,__classPrivateFieldGet(this,_JsonFile_data,"f"),this.prettyPrint)}get(key){return JSON.parse(JSON.stringify(__classPrivateFieldGet(this,_JsonFile_data,"f")[key]))}set(key,value){if(__classPrivateFieldGet(this,_JsonFile_data,"f")[key]!==value){const json=JSON.stringify(value);json===JSON.stringify(__classPrivateFieldGet(this,_JsonFile_data,"f")[key])||(value=JSON.parse(json),__classPrivateFieldGet(this,_JsonFile_data,"f")[key]=value,this.saveFile(),this.emit("set",Date.now(),key,value))}}has(key){return __classPrivateFieldGet(this,_JsonFile_data,"f")[key]!==void 0}delete(key){delete __classPrivateFieldGet(this,_JsonFile_data,"f")[key],this.saveFile(),this.emit("set",Date.now(),key,void 0)}getOrElse(key,getValue){if(this.has(key))return JSON.parse(JSON.stringify(this.get(key)));const value=JSON.parse(JSON.stringify(getValue()));return this.set(key,value),value}clear(){const time=Date.now();for(const key of Object.keys(__classPrivateFieldGet(this,_JsonFile_data,"f")))this.emit("set",time,key,void 0);__classPrivateFieldSet(this,_JsonFile_data,{},"f"),fs.writeFileSync(this.filepath,"{}","utf8")}assign(data){data=JSON.parse(JSON.stringify(data));const time=Date.now();for(const[key,value]of Object.entries(data))__classPrivateFieldGet(this,_JsonFile_data,"f")[key]&&JSON.stringify(__classPrivateFieldGet(this,_JsonFile_data,"f")[key])!==JSON.stringify(value)&&this.emit("set",time,key,value);Object.assign(__classPrivateFieldGet(this,_JsonFile_data,"f"),data),this.saveFile()}ensureDirectoryExists(){fs.mkdirSync(path.dirname(this.filepath),{recursive:!0})}saveFile(){writeJsonFileSync(this.filepath,__classPrivateFieldGet(this,_JsonFile_data,"f"),this.prettyPrint)}loadFile(){__classPrivateFieldSet(this,_JsonFile_data,readJsonFileSync(this.filepath),"f")}}_JsonFile_data=new WeakMap;class LogFile{constructor(filepath){this.filepath=filepath,this.ensureDirectoryExists()}append(data,time=Date.now()){return __awaiter(this,void 0,void 0,function*(){yield fs.promises.appendFile(this.filepath,time+"|"+JSON.stringify(data)+"\n","utf8")})}reset(){fs.rmSync(this.filepath)}readFile(){const data=fs.readFileSync(this.filepath,"utf8"),lines=data.split("\n"),result=[];for(const line of lines){const i=line.indexOf("|");if(-1===i)continue;const time=parseInt(line.substring(0,i)),data=JSON.parse(line.substring(i+1));result.push([time,data])}return result.sort((a,b)=>b[0]-a[0])}keys(){return __asyncGenerator(this,arguments,function*keys_1(){var _a,e_1,_b,_c;const fileStream=fs.createReadStream(this.filepath,"utf8"),rl=readline.createInterface({input:fileStream,crlfDelay:1/0});try{for(var rl_1_1,_d=!0,rl_1=__asyncValues(rl);rl_1_1=yield __await(rl_1.next()),_a=rl_1_1.done,!_a;_d=!0){_c=rl_1_1.value,_d=!1;const line=_c,i=line.indexOf("|"),time=parseInt(line.substring(0,i));yield yield __await(time)}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_d||_a||!(_b=rl_1.return)||(yield __await(_b.call(rl_1)))}finally{if(e_1)throw e_1.error}}})}values(){return __asyncGenerator(this,arguments,function*values_1(){var _a,e_2,_b,_c;const fileStream=fs.createReadStream(this.filepath,"utf8"),rl=readline.createInterface({input:fileStream,crlfDelay:1/0});try{for(var rl_2_1,_d=!0,rl_2=__asyncValues(rl);rl_2_1=yield __await(rl_2.next()),_a=rl_2_1.done,!_a;_d=!0){_c=rl_2_1.value,_d=!1;const line=_c,i=line.indexOf("|"),data=JSON.parse(line.substring(i+1));yield yield __await(data)}}catch(e_2_1){e_2={error:e_2_1}}finally{try{_d||_a||!(_b=rl_2.return)||(yield __await(_b.call(rl_2)))}finally{if(e_2)throw e_2.error}}})}entries(){return __asyncGenerator(this,arguments,function*entries_1(){var _a,e_3,_b,_c;const fileStream=fs.createReadStream(this.filepath,"utf8"),rl=readline.createInterface({input:fileStream,crlfDelay:1/0});try{for(var rl_3_1,_d=!0,rl_3=__asyncValues(rl);rl_3_1=yield __await(rl_3.next()),_a=rl_3_1.done,!_a;_d=!0){_c=rl_3_1.value,_d=!1;const line=_c,i=line.indexOf("|"),time=parseInt(line.substring(0,i)),data=JSON.parse(line.substring(i+1));yield yield __await([time,data])}}catch(e_3_1){e_3={error:e_3_1}}finally{try{_d||_a||!(_b=rl_3.return)||(yield __await(_b.call(rl_3)))}finally{if(e_3)throw e_3.error}}})}ensureDirectoryExists(){fs.mkdirSync(path.dirname(this.filepath),{recursive:!0})}}class AppData{constructor(appAuthor,appName,configName){this.directory=path.join(getAppDataPath(),appAuthor,appName,configName),this.app=new JsonFile(path.join(this.directory,"appdata.json"),!1),this.user=new JsonFile(path.join(this.directory,"config.json"),!0),this.history=new LogFile(path.join(this.directory,"history.log")),this.app.on("set",(time,k,v)=>__awaiter(this,void 0,void 0,function*(){yield this.history.append({source:"app",key:k,value:v},time)})),this.user.on("set",(time,k,v)=>__awaiter(this,void 0,void 0,function*(){yield this.history.append({source:"user",key:k,value:v},time)}))}}function createDirectory(dirpath){return __awaiter(this,void 0,void 0,function*(){return yield fs.promises.mkdir(dirpath,{recursive:!0}),dirpath})}function appendLineToFile(filepath,line,linebreakBefore=!1){return __awaiter(this,void 0,void 0,function*(){fs.existsSync(filepath)||(yield createDirectory(path.dirname(filepath)),yield fs.promises.writeFile(filepath,"")),yield fs.promises.appendFile(filepath,linebreakBefore?"\n"+line:line+"\n")})}function cleanDirectorySync(dirpath,predicate){for(const filename of fs.readdirSync(dirpath)){const filepath=path.join(dirpath,filename),stat=fs.statSync(filepath);predicate(filepath,stat)&&fs.unlinkSync(filepath)}}function createDirectorySync(dirpath){return fs.mkdirSync(dirpath,{recursive:!0}),dirpath}function normalizeFileExtension(ext){if(""===ext||"."===ext)return"";if(/[<>"|?*:]/g.test(ext))throw new Error(`Illegal characters in file extension: ${ext} | Illegal characters are: <>"|?:*`);return ext.includes(".")?ext.substring(ext.lastIndexOf(".")):"."+ext}function createFileExtensionFilter(...fileExtensions){return fileExtensions.length?filepath=>{for(const ext of fileExtensions.map(normalizeFileExtension))if(path.extname(filepath)===ext)return!0;return!1}:()=>!0}function cwdpath(...paths){return path.join(process.cwd(),...paths)}function deleteDirectory(dirpath){return __awaiter(this,void 0,void 0,function*(){yield fs.promises.rm(dirpath,{recursive:!0,force:!0})})}function deleteDirectorySafe(dirpath){return __awaiter(this,void 0,void 0,function*(){fs.existsSync(dirpath)&&(yield fs.promises.rm(dirpath,{recursive:!0,force:!0}))})}function deleteDirectorySafeSync(dirpath){return fs.existsSync(dirpath)?(fs.rmSync(dirpath,{recursive:!0,force:!0}),dirpath):dirpath}function deleteDirectorySync(dirpath){return fs.rmSync(dirpath,{recursive:!0,force:!0}),dirpath}function ensureValidWindowsPath(path,options){const throwOrFalse=msg=>{if(options&&!0===options.assert)throw new Error(`Invalid windows path. ${msg} | input received: ${path}`);return!1};if(0===path.length)return throwOrFalse("Path string is length 0.");if(-1!==path.indexOf("/")&&-1!==path.indexOf("\\"))return throwOrFalse("Path contains both backslash and forward slash.");const maxLength=(options&&options.extendedMaxLength?32767:260)-12;if(path.length>maxLength)return throwOrFalse(`Maximum length of ${maxLength} exceeded`);let noDriveLetter=path;return /^\w:(\\|\/)/g.test(path)&&(noDriveLetter=path.substring(2)),/[<>"|?*:]/g.test(noDriveLetter)?throwOrFalse(`Illegal characters in: ${path} | Illegal characters are: <>"|?:*`):!/(\\|\/)(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])((\\|\/)|$)/g.test(path)||throwOrFalse("Illegal name in path string")}function isWindows(){return process.platform.includes("win")}function getDiskDrivesWindows(){if(!isWindows())throw new Error("This function is only available on Windows.");return child_process.execSync("wmic logicaldisk get name").toString().split("\n").map(s=>s.trim()).filter(s=>/^[a-z]:/i.test(s)).map(s=>s.substring(0,2)+path.sep)}function getHomeDirectory(){const home=path.resolve(process.env.HOME||process.env.USERPROFILE||"");if(!home)throw new Error("Home directory not found");return home}function getDownloadsDirectory(){return path.join(getHomeDirectory(),"Downloads")}function getLastMofifiedFileIn(dirpath){return __awaiter(this,void 0,void 0,function*(){const children=yield fs.promises.readdir(dirpath),filtered=children.map(fname=>{const fpath=path.join(dirpath,fname),stat=fs.statSync(fpath);return[fpath,stat.mtimeMs,stat.isFile()]}).filter(a=>a[2]),sorted=filtered.sort((a,b)=>b[1]-a[1]);return sorted[0][0]})}function getRootDir(){return path.parse(process.cwd()).root}function readFileLastLines(filepath,n,encoding="utf8"){return __awaiter(this,void 0,void 0,function*(){return yield readLastLines.read(filepath,n,encoding)})}function readJsonFile(filepath){return __awaiter(this,void 0,void 0,function*(){return JSON.parse(yield fs.promises.readFile(filepath,"utf8"))})}function readPackageJson(projectRoot=process.cwd()){const filepath=path.join(projectRoot,"package.json");return fs.existsSync(filepath)?readJsonFileSync(filepath):void 0}function removeIllegalFilenameCharacters(string){return string.replace(/[/\\?%*:|"<>]/g,"")}function tempFile(fileExtension,callback){const dir=path.join(process.env.TEMP,"bemoje","temp"),fpath=path.join(dir,Date.now()+fileExtension);fs.mkdirSync(dir,{recursive:!0});const prom=callback(fpath);if(prom instanceof Promise){const rm=()=>fs.rmSync(fpath);prom.then(rm).catch(rm)}else fs.rmSync(fpath)}function unzipFile(filepath,outdir){return __awaiter(this,void 0,void 0,function*(){yield extract(filepath,{dir:outdir})})}function unzipMergeFiles(source,target){return __awaiter(this,void 0,void 0,function*(){"string"==typeof source&&(source=fs.readdirSync(source).map(filename=>path.join(source,filename)));for(const filepath of source){const stat=yield fs.promises.stat(filepath);stat.isDirectory()||filepath.endsWith(".zip")&&(yield extract(filepath,{dir:target}))}})}function wipeDirectorySafe(dirpath){return __awaiter(this,void 0,void 0,function*(){yield deleteDirectorySafe(dirpath),yield createDirectory(dirpath)})}function writeJsonFile(filepath,data,pretty=!1){return __awaiter(this,void 0,void 0,function*(){yield fs.promises.writeFile(filepath,JSON.stringify(data,null,pretty?2:void 0))})}exports.AppData=AppData,exports.JsonFile=JsonFile,exports.LogFile=LogFile,exports.absoluteToRelativePath=absoluteToRelativePath,exports.appendLineToFile=appendLineToFile,exports.cleanDirectorySync=cleanDirectorySync,exports.createDirectory=createDirectory,exports.createDirectorySync=createDirectorySync,exports.createFileExtensionFilter=createFileExtensionFilter,exports.cwdpath=cwdpath,exports.deleteDirectory=deleteDirectory,exports.deleteDirectorySafe=deleteDirectorySafe,exports.deleteDirectorySafeSync=deleteDirectorySafeSync,exports.deleteDirectorySync=deleteDirectorySync,exports.ensureValidWindowsPath=ensureValidWindowsPath,exports.getDiskDrivesWindows=getDiskDrivesWindows,exports.getDownloadsDirectory=getDownloadsDirectory,exports.getHomeDirectory=getHomeDirectory,exports.getLastMofifiedFileIn=getLastMofifiedFileIn,exports.getRootDir=getRootDir,exports.isWindows=isWindows,exports.normalizeFileExtension=normalizeFileExtension,exports.readFileLastLines=readFileLastLines,exports.readJsonFile=readJsonFile,exports.readJsonFileSync=readJsonFileSync,exports.readPackageJson=readPackageJson,exports.removeIllegalFilenameCharacters=removeIllegalFilenameCharacters,exports.tempFile=tempFile,exports.unzipFile=unzipFile,exports.unzipMergeFiles=unzipMergeFiles,exports.wipeDirectorySafe=wipeDirectorySafe,exports.writeJsonFile=writeJsonFile,exports.writeJsonFileSync=writeJsonFileSync;
|
package/dist/index.esm.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @bemoje/fs v0.0.
|
|
2
|
+
* @bemoje/fs v0.0.12
|
|
3
3
|
* (c) Benjamin Møller Jensen
|
|
4
4
|
* Released under the MIT License.
|
|
5
5
|
*/import{regexEscapeString}from"@bemoje/string";import path from"path";import getAppDataPath from"appdata-path";import EventEmitter from"events";import fs from"fs";import readline from"readline";import{execSync}from"child_process";import readLastLines from"read-last-lines";import extract from"extract-zip";function absoluteToRelativePath(absolute,workingDirectory=process.cwd()){return path.normalize(absolute).replace(new RegExp(regexEscapeString(path.normalize(workingDirectory)+path.sep),"i"),"")}function __awaiter(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function __values(o){var s="function"==typeof Symbol&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&"number"==typeof o.length)return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")}function __await(v){return this instanceof __await?(this.v=v,this):new __await(v)}function __asyncGenerator(thisArg,_arguments,generator){function verb(n){g[n]&&(i[n]=function(v){return new Promise(function(a,b){1<q.push([n,v,a,b])||resume(n,v)})})}function resume(n,v){try{step(g[n](v))}catch(e){settle(q[0][3],e)}}function step(r){r.value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f,v){(f(v),q.shift(),q.length)&&resume(q[0][0],q[0][1])}if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,g=generator.apply(thisArg,_arguments||[]),q=[];return i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i}function __asyncValues(o){function verb(n){i[n]=o[n]&&function(v){return new Promise(function(resolve,reject){v=o[n](v),settle(resolve,reject,v.done,v.value)})}}function settle(resolve,reject,d,v){Promise.resolve(v).then(function(v){resolve({value:v,done:d})},reject)}if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,m=o[Symbol.asyncIterator];return m?m.call(o):(o="function"==typeof __values?__values(o):o[Symbol.iterator](),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i)}function __classPrivateFieldGet(receiver,state,kind,f){if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===kind?f:"a"===kind?f.call(receiver):f?f.value:state.get(receiver)}function __classPrivateFieldSet(receiver,state,value,kind,f){if("m"===kind)throw new TypeError("Private method is not writable");if("a"===kind&&!f)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof state?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===kind?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value}"function"==typeof SuppressedError?SuppressedError:function(error,suppressed,message){var e=new Error(message);return e.name="SuppressedError",e.error=error,e.suppressed=suppressed,e};function readJsonFileSync(filepath){return JSON.parse(fs.readFileSync(filepath,"utf8"))}function writeJsonFileSync(filepath,data,pretty=!1){fs.writeFileSync(filepath,JSON.stringify(data,null,pretty?2:void 0))}var _JsonFile_data;class JsonFile extends EventEmitter{get data(){return JSON.parse(JSON.stringify(__classPrivateFieldGet(this,_JsonFile_data,"f")))}constructor(filepath,prettyPrint=!1){super(),_JsonFile_data.set(this,void 0),this.filepath=filepath,__classPrivateFieldSet(this,_JsonFile_data,{},"f"),this.prettyPrint=prettyPrint,this.ensureDirectoryExists(),fs.existsSync(this.filepath)?this.loadFile():writeJsonFileSync(this.filepath,__classPrivateFieldGet(this,_JsonFile_data,"f"),this.prettyPrint)}get(key){return JSON.parse(JSON.stringify(__classPrivateFieldGet(this,_JsonFile_data,"f")[key]))}set(key,value){if(__classPrivateFieldGet(this,_JsonFile_data,"f")[key]!==value){const json=JSON.stringify(value);json===JSON.stringify(__classPrivateFieldGet(this,_JsonFile_data,"f")[key])||(value=JSON.parse(json),__classPrivateFieldGet(this,_JsonFile_data,"f")[key]=value,this.saveFile(),this.emit("set",Date.now(),key,value))}}has(key){return __classPrivateFieldGet(this,_JsonFile_data,"f")[key]!==void 0}delete(key){delete __classPrivateFieldGet(this,_JsonFile_data,"f")[key],this.saveFile(),this.emit("set",Date.now(),key,void 0)}getOrElse(key,getValue){if(this.has(key))return JSON.parse(JSON.stringify(this.get(key)));const value=JSON.parse(JSON.stringify(getValue()));return this.set(key,value),value}clear(){const time=Date.now();for(const key of Object.keys(__classPrivateFieldGet(this,_JsonFile_data,"f")))this.emit("set",time,key,void 0);__classPrivateFieldSet(this,_JsonFile_data,{},"f"),fs.writeFileSync(this.filepath,"{}","utf8")}assign(data){data=JSON.parse(JSON.stringify(data));const time=Date.now();for(const[key,value]of Object.entries(data))__classPrivateFieldGet(this,_JsonFile_data,"f")[key]&&JSON.stringify(__classPrivateFieldGet(this,_JsonFile_data,"f")[key])!==JSON.stringify(value)&&this.emit("set",time,key,value);Object.assign(__classPrivateFieldGet(this,_JsonFile_data,"f"),data),this.saveFile()}ensureDirectoryExists(){fs.mkdirSync(path.dirname(this.filepath),{recursive:!0})}saveFile(){writeJsonFileSync(this.filepath,__classPrivateFieldGet(this,_JsonFile_data,"f"),this.prettyPrint)}loadFile(){__classPrivateFieldSet(this,_JsonFile_data,readJsonFileSync(this.filepath),"f")}}_JsonFile_data=new WeakMap;class LogFile{constructor(filepath){this.filepath=filepath,this.ensureDirectoryExists()}append(data,time=Date.now()){return __awaiter(this,void 0,void 0,function*(){yield fs.promises.appendFile(this.filepath,time+"|"+JSON.stringify(data)+"\n","utf8")})}reset(){fs.rmSync(this.filepath)}readFile(){const data=fs.readFileSync(this.filepath,"utf8"),lines=data.split("\n"),result=[];for(const line of lines){const i=line.indexOf("|");if(-1===i)continue;const time=parseInt(line.substring(0,i)),data=JSON.parse(line.substring(i+1));result.push([time,data])}return result.sort((a,b)=>b[0]-a[0])}keys(){return __asyncGenerator(this,arguments,function*keys_1(){var _a,e_1,_b,_c;const fileStream=fs.createReadStream(this.filepath,"utf8"),rl=readline.createInterface({input:fileStream,crlfDelay:1/0});try{for(var rl_1_1,_d=!0,rl_1=__asyncValues(rl);rl_1_1=yield __await(rl_1.next()),_a=rl_1_1.done,!_a;_d=!0){_c=rl_1_1.value,_d=!1;const line=_c,i=line.indexOf("|"),time=parseInt(line.substring(0,i));yield yield __await(time)}}catch(e_1_1){e_1={error:e_1_1}}finally{try{_d||_a||!(_b=rl_1.return)||(yield __await(_b.call(rl_1)))}finally{if(e_1)throw e_1.error}}})}values(){return __asyncGenerator(this,arguments,function*values_1(){var _a,e_2,_b,_c;const fileStream=fs.createReadStream(this.filepath,"utf8"),rl=readline.createInterface({input:fileStream,crlfDelay:1/0});try{for(var rl_2_1,_d=!0,rl_2=__asyncValues(rl);rl_2_1=yield __await(rl_2.next()),_a=rl_2_1.done,!_a;_d=!0){_c=rl_2_1.value,_d=!1;const line=_c,i=line.indexOf("|"),data=JSON.parse(line.substring(i+1));yield yield __await(data)}}catch(e_2_1){e_2={error:e_2_1}}finally{try{_d||_a||!(_b=rl_2.return)||(yield __await(_b.call(rl_2)))}finally{if(e_2)throw e_2.error}}})}entries(){return __asyncGenerator(this,arguments,function*entries_1(){var _a,e_3,_b,_c;const fileStream=fs.createReadStream(this.filepath,"utf8"),rl=readline.createInterface({input:fileStream,crlfDelay:1/0});try{for(var rl_3_1,_d=!0,rl_3=__asyncValues(rl);rl_3_1=yield __await(rl_3.next()),_a=rl_3_1.done,!_a;_d=!0){_c=rl_3_1.value,_d=!1;const line=_c,i=line.indexOf("|"),time=parseInt(line.substring(0,i)),data=JSON.parse(line.substring(i+1));yield yield __await([time,data])}}catch(e_3_1){e_3={error:e_3_1}}finally{try{_d||_a||!(_b=rl_3.return)||(yield __await(_b.call(rl_3)))}finally{if(e_3)throw e_3.error}}})}ensureDirectoryExists(){fs.mkdirSync(path.dirname(this.filepath),{recursive:!0})}}class AppData{constructor(appAuthor,appName,configName){this.directory=path.join(getAppDataPath(),appAuthor,appName,configName),this.app=new JsonFile(path.join(this.directory,"appdata.json"),!1),this.user=new JsonFile(path.join(this.directory,"config.json"),!0),this.history=new LogFile(path.join(this.directory,"history.log")),this.app.on("set",(time,k,v)=>__awaiter(this,void 0,void 0,function*(){yield this.history.append({source:"app",key:k,value:v},time)})),this.user.on("set",(time,k,v)=>__awaiter(this,void 0,void 0,function*(){yield this.history.append({source:"user",key:k,value:v},time)}))}}function createDirectory(dirpath){return __awaiter(this,void 0,void 0,function*(){return yield fs.promises.mkdir(dirpath,{recursive:!0}),dirpath})}function appendLineToFile(filepath,line,linebreakBefore=!1){return __awaiter(this,void 0,void 0,function*(){fs.existsSync(filepath)||(yield createDirectory(path.dirname(filepath)),yield fs.promises.writeFile(filepath,"")),yield fs.promises.appendFile(filepath,linebreakBefore?"\n"+line:line+"\n")})}function cleanDirectorySync(dirpath,predicate){for(const filename of fs.readdirSync(dirpath)){const filepath=path.join(dirpath,filename),stat=fs.statSync(filepath);predicate(filepath,stat)&&fs.unlinkSync(filepath)}}function createDirectorySync(dirpath){return fs.mkdirSync(dirpath,{recursive:!0}),dirpath}function normalizeFileExtension(ext){if(""===ext||"."===ext)return"";if(/[<>"|?*:]/g.test(ext))throw new Error(`Illegal characters in file extension: ${ext} | Illegal characters are: <>"|?:*`);return ext.includes(".")?ext.substring(ext.lastIndexOf(".")):"."+ext}function createFileExtensionFilter(...fileExtensions){return fileExtensions.length?filepath=>{for(const ext of fileExtensions.map(normalizeFileExtension))if(path.extname(filepath)===ext)return!0;return!1}:()=>!0}function cwdpath(...paths){return path.join(process.cwd(),...paths)}function deleteDirectory(dirpath){return __awaiter(this,void 0,void 0,function*(){yield fs.promises.rm(dirpath,{recursive:!0,force:!0})})}function deleteDirectorySafe(dirpath){return __awaiter(this,void 0,void 0,function*(){fs.existsSync(dirpath)&&(yield fs.promises.rm(dirpath,{recursive:!0,force:!0}))})}function deleteDirectorySafeSync(dirpath){return fs.existsSync(dirpath)?(fs.rmSync(dirpath,{recursive:!0,force:!0}),dirpath):dirpath}function deleteDirectorySync(dirpath){return fs.rmSync(dirpath,{recursive:!0,force:!0}),dirpath}function ensureValidWindowsPath(path,options){const throwOrFalse=msg=>{if(options&&!0===options.assert)throw new Error(`Invalid windows path. ${msg} | input received: ${path}`);return!1};if(0===path.length)return throwOrFalse("Path string is length 0.");if(-1!==path.indexOf("/")&&-1!==path.indexOf("\\"))return throwOrFalse("Path contains both backslash and forward slash.");const maxLength=(options&&options.extendedMaxLength?32767:260)-12;if(path.length>maxLength)return throwOrFalse(`Maximum length of ${maxLength} exceeded`);let noDriveLetter=path;return /^\w:(\\|\/)/g.test(path)&&(noDriveLetter=path.substring(2)),/[<>"|?*:]/g.test(noDriveLetter)?throwOrFalse(`Illegal characters in: ${path} | Illegal characters are: <>"|?:*`):!/(\\|\/)(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])((\\|\/)|$)/g.test(path)||throwOrFalse("Illegal name in path string")}function isWindows(){return process.platform.includes("win")}function getDiskDrivesWindows(){if(!isWindows())throw new Error("This function is only available on Windows.");return execSync("wmic logicaldisk get name").toString().split("\n").map(s=>s.trim()).filter(s=>/^[a-z]:/i.test(s)).map(s=>s.substring(0,2)+path.sep)}function getHomeDirectory(){const home=path.resolve(process.env.HOME||process.env.USERPROFILE||"");if(!home)throw new Error("Home directory not found");return home}function getDownloadsDirectory(){return path.join(getHomeDirectory(),"Downloads")}function getLastMofifiedFileIn(dirpath){return __awaiter(this,void 0,void 0,function*(){const children=yield fs.promises.readdir(dirpath),filtered=children.map(fname=>{const fpath=path.join(dirpath,fname),stat=fs.statSync(fpath);return[fpath,stat.mtimeMs,stat.isFile()]}).filter(a=>a[2]),sorted=filtered.sort((a,b)=>b[1]-a[1]);return sorted[0][0]})}function getRootDir(){return path.parse(process.cwd()).root}function readFileLastLines(filepath,n,encoding="utf8"){return __awaiter(this,void 0,void 0,function*(){return yield readLastLines.read(filepath,n,encoding)})}function readJsonFile(filepath){return __awaiter(this,void 0,void 0,function*(){return JSON.parse(yield fs.promises.readFile(filepath,"utf8"))})}function readPackageJson(projectRoot=process.cwd()){const filepath=path.join(projectRoot,"package.json");return fs.existsSync(filepath)?readJsonFileSync(filepath):void 0}function removeIllegalFilenameCharacters(string){return string.replace(/[/\\?%*:|"<>]/g,"")}function tempFile(fileExtension,callback){const dir=path.join(process.env.TEMP,"bemoje","temp"),fpath=path.join(dir,Date.now()+fileExtension);fs.mkdirSync(dir,{recursive:!0});const prom=callback(fpath);if(prom instanceof Promise){const rm=()=>fs.rmSync(fpath);prom.then(rm).catch(rm)}else fs.rmSync(fpath)}function unzipFile(filepath,outdir){return __awaiter(this,void 0,void 0,function*(){yield extract(filepath,{dir:outdir})})}function unzipMergeFiles(source,target){return __awaiter(this,void 0,void 0,function*(){"string"==typeof source&&(source=fs.readdirSync(source).map(filename=>path.join(source,filename)));for(const filepath of source){const stat=yield fs.promises.stat(filepath);stat.isDirectory()||filepath.endsWith(".zip")&&(yield extract(filepath,{dir:target}))}})}function wipeDirectorySafe(dirpath){return __awaiter(this,void 0,void 0,function*(){yield deleteDirectorySafe(dirpath),yield createDirectory(dirpath)})}function writeJsonFile(filepath,data,pretty=!1){return __awaiter(this,void 0,void 0,function*(){yield fs.promises.writeFile(filepath,JSON.stringify(data,null,pretty?2:void 0))})}export{AppData,JsonFile,LogFile,absoluteToRelativePath,appendLineToFile,cleanDirectorySync,createDirectory,createDirectorySync,createFileExtensionFilter,cwdpath,deleteDirectory,deleteDirectorySafe,deleteDirectorySafeSync,deleteDirectorySync,ensureValidWindowsPath,getDiskDrivesWindows,getDownloadsDirectory,getHomeDirectory,getLastMofifiedFileIn,getRootDir,isWindows,normalizeFileExtension,readFileLastLines,readJsonFile,readJsonFileSync,readPackageJson,removeIllegalFilenameCharacters,tempFile,unzipFile,unzipMergeFiles,wipeDirectorySafe,writeJsonFile,writeJsonFileSync};
|