Comparing version 1.2.3 to 1.2.4
@@ -25,2 +25,2 @@ /* | ||
// @bun | ||
import Elysia from"elysia";var assembleStyles=function(){const codes=new Map;for(let[groupName,group]of Object.entries(styles)){for(let[styleName,style]of Object.entries(group))styles[styleName]={open:`\x1B[${style[0]}m`,close:`\x1B[${style[1]}m`},group[styleName]=styles[styleName],codes.set(style[0],style[1]);Object.defineProperty(styles,groupName,{value:group,enumerable:!1})}return Object.defineProperty(styles,"codes",{value:codes,enumerable:!1}),styles.color.close="\x1B[39m",styles.bgColor.close="\x1B[49m",styles.color.ansi=wrapAnsi16(),styles.color.ansi256=wrapAnsi256(),styles.color.ansi16m=wrapAnsi16m(),styles.bgColor.ansi=wrapAnsi16(10),styles.bgColor.ansi256=wrapAnsi256(10),styles.bgColor.ansi16m=wrapAnsi16m(10),Object.defineProperties(styles,{rgbToAnsi256:{value(red,green,blue){if(red===green&&green===blue){if(red<8)return 16;if(red>248)return 231;return Math.round((red-8)/247*24)+232}return 16+36*Math.round(red/255*5)+6*Math.round(green/255*5)+Math.round(blue/255*5)},enumerable:!1},hexToRgb:{value(hex){const matches=/[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));if(!matches)return[0,0,0];let[colorString]=matches;if(colorString.length===3)colorString=[...colorString].map((character)=>character+character).join("");const integer=Number.parseInt(colorString,16);return[integer>>16&255,integer>>8&255,integer&255]},enumerable:!1},hexToAnsi256:{value:(hex)=>styles.rgbToAnsi256(...styles.hexToRgb(hex)),enumerable:!1},ansi256ToAnsi:{value(code){if(code<8)return 30+code;if(code<16)return 90+(code-8);let red,green,blue;if(code>=232)red=((code-232)*10+8)/255,green=red,blue=red;else{code-=16;const remainder=code%36;red=Math.floor(code/36)/5,green=Math.floor(remainder/6)/5,blue=remainder%6/5}const value=Math.max(red,green,blue)*2;if(value===0)return 30;let result=30+(Math.round(blue)<<2|Math.round(green)<<1|Math.round(red));if(value===2)result+=60;return result},enumerable:!1},rgbToAnsi:{value:(red,green,blue)=>styles.ansi256ToAnsi(styles.rgbToAnsi256(red,green,blue)),enumerable:!1},hexToAnsi:{value:(hex)=>styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),enumerable:!1}}),styles};var wrapAnsi16=(offset=0)=>(code)=>`\x1B[${code+offset}m`,wrapAnsi256=(offset=0)=>(code)=>`\x1B[${38+offset};5;${code}m`,wrapAnsi16m=(offset=0)=>(red,green,blue)=>`\x1B[${38+offset};2;${red};${green};${blue}m`,styles={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},modifierNames=Object.keys(styles.modifier),foregroundColorNames=Object.keys(styles.color),backgroundColorNames=Object.keys(styles.bgColor),colorNames=[...foregroundColorNames,...backgroundColorNames],ansiStyles=assembleStyles(),ansi_styles_default=ansiStyles;import process2 from"process";import os from"os";import tty from"tty";var hasFlag=function(flag,argv=globalThis.Deno?globalThis.Deno.args:process2.argv){const prefix=flag.startsWith("-")?"":flag.length===1?"-":"--",position=argv.indexOf(prefix+flag),terminatorPosition=argv.indexOf("--");return position!==-1&&(terminatorPosition===-1||position<terminatorPosition)},envForceColor=function(){if("FORCE_COLOR"in env){if(env.FORCE_COLOR==="true")return 1;if(env.FORCE_COLOR==="false")return 0;return env.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(env.FORCE_COLOR,10),3)}},translateLevel=function(level){if(level===0)return!1;return{level,hasBasic:!0,has256:level>=2,has16m:level>=3}},_supportsColor=function(haveStream,{streamIsTTY,sniffFlags=!0}={}){const noFlagForceColor=envForceColor();if(noFlagForceColor!==void 0)flagForceColor=noFlagForceColor;const forceColor=sniffFlags?flagForceColor:noFlagForceColor;if(forceColor===0)return 0;if(sniffFlags){if(hasFlag("color=16m")||hasFlag("color=full")||hasFlag("color=truecolor"))return 3;if(hasFlag("color=256"))return 2}if("TF_BUILD"in env&&"AGENT_NAME"in env)return 1;if(haveStream&&!streamIsTTY&&forceColor===void 0)return 0;const min=forceColor||0;if(env.TERM==="dumb")return min;if(process2.platform==="win32"){const osRelease=os.release().split(".");if(Number(osRelease[0])>=10&&Number(osRelease[2])>=10586)return Number(osRelease[2])>=14931?3:2;return 1}if("CI"in env){if("GITHUB_ACTIONS"in env||"GITEA_ACTIONS"in env)return 3;if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((sign)=>(sign in env))||env.CI_NAME==="codeship")return 1;return min}if("TEAMCITY_VERSION"in env)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION)?1:0;if(env.COLORTERM==="truecolor")return 3;if(env.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in env){const version=Number.parseInt((env.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(env.TERM_PROGRAM){case"iTerm.app":return version>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(env.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM))return 1;if("COLORTERM"in env)return 1;return min};function createSupportsColor(stream,options={}){const level=_supportsColor(stream,{streamIsTTY:stream&&stream.isTTY,...options});return translateLevel(level)}var{env}=process2,flagForceColor;if(hasFlag("no-color")||hasFlag("no-colors")||hasFlag("color=false")||hasFlag("color=never"))flagForceColor=0;else if(hasFlag("color")||hasFlag("colors")||hasFlag("color=true")||hasFlag("color=always"))flagForceColor=1;var supportsColor={stdout:createSupportsColor({isTTY:tty.isatty(1)}),stderr:createSupportsColor({isTTY:tty.isatty(2)})},supports_color_default=supportsColor;function stringReplaceAll(string,substring,replacer){let index=string.indexOf(substring);if(index===-1)return string;const substringLength=substring.length;let endIndex=0,returnValue="";do returnValue+=string.slice(endIndex,index)+substring+replacer,endIndex=index+substringLength,index=string.indexOf(substring,endIndex);while(index!==-1);return returnValue+=string.slice(endIndex),returnValue}function stringEncaseCRLFWithFirstIndex(string,prefix,postfix,index){let endIndex=0,returnValue="";do{const gotCR=string[index-1]==="\r";returnValue+=string.slice(endIndex,gotCR?index-1:index)+prefix+(gotCR?"\r\n":"\n")+postfix,endIndex=index+1,index=string.indexOf("\n",endIndex)}while(index!==-1);return returnValue+=string.slice(endIndex),returnValue}var createChalk=function(options){return chalkFactory(options)};var{stdout:stdoutColor,stderr:stderrColor}=supports_color_default,GENERATOR=Symbol("GENERATOR"),STYLER=Symbol("STYLER"),IS_EMPTY=Symbol("IS_EMPTY"),levelMapping=["ansi","ansi","ansi256","ansi16m"],styles2=Object.create(null),applyOptions=(object,options={})=>{if(options.level&&!(Number.isInteger(options.level)&&options.level>=0&&options.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const colorLevel=stdoutColor?stdoutColor.level:0;object.level=options.level===void 0?colorLevel:options.level};var chalkFactory=(options)=>{const chalk=(...strings)=>strings.join(" ");return applyOptions(chalk,options),Object.setPrototypeOf(chalk,createChalk.prototype),chalk};Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[styleName,style]of Object.entries(ansi_styles_default))styles2[styleName]={get(){const builder=createBuilder(this,createStyler(style.open,style.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(this,styleName,{value:builder}),builder}};styles2.visible={get(){const builder=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this,"visible",{value:builder}),builder}};var getModelAnsi=(model,level,type,...arguments_)=>{if(model==="rgb"){if(level==="ansi16m")return ansi_styles_default[type].ansi16m(...arguments_);if(level==="ansi256")return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_))}if(model==="hex")return getModelAnsi("rgb",level,type,...ansi_styles_default.hexToRgb(...arguments_));return ansi_styles_default[type][model](...arguments_)},usedModels=["rgb","hex","ansi256"];for(let model of usedModels){styles2[model]={get(){const{level}=this;return function(...arguments_){const styler=createStyler(getModelAnsi(model,levelMapping[level],"color",...arguments_),ansi_styles_default.color.close,this[STYLER]);return createBuilder(this,styler,this[IS_EMPTY])}}};const bgModel="bg"+model[0].toUpperCase()+model.slice(1);styles2[bgModel]={get(){const{level}=this;return function(...arguments_){const styler=createStyler(getModelAnsi(model,levelMapping[level],"bgColor",...arguments_),ansi_styles_default.bgColor.close,this[STYLER]);return createBuilder(this,styler,this[IS_EMPTY])}}}}var proto=Object.defineProperties(()=>{},{...styles2,level:{enumerable:!0,get(){return this[GENERATOR].level},set(level){this[GENERATOR].level=level}}}),createStyler=(open,close,parent)=>{let openAll,closeAll;if(parent===void 0)openAll=open,closeAll=close;else openAll=parent.openAll+open,closeAll=close+parent.closeAll;return{open,close,openAll,closeAll,parent}},createBuilder=(self,_styler,_isEmpty)=>{const builder=(...arguments_)=>applyStyle(builder,arguments_.length===1?""+arguments_[0]:arguments_.join(" "));return Object.setPrototypeOf(builder,proto),builder[GENERATOR]=self,builder[STYLER]=_styler,builder[IS_EMPTY]=_isEmpty,builder},applyStyle=(self,string)=>{if(self.level<=0||!string)return self[IS_EMPTY]?"":string;let styler=self[STYLER];if(styler===void 0)return string;const{openAll,closeAll}=styler;if(string.includes("\x1B"))while(styler!==void 0)string=stringReplaceAll(string,styler.close,styler.open),styler=styler.parent;const lfIndex=string.indexOf("\n");if(lfIndex!==-1)string=stringEncaseCRLFWithFirstIndex(string,closeAll,openAll,lfIndex);return openAll+string+closeAll};Object.defineProperties(createChalk.prototype,styles2);var chalk=createChalk(),chalkStderr=createChalk({level:stderrColor?stderrColor.level:0});var source_default=chalk;import{StatusMap} from"elysia";function removeAnsi(text){return text.replace(/\u001b\[\d*m/g,"").trimStart()}var buildAttrs=(ctx,reqAttrs,timeStart)=>{const{request,path,body,query,set}=ctx;let attrs={};for(let key of reqAttrs)switch(key){case"ip":attrs.ip=request.headers.get("x-forwarded-for")||"<ip?>";break;case"method":attrs.method=request.method;break;case"path":attrs.path=path;break;case"body":attrs.body=body;break;case"query":attrs.query=query;break;case"time":attrs.time=new Date;break;case"contentLength":attrs.contentLength=Number(request.headers.get("content-length"));break;case"status":if(!set.status)break;attrs.status=typeof set.status==="number"?set.status:StatusMap[set.status];break;case"referer":attrs.referer=request.headers.get("referer")||"<referer?>";break;case"userAgent":attrs.userAgent=request.headers.get("user-agent")||"<user-agent?>";break;case"duration":const now=process.hrtime.bigint();attrs.duration=(now-timeStart)/1000n;break}return attrs},colourLogType=(type,colourDef)=>{let bgColour=source_default.bgBlack;switch(type){case"http":bgColour=colourDef[type]&&source_default.hex(colourDef[type])||source_default.bgBlue;break;case"info":bgColour=colourDef[type]&&source_default.hex(colourDef[type])||source_default.bgGreen;break;case"warn":bgColour=colourDef[type]&&source_default.hex(colourDef[type])||source_default.bgYellow;break;case"debug":bgColour=colourDef[type]&&source_default.hex(colourDef[type])||source_default.bgCyan;break;case"error":bgColour=colourDef[type]&&source_default.hex(colourDef[type])||source_default.bgRed;break}const withSpaces=` ${type.toUpperCase()} `;return bgColour?.(withSpaces)??withSpaces};var common_default=(options)=>new Logestic(options).use(["time","method","path","status"]).format({onSuccess({time,method,path,status}){const grayTime=source_default.gray(`${time.toISOString()}`),methodPath=source_default.cyan(`${method} ${path}`);let statusColor=source_default.white;if(200<=status&&status<300)statusColor=source_default.green;if(400<=status&&status<500)statusColor=source_default.yellow;if(500<=status)statusColor=source_default.red;return`[${grayTime}] ${methodPath} ${statusColor(status)}`},onFailure({request,error,code,datetime}){const grayTime=source_default.gray(`${datetime.toISOString()}`),msg=source_default.red(`${request.method} ${request.url} ${error.message} ${code}`);return`[${grayTime}] ${msg}`}});var getDateTimeString=(date)=>{const year=date.getFullYear(),month=date.getMonth()+1,day=date.getDate(),hours=date.getHours(),minutes=date.getMinutes(),seconds=date.getSeconds();return`${day}/${month}/${year} ${hours}:${minutes}:${seconds}`},defaultOptions={showLevel:!0},fancy_default=(options)=>new Logestic({...defaultOptions,...options}).use(["time","method","path","duration"]).format({onSuccess({time,method,path,duration}){const dateTime=source_default.gray(getDateTimeString(time)),methodPath=source_default.cyan(`${method} ${path}`);return`${dateTime} ${methodPath} ${duration}\u03BCs`},onFailure({request,datetime}){const dateTime=getDateTimeString(datetime);return source_default.red(`${dateTime} ${request.method} ${request.url}`)}});var commontz_default=(options)=>new Logestic(options).use(["time","method","path","status"]).format({onSuccess({time,method,path,status}){const grayTime=source_default.gray(`${time.toString()}`),methodPath=source_default.cyan(`${method} ${path}`);let statusColor=source_default.white;if(200<=status&&status<300)statusColor=source_default.green;if(400<=status&&status<500)statusColor=source_default.yellow;if(500<=status)statusColor=source_default.red;return`[${grayTime}] ${methodPath} ${statusColor(status)}`},onFailure({request,error,code,datetime}){const grayTime=source_default.gray(`${datetime.toString()}`),msg=source_default.red(`${request.method} ${request.url} ${error.message} ${code}`);return`[${grayTime}] ${msg}`}});var getPreset=(preset)=>{switch(preset){case"common":return common_default;case"fancy":return fancy_default;case"commontz":return commontz_default}};import fs from"fs";var chalk2=source_default;class Logestic{requestedAttrs;dest;showLevel;logLevelColour;httpLogging;explicitLogging;constructor(options={}){this.requestedAttrs=[],this.showLevel=options.showLevel||!1,this.logLevelColour=options.logLevelColour||{},this.httpLogging=options.httpLogging||!0,this.explicitLogging=options.explicitLogging||!0,this.setDest(options.dest||Bun.stdout)}setDest(dest){if(dest===Bun.stdin)throw new Error("Cannot log to stdin. Please provide a writable destination.");if(dest===Bun.stdout||dest===Bun.stderr){this.dest=dest;return}this.createFileIfNotExists(dest).then((file)=>this.dest=file).catch((err)=>{throw err})}async createFileIfNotExists(dest){if(!await dest.exists())Bun.write(dest,"");return dest}use(attrs){if(Array.isArray(attrs)){for(let attr of attrs)this._use(attr);return this}return this._use(attrs),this}_use(attr){this.requestedAttrs.push(attr)}static preset(name,options={}){return getPreset(name)(options)}build(){return new Elysia({name:"logestic"}).decorate("logestic",this)}format(formatAttr){return this.build().state("logestic_timeStart",0n).onRequest(({store,request})=>{if(store.logestic_timeStart=process.hrtime.bigint(),formatAttr.onRequest){let msg=formatAttr.onRequest(request);if(this.showLevel)msg=`${colourLogType("http",this.logLevelColour)} ${msg}`;this.log(msg)}}).onAfterResponse({as:"global"},(ctx)=>{if(!this.httpLogging)return;const{store:{logestic_timeStart}}=ctx;let attrs=buildAttrs(ctx,this.requestedAttrs,logestic_timeStart),msg=formatAttr.onSuccess(attrs);if(this.showLevel)msg=`${colourLogType("http",this.logLevelColour)} ${msg}`;this.log(msg)}).onError({as:"global"},({request,error,code})=>{let datetime=new Date,msg=formatAttr.onFailure({request,error,code,datetime});if(this.showLevel)msg=`${colourLogType("error",this.logLevelColour)} ${msg}`;this.log(msg)})}async log(msg){const msgNewLine=`${msg}\n`;if(!this.dest.name||!this.dest.name.length){Bun.write(this.dest,msgNewLine);return}const sanitised=removeAnsi(msgNewLine);fs.appendFile(this.dest.name,sanitised,(err)=>{if(err)throw err})}info(msg){if(!this.explicitLogging)return;let _msg=msg;if(this.showLevel)_msg=`${colourLogType("info",this.logLevelColour)} ${msg}`;this.log(_msg)}warn(msg){if(!this.explicitLogging)return;let _msg=msg;if(this.showLevel)_msg=`${colourLogType("warn",this.logLevelColour)} ${msg}`;this.log(_msg)}debug(msg){if(!this.explicitLogging)return;let _msg=msg;if(this.showLevel)_msg=`${colourLogType("debug",this.logLevelColour)} ${msg}`;this.log(_msg)}error(msg){if(!this.explicitLogging)return;let _msg=msg;if(this.showLevel)_msg=`${colourLogType("error",this.logLevelColour)} ${msg}`;this.log(_msg)}}export{chalk2 as chalk,Logestic}; | ||
import Elysia from"elysia";var assembleStyles=function(){const codes=new Map;for(let[groupName,group]of Object.entries(styles)){for(let[styleName,style]of Object.entries(group))styles[styleName]={open:`\x1B[${style[0]}m`,close:`\x1B[${style[1]}m`},group[styleName]=styles[styleName],codes.set(style[0],style[1]);Object.defineProperty(styles,groupName,{value:group,enumerable:!1})}return Object.defineProperty(styles,"codes",{value:codes,enumerable:!1}),styles.color.close="\x1B[39m",styles.bgColor.close="\x1B[49m",styles.color.ansi=wrapAnsi16(),styles.color.ansi256=wrapAnsi256(),styles.color.ansi16m=wrapAnsi16m(),styles.bgColor.ansi=wrapAnsi16(10),styles.bgColor.ansi256=wrapAnsi256(10),styles.bgColor.ansi16m=wrapAnsi16m(10),Object.defineProperties(styles,{rgbToAnsi256:{value(red,green,blue){if(red===green&&green===blue){if(red<8)return 16;if(red>248)return 231;return Math.round((red-8)/247*24)+232}return 16+36*Math.round(red/255*5)+6*Math.round(green/255*5)+Math.round(blue/255*5)},enumerable:!1},hexToRgb:{value(hex){const matches=/[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));if(!matches)return[0,0,0];let[colorString]=matches;if(colorString.length===3)colorString=[...colorString].map((character)=>character+character).join("");const integer=Number.parseInt(colorString,16);return[integer>>16&255,integer>>8&255,integer&255]},enumerable:!1},hexToAnsi256:{value:(hex)=>styles.rgbToAnsi256(...styles.hexToRgb(hex)),enumerable:!1},ansi256ToAnsi:{value(code){if(code<8)return 30+code;if(code<16)return 90+(code-8);let red,green,blue;if(code>=232)red=((code-232)*10+8)/255,green=red,blue=red;else{code-=16;const remainder=code%36;red=Math.floor(code/36)/5,green=Math.floor(remainder/6)/5,blue=remainder%6/5}const value=Math.max(red,green,blue)*2;if(value===0)return 30;let result=30+(Math.round(blue)<<2|Math.round(green)<<1|Math.round(red));if(value===2)result+=60;return result},enumerable:!1},rgbToAnsi:{value:(red,green,blue)=>styles.ansi256ToAnsi(styles.rgbToAnsi256(red,green,blue)),enumerable:!1},hexToAnsi:{value:(hex)=>styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),enumerable:!1}}),styles};var wrapAnsi16=(offset=0)=>(code)=>`\x1B[${code+offset}m`,wrapAnsi256=(offset=0)=>(code)=>`\x1B[${38+offset};5;${code}m`,wrapAnsi16m=(offset=0)=>(red,green,blue)=>`\x1B[${38+offset};2;${red};${green};${blue}m`,styles={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},modifierNames=Object.keys(styles.modifier),foregroundColorNames=Object.keys(styles.color),backgroundColorNames=Object.keys(styles.bgColor),colorNames=[...foregroundColorNames,...backgroundColorNames],ansiStyles=assembleStyles(),ansi_styles_default=ansiStyles;import process2 from"process";import os from"os";import tty from"tty";var hasFlag=function(flag,argv=globalThis.Deno?globalThis.Deno.args:process2.argv){const prefix=flag.startsWith("-")?"":flag.length===1?"-":"--",position=argv.indexOf(prefix+flag),terminatorPosition=argv.indexOf("--");return position!==-1&&(terminatorPosition===-1||position<terminatorPosition)},envForceColor=function(){if("FORCE_COLOR"in env){if(env.FORCE_COLOR==="true")return 1;if(env.FORCE_COLOR==="false")return 0;return env.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(env.FORCE_COLOR,10),3)}},translateLevel=function(level){if(level===0)return!1;return{level,hasBasic:!0,has256:level>=2,has16m:level>=3}},_supportsColor=function(haveStream,{streamIsTTY,sniffFlags=!0}={}){const noFlagForceColor=envForceColor();if(noFlagForceColor!==void 0)flagForceColor=noFlagForceColor;const forceColor=sniffFlags?flagForceColor:noFlagForceColor;if(forceColor===0)return 0;if(sniffFlags){if(hasFlag("color=16m")||hasFlag("color=full")||hasFlag("color=truecolor"))return 3;if(hasFlag("color=256"))return 2}if("TF_BUILD"in env&&"AGENT_NAME"in env)return 1;if(haveStream&&!streamIsTTY&&forceColor===void 0)return 0;const min=forceColor||0;if(env.TERM==="dumb")return min;if(process2.platform==="win32"){const osRelease=os.release().split(".");if(Number(osRelease[0])>=10&&Number(osRelease[2])>=10586)return Number(osRelease[2])>=14931?3:2;return 1}if("CI"in env){if("GITHUB_ACTIONS"in env||"GITEA_ACTIONS"in env)return 3;if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((sign)=>(sign in env))||env.CI_NAME==="codeship")return 1;return min}if("TEAMCITY_VERSION"in env)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION)?1:0;if(env.COLORTERM==="truecolor")return 3;if(env.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in env){const version=Number.parseInt((env.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(env.TERM_PROGRAM){case"iTerm.app":return version>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(env.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM))return 1;if("COLORTERM"in env)return 1;return min};function createSupportsColor(stream,options={}){const level=_supportsColor(stream,{streamIsTTY:stream&&stream.isTTY,...options});return translateLevel(level)}var{env}=process2,flagForceColor;if(hasFlag("no-color")||hasFlag("no-colors")||hasFlag("color=false")||hasFlag("color=never"))flagForceColor=0;else if(hasFlag("color")||hasFlag("colors")||hasFlag("color=true")||hasFlag("color=always"))flagForceColor=1;var supportsColor={stdout:createSupportsColor({isTTY:tty.isatty(1)}),stderr:createSupportsColor({isTTY:tty.isatty(2)})},supports_color_default=supportsColor;function stringReplaceAll(string,substring,replacer){let index=string.indexOf(substring);if(index===-1)return string;const substringLength=substring.length;let endIndex=0,returnValue="";do returnValue+=string.slice(endIndex,index)+substring+replacer,endIndex=index+substringLength,index=string.indexOf(substring,endIndex);while(index!==-1);return returnValue+=string.slice(endIndex),returnValue}function stringEncaseCRLFWithFirstIndex(string,prefix,postfix,index){let endIndex=0,returnValue="";do{const gotCR=string[index-1]==="\r";returnValue+=string.slice(endIndex,gotCR?index-1:index)+prefix+(gotCR?"\r\n":"\n")+postfix,endIndex=index+1,index=string.indexOf("\n",endIndex)}while(index!==-1);return returnValue+=string.slice(endIndex),returnValue}var createChalk=function(options){return chalkFactory(options)};var{stdout:stdoutColor,stderr:stderrColor}=supports_color_default,GENERATOR=Symbol("GENERATOR"),STYLER=Symbol("STYLER"),IS_EMPTY=Symbol("IS_EMPTY"),levelMapping=["ansi","ansi","ansi256","ansi16m"],styles2=Object.create(null),applyOptions=(object,options={})=>{if(options.level&&!(Number.isInteger(options.level)&&options.level>=0&&options.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const colorLevel=stdoutColor?stdoutColor.level:0;object.level=options.level===void 0?colorLevel:options.level};var chalkFactory=(options)=>{const chalk=(...strings)=>strings.join(" ");return applyOptions(chalk,options),Object.setPrototypeOf(chalk,createChalk.prototype),chalk};Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[styleName,style]of Object.entries(ansi_styles_default))styles2[styleName]={get(){const builder=createBuilder(this,createStyler(style.open,style.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(this,styleName,{value:builder}),builder}};styles2.visible={get(){const builder=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this,"visible",{value:builder}),builder}};var getModelAnsi=(model,level,type,...arguments_)=>{if(model==="rgb"){if(level==="ansi16m")return ansi_styles_default[type].ansi16m(...arguments_);if(level==="ansi256")return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_))}if(model==="hex")return getModelAnsi("rgb",level,type,...ansi_styles_default.hexToRgb(...arguments_));return ansi_styles_default[type][model](...arguments_)},usedModels=["rgb","hex","ansi256"];for(let model of usedModels){styles2[model]={get(){const{level}=this;return function(...arguments_){const styler=createStyler(getModelAnsi(model,levelMapping[level],"color",...arguments_),ansi_styles_default.color.close,this[STYLER]);return createBuilder(this,styler,this[IS_EMPTY])}}};const bgModel="bg"+model[0].toUpperCase()+model.slice(1);styles2[bgModel]={get(){const{level}=this;return function(...arguments_){const styler=createStyler(getModelAnsi(model,levelMapping[level],"bgColor",...arguments_),ansi_styles_default.bgColor.close,this[STYLER]);return createBuilder(this,styler,this[IS_EMPTY])}}}}var proto=Object.defineProperties(()=>{},{...styles2,level:{enumerable:!0,get(){return this[GENERATOR].level},set(level){this[GENERATOR].level=level}}}),createStyler=(open,close,parent)=>{let openAll,closeAll;if(parent===void 0)openAll=open,closeAll=close;else openAll=parent.openAll+open,closeAll=close+parent.closeAll;return{open,close,openAll,closeAll,parent}},createBuilder=(self,_styler,_isEmpty)=>{const builder=(...arguments_)=>applyStyle(builder,arguments_.length===1?""+arguments_[0]:arguments_.join(" "));return Object.setPrototypeOf(builder,proto),builder[GENERATOR]=self,builder[STYLER]=_styler,builder[IS_EMPTY]=_isEmpty,builder},applyStyle=(self,string)=>{if(self.level<=0||!string)return self[IS_EMPTY]?"":string;let styler=self[STYLER];if(styler===void 0)return string;const{openAll,closeAll}=styler;if(string.includes("\x1B"))while(styler!==void 0)string=stringReplaceAll(string,styler.close,styler.open),styler=styler.parent;const lfIndex=string.indexOf("\n");if(lfIndex!==-1)string=stringEncaseCRLFWithFirstIndex(string,closeAll,openAll,lfIndex);return openAll+string+closeAll};Object.defineProperties(createChalk.prototype,styles2);var chalk=createChalk(),chalkStderr=createChalk({level:stderrColor?stderrColor.level:0});var source_default=chalk;import{StatusMap} from"elysia";function removeAnsi(text){return text.replace(/\u001b\[\d*m/g,"").trimStart()}var buildAttrs=(ctx,reqAttrs,timeStart)=>{const{request,path,body,query,set}=ctx;let attrs={};for(let key of reqAttrs)switch(key){case"ip":attrs.ip=request.headers.get("x-forwarded-for")||"<ip?>";break;case"method":attrs.method=request.method;break;case"path":attrs.path=path;break;case"body":attrs.body=body;break;case"query":attrs.query=query;break;case"time":attrs.time=new Date;break;case"contentLength":attrs.contentLength=Number(request.headers.get("content-length"));break;case"status":if(!set.status)break;attrs.status=typeof set.status==="number"?set.status:StatusMap[set.status];break;case"referer":attrs.referer=request.headers.get("referer")||"<referer?>";break;case"userAgent":attrs.userAgent=request.headers.get("user-agent")||"<user-agent?>";break;case"duration":const now=process.hrtime.bigint();attrs.duration=(now-timeStart)/1000n;break}return attrs},colourLogType=(type,colourDef)=>{let bgColour=source_default.bgBlack;switch(type){case"http":bgColour=colourDef[type]&&source_default.hex(colourDef[type])||source_default.bgBlue;break;case"info":bgColour=colourDef[type]&&source_default.hex(colourDef[type])||source_default.bgGreen;break;case"warn":bgColour=colourDef[type]&&source_default.hex(colourDef[type])||source_default.bgYellow;break;case"debug":bgColour=colourDef[type]&&source_default.hex(colourDef[type])||source_default.bgCyan;break;case"error":bgColour=colourDef[type]&&source_default.hex(colourDef[type])||source_default.bgRed;break}const withSpaces=` ${type.toUpperCase()} `;return bgColour?.(withSpaces)??withSpaces};var common_default=(options)=>new Logestic(options).use(["time","method","path","status"]).format({onSuccess({time,method,path,status}){const grayTime=source_default.gray(`${time.toISOString()}`),methodPath=source_default.cyan(`${method} ${path}`);let statusColor=source_default.white;if(200<=status&&status<300)statusColor=source_default.green;if(400<=status&&status<500)statusColor=source_default.yellow;if(500<=status)statusColor=source_default.red;return`[${grayTime}] ${methodPath} ${statusColor(status)}`},onFailure({request,error,code,datetime}){const grayTime=source_default.gray(`${datetime.toISOString()}`),msg=source_default.red(`${request.method} ${request.url} ${error.message} ${code}`);return`[${grayTime}] ${msg}`}});var getDateTimeString=(date)=>{const year=date.getFullYear(),month=date.getMonth()+1,day=date.getDate(),hours=date.getHours(),minutes=date.getMinutes(),seconds=date.getSeconds();return`${day}/${month}/${year} ${hours}:${minutes}:${seconds}`},defaultOptions={showLevel:!0},fancy_default=(options)=>new Logestic({...defaultOptions,...options}).use(["time","method","path","duration"]).format({onSuccess({time,method,path,duration}){const dateTime=source_default.gray(getDateTimeString(time)),methodPath=source_default.cyan(`${method} ${path}`);return`${dateTime} ${methodPath} ${duration}\u03BCs`},onFailure({request,datetime}){const dateTime=getDateTimeString(datetime);return source_default.red(`${dateTime} ${request.method} ${request.url}`)}});var commontz_default=(options)=>new Logestic(options).use(["time","method","path","status"]).format({onSuccess({time,method,path,status}){const grayTime=source_default.gray(`${time.toString()}`),methodPath=source_default.cyan(`${method} ${path}`);let statusColor=source_default.white;if(200<=status&&status<300)statusColor=source_default.green;if(400<=status&&status<500)statusColor=source_default.yellow;if(500<=status)statusColor=source_default.red;return`[${grayTime}] ${methodPath} ${statusColor(status)}`},onFailure({request,error,code,datetime}){const grayTime=source_default.gray(`${datetime.toString()}`),msg=source_default.red(`${request.method} ${request.url} ${error.message} ${code}`);return`[${grayTime}] ${msg}`}});var getPreset=(preset)=>{switch(preset){case"common":return common_default;case"fancy":return fancy_default;case"commontz":return commontz_default}};import fs from"fs";var chalk2=source_default;class Logestic{requestedAttrs;dest;showLevel;logLevelColour;httpLogging;explicitLogging;constructor(options={}){this.requestedAttrs=[],this.showLevel=options.showLevel||!1,this.logLevelColour=options.logLevelColour||{},this.httpLogging=options.httpLogging||!0,this.explicitLogging=options.explicitLogging||!0,this.setDest(options.dest||Bun.stdout)}setDest(dest){if(dest===Bun.stdin)throw new Error("Cannot log to stdin. Please provide a writable destination.");if(dest===Bun.stdout||dest===Bun.stderr){this.dest=dest;return}this.createFileIfNotExists(dest).then((file)=>this.dest=file).catch((err)=>{throw err})}async createFileIfNotExists(dest){if(!await dest.exists())Bun.write(dest,"");return dest}use(attrs){if(Array.isArray(attrs)){for(let attr of attrs)this._use(attr);return this}return this._use(attrs),this}_use(attr){this.requestedAttrs.push(attr)}static preset(name,options={}){return getPreset(name)(options)}build(){return new Elysia({name:"logestic"}).decorate("logestic",this)}format(formatAttr){return this.build().state("logestic_timeStart",0n).onRequest(({store,request})=>{if(store.logestic_timeStart=process.hrtime.bigint(),formatAttr.onRequest){let msg=formatAttr.onRequest(request);if(this.showLevel)msg=`${colourLogType("http",this.logLevelColour)} ${msg}`;this.log(msg)}}).onAfterResponse({as:"global"},(ctx)=>{if(!this.httpLogging)return;const{store:{logestic_timeStart}}=ctx;let attrs=buildAttrs(ctx,this.requestedAttrs,logestic_timeStart),msg=formatAttr.onSuccess(attrs);if(this.showLevel)msg=`${colourLogType("http",this.logLevelColour)} ${msg}`;this.log(msg)}).onError({as:"global"},({request,error,code})=>{let datetime=new Date,msg=formatAttr.onFailure({request,error,code,datetime});if(this.showLevel)msg=`${colourLogType("error",this.logLevelColour)} ${msg}`;this.log(msg)})}async log(msg){if(!msg||msg==="")return;const msgNewLine=`${msg}\n`;if(!this.dest.name||!this.dest.name.length){Bun.write(this.dest,msgNewLine);return}const sanitised=removeAnsi(msgNewLine);fs.appendFile(this.dest.name,sanitised,(err)=>{if(err)throw err})}info(msg){if(!this.explicitLogging)return;let _msg=msg;if(this.showLevel)_msg=`${colourLogType("info",this.logLevelColour)} ${msg}`;this.log(_msg)}warn(msg){if(!this.explicitLogging)return;let _msg=msg;if(this.showLevel)_msg=`${colourLogType("warn",this.logLevelColour)} ${msg}`;this.log(_msg)}debug(msg){if(!this.explicitLogging)return;let _msg=msg;if(this.showLevel)_msg=`${colourLogType("debug",this.logLevelColour)} ${msg}`;this.log(_msg)}error(msg){if(!this.explicitLogging)return;let _msg=msg;if(this.showLevel)_msg=`${colourLogType("error",this.logLevelColour)} ${msg}`;this.log(_msg)}}export{chalk2 as chalk,Logestic}; |
{ | ||
"name": "logestic", | ||
"version": "1.2.3", | ||
"version": "1.2.4", | ||
"author": "Nishant Aanjaney Jalan <cybercoder.nishant@gmail.com>", | ||
@@ -49,2 +49,2 @@ "description": "An advanced and customisable logging library for ElysiaJS", | ||
} | ||
} | ||
} |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
31422
0