jet-logger 2.2.2 → 3.0.0

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/LICENSE CHANGED
File without changes
package/README.md CHANGED
@@ -1,12 +1,41 @@
1
- # Jet-Logger ✈️
1
+ # ✈️🪵 Jet-Logger
2
2
 
3
- > Super fast, zero-dependency logging for Node.js and TypeScript projects.
3
+ > A super quick, easy to setup TypeScript first logging tool for NodeJS and browsers.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/jet-logger?logo=npm&label=npm)](https://www.npmjs.com/package/jet-logger)
6
6
  [![npm downloads](https://img.shields.io/npm/dm/jet-logger?color=orange)](https://www.npmjs.com/package/jet-logger)
7
- [![License](https://img.shields.io/npm/l/jet-logger)](https://github.com/seanpmaxwell/jet-logger/blob/master/LICENSE)
7
+ [![License](https://img.shields.io/npm/l/jet-logger)](https://github.com/seanpmaxwell/jet-logger/blob/main/LICENSE)
8
8
  [![TypeScript definitions](https://img.shields.io/badge/TypeScript-ready-3178c6?logo=typescript&logoColor=white)](https://www.npmjs.com/package/jet-logger)
9
9
 
10
- Jet-Logger is an easy-to-configure logger that can print to the console, write to disk, or forward events to your own transport. Configure it entirely through environment variables or in code, and get colorized output, timestamps, and JSON log formatting out-of-the-box.
10
+ <p align="center">· · ·</p>
11
+
12
+ ## 👀 Preview
13
+
14
+ ![Four log calls are typed into app.ts, then running it prints four color-coded lines, each starting with the time: a green INFO, an underlined magenta IMPORTANT, a yellow WARNING, and a red ERROR](https://raw.githubusercontent.com/seanpmaxwell/jet-logger/HEAD/assets/demo.gif)
15
+
16
+ <p align="center">· · ·</p>
17
+
18
+ ## Features ✨
19
+
20
+ - Works locally and in browsers
21
+ - Zero dependencies, written in TypeScript
22
+ - Configure programmatically or through environment variables
23
+ - Tiny: **8 kB** packed
24
+ - Logs can be sent to the console or a file
25
+ - Both plain-text `line` and `json` (JSON Lines) formats supported
26
+ - Color-coded `info`, `imp`, `warn`, and `err` levels in terminals
27
+
28
+ <p align="center">· · ·</p>
29
+
30
+ ## 📦 Installation
31
+
32
+ ```bash
33
+ npm install jet-logger
34
+ ```
35
+
36
+ > Requires Node.js 20.16+ or 22.3+. Jet-Logger is an ES module; CommonJS projects can `require()` it on Node.js 20.19+ and 22.12+.
37
+
38
+
39
+ <p align="center">· · ·</p>
11
40
 
12
41
  Please refer to the official <a href="https://github.com/seanpmaxwell/jet-logger">github repo</a> for the most up-to-date documentation.
package/lib/index.d.ts ADDED
@@ -0,0 +1,106 @@
1
+ // Generated by dts-bundle-generator v9.5.1
2
+
3
+ type Enum<O extends BaseTypes> = {
4
+ [K in keyof O]: O[K] extends string | number ? O[K] : never;
5
+ }[keyof O];
6
+ type BaseTypes = Record<string, number> | Record<string, string>;
7
+ declare const EModes: {
8
+ readonly CONSOLE: "console";
9
+ readonly FILE: "file";
10
+ readonly BROWSER: "browser";
11
+ readonly CUSTOM: "custom";
12
+ readonly OFF: "off";
13
+ };
14
+ declare const Modes: {
15
+ readonly is: (val: unknown) => val is "console" | "file" | "browser" | "custom" | "off";
16
+ readonly enum: () => {
17
+ readonly CONSOLE: "console";
18
+ readonly FILE: "file";
19
+ readonly BROWSER: "browser";
20
+ readonly CUSTOM: "custom";
21
+ readonly OFF: "off";
22
+ };
23
+ readonly CONSOLE: "console";
24
+ readonly FILE: "file";
25
+ readonly BROWSER: "browser";
26
+ readonly CUSTOM: "custom";
27
+ readonly OFF: "off";
28
+ };
29
+ type EModes$1 = typeof EModes;
30
+ type Modes = Enum<EModes$1>;
31
+ declare const EFormats: {
32
+ readonly LINE: "line";
33
+ readonly JSON: "json";
34
+ };
35
+ declare const Formats: {
36
+ readonly is: (val: unknown) => val is "line" | "json";
37
+ readonly enum: () => {
38
+ readonly LINE: "line";
39
+ readonly JSON: "json";
40
+ };
41
+ readonly LINE: "line";
42
+ readonly JSON: "json";
43
+ };
44
+ type EFormats$1 = typeof EFormats;
45
+ type Formats = Enum<EFormats$1>;
46
+ type Labels = "INFO" | "WARNING" | "ERROR" | "IMPORTANT";
47
+ type IOptions = {
48
+ format: Formats;
49
+ showTime: boolean;
50
+ prependTimeToFilename: boolean;
51
+ filepath: string;
52
+ } & ({
53
+ mode: Exclude<Modes, "custom">;
54
+ customTransport: null;
55
+ } | {
56
+ mode: Modes;
57
+ customTransport: CustomTransportFn;
58
+ });
59
+ export interface CustomTransportContext {
60
+ time: string;
61
+ level: Labels | null;
62
+ msg: string;
63
+ }
64
+ export interface CustomTransportFn {
65
+ (context: CustomTransportContext): void | Promise<void>;
66
+ }
67
+ type APIOptions = Partial<IOptions>;
68
+ export type JetLoggerOptions = APIOptions;
69
+ export type JetLoggerInstance = Readonly<{
70
+ info(...args: unknown[]): void;
71
+ warn(...args: unknown[]): void;
72
+ err(...args: unknown[]): void;
73
+ imp(...args: unknown[]): void;
74
+ line(): void;
75
+ out(...args: unknown[]): void;
76
+ catch(cb: () => unknown): void;
77
+ flush(): Promise<void>;
78
+ close(): Promise<void>;
79
+ }>;
80
+ /**
81
+ * Throw this when the property on an object is invalid.
82
+ */
83
+ declare class InvalidOptionErr extends Error {
84
+ readonly property: string;
85
+ readonly value: unknown;
86
+ protected constructor(message: string, property: string, value: unknown);
87
+ /**
88
+ * Factory-Function. Setup the message and return a new instance.
89
+ */
90
+ static of(property: string, value: unknown, additionalMsg?: string): InvalidOptionErr;
91
+ }
92
+ interface JetLogger {
93
+ (options?: JetLoggerOptions): JetLoggerInstance;
94
+ readonly Modes: EModes$1;
95
+ readonly Formats: EFormats$1;
96
+ }
97
+ declare const DefaultLogger: JetLoggerInstance;
98
+ declare const JetLogger$1: JetLogger;
99
+
100
+ export {
101
+ DefaultLogger as default,
102
+ InvalidOptionErr as InvalidOptionError,
103
+ JetLogger$1 as JetLogger,
104
+ };
105
+
106
+ export {};
package/lib/index.js ADDED
@@ -0,0 +1,12 @@
1
+ function gt(t){return typeof t=="boolean"}function ht(t){return typeof t=="number"}function wt(t){return typeof t=="string"}function St(t){return typeof t=="string"&&t.length>0}function yt(t){return t!==void 0}function Et(t){return typeof t=="object"&&t!==null}function Tt(t){return typeof t=="function"}function Ot(t){return t===null||typeof t=="function"}function Lt(t){if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.toLowerCase();if(e==="true")return!0;if(e==="false")return!1}}var c={is:{def:yt,bool:gt,num:ht,str:wt,neStr:St,obj:Et,fn:Tt,nul:{fn:Ot}},parse:{bool:Lt}};function v(t){let e=Object.values(t);e=e.filter(n=>c.is.str(n)||c.is.num(n));let o=new Set(e);return{is:n=>o.has(n),enum:()=>({...t})}}var U={CONSOLE:"console",FILE:"file",BROWSER:"browser",CUSTOM:"custom",OFF:"off"},p={...U,...v(U)},Y={LINE:"line",JSON:"json"},f={...Y,...v(Y)};var K=/^\s+at /;function M(t){return t instanceof Error?t.message:String(t)}function z(t){if(!t.stack)return;let e=t.stack.split(`
2
+ `),o=e.findIndex(s=>K.test(s));return(o>=0?e.slice(o):e).map(s=>s.trim()).filter(s=>s!=="")}function L(t){let e=String(t),{stack:o}=t;return o?o.startsWith(e)||o.split(`
3
+ `).some(r=>K.test(r))?o:`${e}
4
+ ${o}`:e}function bt(t,e,o){let r=i=>{try{e(i)}catch{}},s;try{s=t()}catch(i){return r(i)}if(!Ft(s))return;let n=Promise.resolve(s).then(void 0,r).finally(()=>o?.delete(n));o?.add(n)}function Ft(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&typeof t.then=="function"}var O=bt;function xt(t,e){let o=[],r=function(s,n){for(;o.length>0&&o[o.length-1].holder!==this;)o.pop();if(typeof n=="bigint")return`${n}n`;if(typeof n!="object"||n===null)return n;if(o.some(l=>l.original===n))return"[Circular]";let i=kt(n);return o.push({holder:i,original:n}),i};try{return JSON.stringify(t,r,e)??String(t)}catch{return String(t)}}function kt(t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t instanceof Map||t instanceof Set?Array.from(t):t}var b=xt;var It="Node.js built-in modules aren't available in this environment";function Rt(){let t=globalThis.process;if(typeof t?.getBuiltinModule!="function")return{IS_BROWSER:!0,IS_LOCAL:!1,nodeModules:()=>{throw new Error(It)}};let e={fs:t.getBuiltinModule("fs"),path:t.getBuiltinModule("path"),util:t.getBuiltinModule("util")};return{IS_BROWSER:!1,IS_LOCAL:!0,nodeModules:()=>e}}var a=Rt();var Pt=(()=>{if(a.IS_LOCAL){let{util:t}=a.nodeModules();return(e,o)=>t.inspect(e,{depth:null,colors:o})}return t=>t instanceof Error?L(t):b(t,2)})(),V=Pt;function vt(t,e){return t.map(o=>c.is.str(o)?o:c.is.obj(o)?V(o,e):String(o)).join(" ")}var m=vt;var Mt={Green:{SGR:"32",CSS:"color: #008000"},LightGreen:{SGR:"2;32",CSS:"color: #006B00"},Yellow:{SGR:"33",CSS:"color: #DAA520"},Red:{SGR:"31",CSS:"color: #FF0000"},Magenta:{SGR:"35",CSS:"color: #FF00FF"},White:{SGR:"38;5;248",CSS:"color: #808080"}},w=Mt;var Ct={Bold:{SGR:"1",CSS:"font-weight: bold"},Underline:{SGR:"4",CSS:"text-decoration: underline"}},C=Ct;var X="\x1B[0m",F=S(w.LightGreen),x=S(w.White),y={Info:{label:"INFO",consoleFn:"info",...S(w.Green)},Important:{label:"IMPORTANT",consoleFn:"info",...S(w.Magenta,C.Bold,C.Underline)},Warning:{label:"WARNING",consoleFn:"warn",...S(w.Yellow)},Error:{label:"ERROR",consoleFn:"error",...S(w.Red)}};function S(...t){return{ansi:`\x1B[${t.map(e=>e.SGR).join(";")}m`,css:t.map(e=>e.CSS).join("; ")}}var k=t=>t,q=(t,e)=>`${e.ansi}${t}${X}`;function I(t,e){let{level:o,args:r}=t,{showTime:s,showDate:n,paint:i}=e,l=i(o.label,o),u=i(m(r,!1),x);return s?`${i(N(n),F)} ${l}: ${u}`:`${l}: ${u}`}function N(t,e=new Date){let o=E(e.getHours()),r=E(e.getMinutes()),s=E(e.getSeconds()),n=E(e.getMilliseconds(),3),i=`${o}:${r}:${s}.${n}`;if(!t)return`[${i}]`;let l=e.getFullYear(),u=E(e.getMonth()+1),h=E(e.getDate());return`[${l}-${u}-${h} ${i}]`}function E(t,e=2){return String(t).padStart(e,"0")}function T(t,e){let o=[],r=[],s;for(let u of t.args)u instanceof Error&&!s?(s=u,o.push(u.message)):typeof u=="object"&&u!==null?r.push(u):o.push(String(u));let n=t.level.label,i=o.join(" "),l=e?{time:new Date().toISOString(),level:n,msg:i}:{level:n,msg:i};return r.length>0&&(l.data=r.length===1?r[0]:r),s&&(l.stack=z(s)),b(l)}function Q(t,e){let o=e instanceof Error?L(e):String(e),r=`jet-logger: ${t}: ${o}`;a.IS_LOCAL?process.stderr.write(r+`
5
+ `):console.error(r)}var A=class t{#t;constructor(e){this.#t=e}static of(e){let{format:o,showTime:r}=e;return o===f.JSON?new t(s=>["%s",T(s,r)]):new t(s=>Nt(s,r))}writeLog(e){let o=this.#t(e);console[e.level.consoleFn](...o)}writeRaw(e){let o=m(e,!1);console.info("%s",o)}flush(){return Promise.resolve()}close(){return Promise.resolve()}};function Nt(t,e){let{level:o,args:r}=t,s=m(r,!1),n=[o.css,o.label,x.css,s];return e?["%c%s %c%s: %c%s",...[F.css,N(!1)],...n]:["%c%s: %c%s",...n]}var Z=A;var J=class t{#t;#e;#o;constructor(e){this.#t=e,this.#e=tt(process.stdout),this.#o=tt(process.stderr)}static of(e){let{format:o,showTime:r}=e;return o===f.JSON?new t(s=>T(s,r)):new t((s,n)=>I(s,{showTime:r,showDate:!1,paint:n?q:k}))}writeLog(e){if(e.level.consoleFn==="info"){let o=this.#t(e,this.#e);process.stdout.write(o+`
6
+ `)}else{let o=this.#t(e,this.#o);process.stderr.write(o+`
7
+ `)}}writeRaw(e){let o=m(e,this.#e);process.stdout.write(o+`
8
+ `)}async flush(){let e=et(process.stdout),o=et(process.stderr);await Promise.all([e,o])}close(){return this.flush()}};function tt(t){let{FORCE_COLOR:e,NO_COLOR:o}=process.env;if(e!==void 0){let r=e.toLowerCase();return!["0","false"].includes(r)}return o?!1:t.isTTY===!0&&(t.hasColors?.()??!0)}function et(t){return new Promise(e=>t.write("",()=>e()))}var ot=J;function At(t,e){let{path:o}=a.nodeModules(),r=o.parse(t);return o.format({...r,base:void 0,ext:"."+e})}var nt=At;function Jt(t,e=new Date){let{path:o}=a.nodeModules(),r=o.parse(t),s=`${_t(e)}_${r.base}`;return o.format({...r,base:s})}function _t(t){return t.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,"")}var rt=Jt;var _="jet-logger.log",R=()=>({mode:p.CONSOLE,format:f.LINE,filepath:_,prependTimeToFilename:!1,showTime:!0,customTransport:null});var Wt=["SIGINT","SIGTERM"],st=!1,W=new Set;function it(t){W.add(t),!st&&(st=!0,process.on("exit",ut),Wt.forEach(e=>process.on(e,lt)))}function lt(t){ut(),!(process.listenerCount(t)>1)&&(process.off(t,lt),process.kill(process.pid,t))}function ut(){W.forEach(t=>t.flushSync())}function at(t){W.delete(t)}var Gt=1e3;function jt(t,e){let{fs:o}=a.nodeModules(),r=0;for(;e.length>0;)try{e=e.subarray(o.writeSync(t,e)),r=0}catch(s){if(!(s.code==="EAGAIN")||++r>Gt)throw s;Bt(1)}}function Bt(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}var ct=jt;var $t=2,Dt=64*1024,G=new Map,j=class t{#t;#e;#o="";#n;#r=0;constructor(e,o){this.#t=e,this.#e=o}static open(e){let{fs:o,path:r}=a.nodeModules(),s=r.resolve(e),n=G.get(s);if(!n){o.mkdirSync(r.dirname(s),{recursive:!0});let i=o.openSync(s,"a");n=new t(s,i),G.set(s,n),it(n)}return n.#r++,n}write(e){this.#o+=e,this.#o.length>=Dt?this.flushSync():this.#n??=setImmediate(()=>this.flushSync())}flush(){return this.flushSync(),Promise.resolve()}flushSync(){if(this.#n&&(clearImmediate(this.#n),this.#n=void 0),this.#o.length===0)return;let e=this.#o;this.#o="",Ht(this.#e,e)}async release(){await this.flush(),this.#r--,!(this.#r>0)&&(G.delete(this.#t),at(this),a.nodeModules().fs.closeSync(this.#e))}};function Ht(t,e){try{ct(t,Buffer.from(e,"utf8"))}catch(o){Ut(o)}}function Ut(t){let e=t instanceof Error?t.message:String(t);try{a.nodeModules().fs.writeSync($t,`jet-logger: file write failed: ${e}
9
+ `)}catch{}}var ft=j;var B=class t{#t;#e;constructor(e,o){this.#t=e,this.#e=o}static of(e){let{format:o,showTime:r}=e,s=Yt(e),n=ft.open(s);return o===f.JSON?new t(n,i=>T(i,r)):new t(n,i=>I(i,{showTime:r,showDate:!0,paint:k}))}writeLog(e){this.#t.write(this.#e(e)+`
10
+ `)}writeRaw(e){this.#t.write(m(e,!1)+`
11
+ `)}flush(){return this.#t.flush()}close(){return this.#t.release()}};function Yt(t){let{filepath:e}=t;return t.format===f.JSON&&Kt(e)&&(e=nt(e,"jsonl")),t.prependTimeToFilename&&(e=rt(e)),e}function Kt(t){let{path:e}=a.nodeModules();return e.basename(t)===_}var pt=B;function zt(){let t=globalThis.process?.env;if(!t)return{};let{JET_LOGGER_MODE:e,JET_LOGGER_FILEPATH:o,JET_LOGGER_PREPEND_TIME_TO_FILENAME:r,JET_LOGGER_SHOW_TIME:s,JET_LOGGER_FORMAT:n}=t,i={},l=e?.toLowerCase();p.is(l)&&(i.mode=l),c.is.neStr(o)&&(i.filepath=o);let u=c.parse.bool(r);c.is.def(u)&&(i.prependTimeToFilename=u);let h=c.parse.bool(s);c.is.def(h)&&(i.showTime=h);let H=n?.toLowerCase();return f.is(H)&&(i.format=H),i}var mt=zt;var $=class t extends Error{property;value;constructor(e,o,r){super(e),this.name="InvalidOptionError",this.property=o,this.value=r}static of(e,o,r){let s=`Invalid option "${e}": ${Vt(o)}`;return r&&(s+=`. ${r}`),new t(s,e,o)}};function Vt(t){if(typeof t=="function")return`[Function ${t.name||"anonymous"}]`;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var d=$;var Xt='The mode is set to "custom". The "customTransport" must be a valid function type.',qt=Object.keys(R()),Qt=new Set(qt);function Zt(t){if(typeof t!="object"||t===null)throw d.of("options",t);for(let[l,u]of Object.entries(t))if(!Qt.has(l))throw d.of(l,u,"Unknown option");let{mode:e,format:o,showTime:r,prependTimeToFilename:s,filepath:n,customTransport:i}=t;if(!p.is(e))throw d.of("mode",e);if(!f.is(o))throw d.of("format",o);if(!c.is.bool(r))throw d.of("showTime",r);if(!c.is.bool(s))throw d.of("prependTimeToFilename",s);if(!c.is.neStr(n))throw d.of("filepath",n);if(!c.is.nul.fn(i))throw d.of("customTransport",i);if(e===p.CUSTOM&&!c.is.fn(i))throw d.of("customTransport",i,Xt)}var dt=Zt;function te(t){let e={...R(),...mt(),...se(t)};return dt(e),e.mode===p.OFF?ne():e.mode===p.CUSTOM?re(e.customTransport):ee(e)}function ee(t){let e=oe(t),o=new Set,r=!1,s,n=(i,l)=>{r||e.writeLog({level:i,args:l})};return{info:(...i)=>n(y.Info,i),warn:(...i)=>n(y.Warning,i),imp:(...i)=>n(y.Important,i),err:(...i)=>n(y.Error,i),line:()=>{r||e.writeRaw([])},out:(...i)=>{r||e.writeRaw(i)},catch:i=>{O(i,u=>n(y.Error,[M(u)]),o)},flush:async()=>{await P(o),await e.flush()},close:()=>s??=(async()=>{await P(o),r=!0,await e.close()})()}}function oe(t){return a.IS_BROWSER||t.mode===p.BROWSER?Z.of(t):t.mode===p.FILE?pt.of(t):ot.of(t)}function ne(){let t=()=>{};return{info:t,warn:t,imp:t,err:t,line:t,out:t,catch:e=>O(e,t),flush:()=>Promise.resolve(),close:()=>Promise.resolve()}}function re(t){let e=new Set,o=!1,r,s=(n,i)=>{if(o)return;let l={time:new Date().toISOString(),level:n,msg:m(i,!1)};O(()=>t(l),h=>Q("customTransport failed",h),e)};return{info:(...n)=>s("INFO",n),warn:(...n)=>s("WARNING",n),imp:(...n)=>s("IMPORTANT",n),err:(...n)=>s("ERROR",n),line:()=>s(null,[`
12
+ `]),out:(...n)=>s(null,n),catch:n=>{O(n,l=>s("ERROR",[M(l)]),e)},flush:()=>P(e),close:()=>r??=P(e).then(()=>{o=!0})}}function se(t){if(!t)return{};let e=Object.entries(t).filter(([,o])=>o!==void 0);return Object.fromEntries(e)}async function P(t){for(;t.size>0;)await Promise.all(t)}var D=te;var ie=Object.assign(D,{Modes:p.enum(),Formats:f.enum()}),le,g=()=>le??=D(),ue=Object.freeze({info:(...t)=>g().info(...t),warn:(...t)=>g().warn(...t),err:(...t)=>g().err(...t),imp:(...t)=>g().imp(...t),line:()=>g().line(),out:(...t)=>g().out(...t),catch:t=>g().catch(t),flush:()=>g().flush(),close:()=>g().close()}),Uo=ie,Yo=ue;export{d as InvalidOptionError,Uo as JetLogger,Yo as default};
package/package.json CHANGED
@@ -1,31 +1,43 @@
1
1
  {
2
2
  "name": "jet-logger",
3
- "version": "2.2.2",
4
- "description": "A super quick, easy to setup logging tool for NodeJS/TypeScript.",
3
+ "version": "3.0.0",
4
+ "description": "A super quick, easy to setup TypeScript first logging tool for NodeJS and browsers.",
5
5
  "type": "module",
6
- "main": "./dist/cjs/index.js",
7
- "module": "./dist/esm/index.js",
8
- "browser": "./dist/esm/index.js",
9
- "types": "./dist/types/index.d.ts",
6
+ "main": "lib/index.js",
7
+ "types": "lib/index.d.ts",
10
8
  "exports": {
11
9
  ".": {
12
- "import": "./dist/esm/index.js",
13
- "require": "./dist/cjs/index.js",
14
- "types": "./dist/types/index.d.ts"
10
+ "types": "./lib/index.d.ts",
11
+ "default": "./lib/index.js"
15
12
  }
16
13
  },
17
14
  "files": [
18
- "dist"
15
+ "lib"
19
16
  ],
17
+ "engines": {
18
+ "node": ">=20.16.0 <21 || >=22.3.0"
19
+ },
20
20
  "scripts": {
21
- "build": "rm -rf ./dist && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && tsc -p tsconfig.types.json",
22
- "clean-install": "rm -rf ./node_modules && rm -r package-lock.json && npm i",
23
- "lint": "eslint .",
24
- "format": "eslint --fix .",
25
- "playground": "tsx ./test/playground.ts",
26
- "pre-publish": "mv README.md README-git && mv README-npm README.md",
27
- "post-publish": "mv README.md README-npm && mv README-git README.md",
28
- "test": "NODE_ENV=test vitest"
21
+ "benchmark": "tsx scripts/benchmark.ts",
22
+ "build": "tsx scripts/build.ts",
23
+ "commit": "npm run format && git add -A && git commit -m \"dev commit\"",
24
+ "commit:push": "npm run commit && git push",
25
+ "demo:gif": "bash demo-studio/start.sh",
26
+ "install:clean": "rm -rf node_modules && rm -f package-lock.json && npm i",
27
+ "lint": "eslint . --max-warnings 0",
28
+ "lint:fix": "eslint . --fix",
29
+ "format": "prettier --write .",
30
+ "format:check": "prettier --check .",
31
+ "npm-data": "npm run build && npm pack --dry-run --json",
32
+ "prepack": "npm run readme:swap",
33
+ "prepublishOnly": "npm run build && tsc && npm run lint && npm run format:check && npm test && npm run test:browser && npm run verify:package",
34
+ "postpack": "npm run readme:restore",
35
+ "readme:swap": "tsx scripts/readme.ts swap",
36
+ "readme:restore": "tsx scripts/readme.ts restore",
37
+ "test": "vitest run",
38
+ "test:browser": "vitest run --config vitest.browser.config.ts",
39
+ "typecheck": "tsc",
40
+ "verify:package": "tsx scripts/verifyPackage.ts"
29
41
  },
30
42
  "repository": {
31
43
  "type": "git",
@@ -58,23 +70,24 @@
58
70
  "url": "https://github.com/seanpmaxwell/jet-logger/issues"
59
71
  },
60
72
  "homepage": "https://github.com/seanpmaxwell/jet-logger#readme",
61
- "dependencies": {
62
- "colors": "1.4.0"
63
- },
64
73
  "devDependencies": {
65
- "@eslint/js": "^9.26.0",
66
- "@stylistic/eslint-plugin": "^5.6.1",
67
- "@trivago/prettier-plugin-sort-imports": "^6.0.1",
68
- "@types/node": "^22.8.1",
69
- "eslint": "^9.26.0",
74
+ "@eslint/js": "^10.0.1",
75
+ "@trivago/prettier-plugin-sort-imports": "^6.0.2",
76
+ "@types/node": "^20.19.43",
77
+ "@vitest/browser": "^4.1.11",
78
+ "@vitest/browser-playwright": "^4.1.11",
79
+ "chalk": "^6.0.0",
80
+ "dts-bundle-generator": "^9.5.1",
81
+ "esbuild": "^0.28.2",
82
+ "eslint": "^10.7.0",
70
83
  "eslint-config-prettier": "^10.1.8",
71
- "eslint-plugin-n": "^17.17.0",
72
- "eslint-plugin-prettier": "^5.5.4",
73
- "jiti": "^2.3.3",
74
- "prettier": "^3.7.4",
75
- "typescript": "~5.9.3",
76
- "tsx": "^4.19.1",
77
- "typescript-eslint": "^8.50.0",
78
- "vitest": "^4.0.15"
84
+ "globals": "^17.7.0",
85
+ "jiti": "^2.7.0",
86
+ "playwright": "^1.63.0",
87
+ "prettier": "^3.9.5",
88
+ "tsx": "^4.23.11",
89
+ "typescript": "^6.0.3",
90
+ "typescript-eslint": "^8.65.0",
91
+ "vitest": "^4.1.10"
79
92
  }
80
93
  }
package/dist/cjs/index.js DELETED
@@ -1 +0,0 @@
1
- export { JetLogger, jetLogger, default, } from './jetLogger.js';
@@ -1,219 +0,0 @@
1
- import colors from 'colors';
2
- import fs from 'fs';
3
- import util from 'util';
4
- const LOGGER_MODES = {
5
- Console: 'CONSOLE',
6
- File: 'FILE',
7
- Custom: 'CUSTOM',
8
- Off: 'OFF',
9
- };
10
- const FORMATS = {
11
- Line: 'LINE',
12
- Json: 'JSON',
13
- };
14
- const LEVELS = {
15
- Info: {
16
- Color: 'green',
17
- Prefix: 'INFO',
18
- },
19
- Important: {
20
- Color: 'magenta',
21
- Prefix: 'IMPORTANT',
22
- },
23
- Warning: {
24
- Color: 'yellow',
25
- Prefix: 'WARNING',
26
- },
27
- Error: {
28
- Color: 'red',
29
- Prefix: 'ERROR',
30
- },
31
- };
32
- const DEFAULTS = {
33
- mode: LOGGER_MODES.Console,
34
- filePath: 'jet-logger.log',
35
- timestamp: true,
36
- format: FORMATS.Line,
37
- customLogFn: () => ({}),
38
- };
39
- const Errors = {
40
- CustomLogger: 'Custom logger mode set to true, but no custom logger was provided.',
41
- Mode: 'The correct logger mode was not specified: Must be "CUSTOM", "FILE", ' +
42
- '"OFF", or "CONSOLE".',
43
- };
44
- export const JetLogger = {
45
- Modes: LOGGER_MODES,
46
- Formats: FORMATS,
47
- };
48
- export function jetLogger(options) {
49
- let mode = DEFAULTS.mode, filePath = DEFAULTS.filePath, timestamp = DEFAULTS.timestamp, format = DEFAULTS.format, customLogFn = DEFAULTS.customLogFn;
50
- if (options?.mode !== undefined) {
51
- mode = options.mode;
52
- }
53
- else if (!!process.env.JET_LOGGER_MODE) {
54
- mode = process.env.JET_LOGGER_MODE.toUpperCase();
55
- }
56
- if (mode === LOGGER_MODES.Off) {
57
- return {
58
- info: (_, __) => ({}),
59
- imp: (_, __) => ({}),
60
- warn: (_, __) => ({}),
61
- err: (_, __) => ({}),
62
- };
63
- }
64
- if (mode === LOGGER_MODES.Custom) {
65
- if (options?.customLogger !== undefined) {
66
- customLogFn = options.customLogger;
67
- }
68
- if (!customLogFn) {
69
- throw Error(Errors.CustomLogger);
70
- }
71
- return {
72
- info: setupPrintWithCustomLogger(LEVELS.Info, customLogFn),
73
- imp: setupPrintWithCustomLogger(LEVELS.Important, customLogFn),
74
- warn: setupPrintWithCustomLogger(LEVELS.Warning, customLogFn),
75
- err: setupPrintWithCustomLogger(LEVELS.Error, customLogFn),
76
- };
77
- }
78
- if (options?.filepath !== undefined) {
79
- filePath = options.filepath;
80
- }
81
- else if (!!process.env.JET_LOGGER_FILEPATH) {
82
- filePath = process.env.JET_LOGGER_FILEPATH;
83
- }
84
- if (options?.timestamp !== undefined) {
85
- timestamp = options.timestamp;
86
- }
87
- else if (!!process.env.JET_LOGGER_TIMESTAMP) {
88
- const envVar = process.env.JET_LOGGER_TIMESTAMP;
89
- timestamp = envVar.toUpperCase() === 'TRUE';
90
- }
91
- if (options?.format !== undefined) {
92
- format = options.format;
93
- }
94
- else if (!!process.env.JET_LOGGER_FORMAT) {
95
- format = process.env.JET_LOGGER_FORMAT.toUpperCase();
96
- }
97
- let formatter = () => '';
98
- if (format === FORMATS.Line) {
99
- formatter = setupLineFormatter(timestamp);
100
- }
101
- else if (format === FORMATS.Json) {
102
- formatter = setupJsonFormatter(timestamp);
103
- }
104
- if (mode === LOGGER_MODES.File) {
105
- let filePathDatetime = true;
106
- if (options?.filepathDatetimeParam !== undefined) {
107
- filePathDatetime = options.filepathDatetimeParam;
108
- }
109
- else if (!!process.env.JET_LOGGER_FILEPATH_DATETIME) {
110
- const envVar = process.env.JET_LOGGER_FILEPATH_DATETIME;
111
- filePathDatetime = envVar.toUpperCase() === 'TRUE';
112
- }
113
- if (filePathDatetime) {
114
- filePath = addDatetimeToFileName(filePath);
115
- }
116
- return {
117
- info: setupPrintToFile(LEVELS.Info, formatter, filePath),
118
- imp: setupPrintToFile(LEVELS.Important, formatter, filePath),
119
- warn: setupPrintToFile(LEVELS.Warning, formatter, filePath),
120
- err: setupPrintToFile(LEVELS.Error, formatter, filePath),
121
- };
122
- }
123
- return {
124
- info: setupPrintToConsole(LEVELS.Info, formatter),
125
- imp: setupPrintToConsole(LEVELS.Important, formatter),
126
- warn: setupPrintToConsole(LEVELS.Warning, formatter),
127
- err: setupPrintToConsole(LEVELS.Error, formatter),
128
- };
129
- }
130
- function setupPrintWithCustomLogger(level, customLogFn) {
131
- return (content, printFull) => {
132
- let contentNew;
133
- if (printFull) {
134
- contentNew = util.inspect(content);
135
- }
136
- else {
137
- contentNew = String(content);
138
- }
139
- return customLogFn(new Date(), level.Prefix, contentNew);
140
- };
141
- }
142
- function setupLineFormatter(timestamp) {
143
- if (timestamp) {
144
- return (content, level) => {
145
- const contentNew = level.Prefix + ': ' + content, time = '[' + new Date().toISOString() + '] ';
146
- return time + contentNew;
147
- };
148
- }
149
- else {
150
- return (content, level) => {
151
- return level.Prefix + ': ' + content;
152
- };
153
- }
154
- }
155
- function setupJsonFormatter(timestamp) {
156
- if (timestamp) {
157
- return (content, level) => {
158
- const json = {
159
- level: level.Prefix,
160
- message: content,
161
- };
162
- json.timestamp = new Date().toISOString();
163
- return JSON.stringify(json);
164
- };
165
- }
166
- else {
167
- return (content, level) => {
168
- const json = {
169
- level: level.Prefix,
170
- message: content,
171
- };
172
- return JSON.stringify(json);
173
- };
174
- }
175
- }
176
- function setupPrintToFile(level, formatter, filePath) {
177
- return (content, printFull) => {
178
- let contentNew;
179
- if (!!printFull) {
180
- contentNew = util.inspect(content);
181
- }
182
- else {
183
- contentNew = String(content);
184
- }
185
- contentNew = formatter(contentNew, level);
186
- fs.appendFile(filePath, contentNew, (err) => {
187
- if (!!err) {
188
- console.error(err);
189
- }
190
- });
191
- };
192
- }
193
- function setupPrintToConsole(level, formatter) {
194
- return (content, printFull) => {
195
- let contentNew;
196
- if (!!printFull) {
197
- contentNew = util.inspect(content);
198
- }
199
- else {
200
- contentNew = String(content);
201
- }
202
- const colorFn = colors[level.Color];
203
- contentNew = formatter(contentNew, level);
204
- console.log(colorFn(contentNew));
205
- };
206
- }
207
- function addDatetimeToFileName(filePath) {
208
- const dateStr = new Date()
209
- .toISOString()
210
- .split('-')
211
- .join('')
212
- .split(':')
213
- .join('')
214
- .slice(0, 15);
215
- const filePathArr = filePath.split('/'), lastIdx = filePathArr.length - 1, fileName = filePathArr[lastIdx], fileNameNew = dateStr + '_' + fileName;
216
- filePathArr[lastIdx] = fileNameNew;
217
- return filePathArr.join('/');
218
- }
219
- export default jetLogger();
package/dist/esm/index.js DELETED
@@ -1 +0,0 @@
1
- export { JetLogger, jetLogger, default, } from './jetLogger.js';
@@ -1,219 +0,0 @@
1
- import colors from 'colors';
2
- import fs from 'fs';
3
- import util from 'util';
4
- const LOGGER_MODES = {
5
- Console: 'CONSOLE',
6
- File: 'FILE',
7
- Custom: 'CUSTOM',
8
- Off: 'OFF',
9
- };
10
- const FORMATS = {
11
- Line: 'LINE',
12
- Json: 'JSON',
13
- };
14
- const LEVELS = {
15
- Info: {
16
- Color: 'green',
17
- Prefix: 'INFO',
18
- },
19
- Important: {
20
- Color: 'magenta',
21
- Prefix: 'IMPORTANT',
22
- },
23
- Warning: {
24
- Color: 'yellow',
25
- Prefix: 'WARNING',
26
- },
27
- Error: {
28
- Color: 'red',
29
- Prefix: 'ERROR',
30
- },
31
- };
32
- const DEFAULTS = {
33
- mode: LOGGER_MODES.Console,
34
- filePath: 'jet-logger.log',
35
- timestamp: true,
36
- format: FORMATS.Line,
37
- customLogFn: () => ({}),
38
- };
39
- const Errors = {
40
- CustomLogger: 'Custom logger mode set to true, but no custom logger was provided.',
41
- Mode: 'The correct logger mode was not specified: Must be "CUSTOM", "FILE", ' +
42
- '"OFF", or "CONSOLE".',
43
- };
44
- export const JetLogger = {
45
- Modes: LOGGER_MODES,
46
- Formats: FORMATS,
47
- };
48
- export function jetLogger(options) {
49
- let mode = DEFAULTS.mode, filePath = DEFAULTS.filePath, timestamp = DEFAULTS.timestamp, format = DEFAULTS.format, customLogFn = DEFAULTS.customLogFn;
50
- if (options?.mode !== undefined) {
51
- mode = options.mode;
52
- }
53
- else if (!!process.env.JET_LOGGER_MODE) {
54
- mode = process.env.JET_LOGGER_MODE.toUpperCase();
55
- }
56
- if (mode === LOGGER_MODES.Off) {
57
- return {
58
- info: (_, __) => ({}),
59
- imp: (_, __) => ({}),
60
- warn: (_, __) => ({}),
61
- err: (_, __) => ({}),
62
- };
63
- }
64
- if (mode === LOGGER_MODES.Custom) {
65
- if (options?.customLogger !== undefined) {
66
- customLogFn = options.customLogger;
67
- }
68
- if (!customLogFn) {
69
- throw Error(Errors.CustomLogger);
70
- }
71
- return {
72
- info: setupPrintWithCustomLogger(LEVELS.Info, customLogFn),
73
- imp: setupPrintWithCustomLogger(LEVELS.Important, customLogFn),
74
- warn: setupPrintWithCustomLogger(LEVELS.Warning, customLogFn),
75
- err: setupPrintWithCustomLogger(LEVELS.Error, customLogFn),
76
- };
77
- }
78
- if (options?.filepath !== undefined) {
79
- filePath = options.filepath;
80
- }
81
- else if (!!process.env.JET_LOGGER_FILEPATH) {
82
- filePath = process.env.JET_LOGGER_FILEPATH;
83
- }
84
- if (options?.timestamp !== undefined) {
85
- timestamp = options.timestamp;
86
- }
87
- else if (!!process.env.JET_LOGGER_TIMESTAMP) {
88
- const envVar = process.env.JET_LOGGER_TIMESTAMP;
89
- timestamp = envVar.toUpperCase() === 'TRUE';
90
- }
91
- if (options?.format !== undefined) {
92
- format = options.format;
93
- }
94
- else if (!!process.env.JET_LOGGER_FORMAT) {
95
- format = process.env.JET_LOGGER_FORMAT.toUpperCase();
96
- }
97
- let formatter = () => '';
98
- if (format === FORMATS.Line) {
99
- formatter = setupLineFormatter(timestamp);
100
- }
101
- else if (format === FORMATS.Json) {
102
- formatter = setupJsonFormatter(timestamp);
103
- }
104
- if (mode === LOGGER_MODES.File) {
105
- let filePathDatetime = true;
106
- if (options?.filepathDatetimeParam !== undefined) {
107
- filePathDatetime = options.filepathDatetimeParam;
108
- }
109
- else if (!!process.env.JET_LOGGER_FILEPATH_DATETIME) {
110
- const envVar = process.env.JET_LOGGER_FILEPATH_DATETIME;
111
- filePathDatetime = envVar.toUpperCase() === 'TRUE';
112
- }
113
- if (filePathDatetime) {
114
- filePath = addDatetimeToFileName(filePath);
115
- }
116
- return {
117
- info: setupPrintToFile(LEVELS.Info, formatter, filePath),
118
- imp: setupPrintToFile(LEVELS.Important, formatter, filePath),
119
- warn: setupPrintToFile(LEVELS.Warning, formatter, filePath),
120
- err: setupPrintToFile(LEVELS.Error, formatter, filePath),
121
- };
122
- }
123
- return {
124
- info: setupPrintToConsole(LEVELS.Info, formatter),
125
- imp: setupPrintToConsole(LEVELS.Important, formatter),
126
- warn: setupPrintToConsole(LEVELS.Warning, formatter),
127
- err: setupPrintToConsole(LEVELS.Error, formatter),
128
- };
129
- }
130
- function setupPrintWithCustomLogger(level, customLogFn) {
131
- return (content, printFull) => {
132
- let contentNew;
133
- if (printFull) {
134
- contentNew = util.inspect(content);
135
- }
136
- else {
137
- contentNew = String(content);
138
- }
139
- return customLogFn(new Date(), level.Prefix, contentNew);
140
- };
141
- }
142
- function setupLineFormatter(timestamp) {
143
- if (timestamp) {
144
- return (content, level) => {
145
- const contentNew = level.Prefix + ': ' + content, time = '[' + new Date().toISOString() + '] ';
146
- return time + contentNew;
147
- };
148
- }
149
- else {
150
- return (content, level) => {
151
- return level.Prefix + ': ' + content;
152
- };
153
- }
154
- }
155
- function setupJsonFormatter(timestamp) {
156
- if (timestamp) {
157
- return (content, level) => {
158
- const json = {
159
- level: level.Prefix,
160
- message: content,
161
- };
162
- json.timestamp = new Date().toISOString();
163
- return JSON.stringify(json);
164
- };
165
- }
166
- else {
167
- return (content, level) => {
168
- const json = {
169
- level: level.Prefix,
170
- message: content,
171
- };
172
- return JSON.stringify(json);
173
- };
174
- }
175
- }
176
- function setupPrintToFile(level, formatter, filePath) {
177
- return (content, printFull) => {
178
- let contentNew;
179
- if (!!printFull) {
180
- contentNew = util.inspect(content);
181
- }
182
- else {
183
- contentNew = String(content);
184
- }
185
- contentNew = formatter(contentNew, level);
186
- fs.appendFile(filePath, contentNew, (err) => {
187
- if (!!err) {
188
- console.error(err);
189
- }
190
- });
191
- };
192
- }
193
- function setupPrintToConsole(level, formatter) {
194
- return (content, printFull) => {
195
- let contentNew;
196
- if (!!printFull) {
197
- contentNew = util.inspect(content);
198
- }
199
- else {
200
- contentNew = String(content);
201
- }
202
- const colorFn = colors[level.Color];
203
- contentNew = formatter(contentNew, level);
204
- console.log(colorFn(contentNew));
205
- };
206
- }
207
- function addDatetimeToFileName(filePath) {
208
- const dateStr = new Date()
209
- .toISOString()
210
- .split('-')
211
- .join('')
212
- .split(':')
213
- .join('')
214
- .slice(0, 15);
215
- const filePathArr = filePath.split('/'), lastIdx = filePathArr.length - 1, fileName = filePathArr[lastIdx], fileNameNew = dateStr + '_' + fileName;
216
- filePathArr[lastIdx] = fileNameNew;
217
- return filePathArr.join('/');
218
- }
219
- export default jetLogger();
@@ -1 +0,0 @@
1
- export { type CustomLogger, JetLogger, jetLogger, default, } from './jetLogger.js';
@@ -1,62 +0,0 @@
1
- /******************************************************************************
2
- Constants
3
- ******************************************************************************/
4
- declare const LOGGER_MODES: {
5
- readonly Console: "CONSOLE";
6
- readonly File: "FILE";
7
- readonly Custom: "CUSTOM";
8
- readonly Off: "OFF";
9
- };
10
- declare const FORMATS: {
11
- readonly Line: "LINE";
12
- readonly Json: "JSON";
13
- };
14
- export declare const JetLogger: {
15
- readonly Modes: {
16
- readonly Console: "CONSOLE";
17
- readonly File: "FILE";
18
- readonly Custom: "CUSTOM";
19
- readonly Off: "OFF";
20
- };
21
- readonly Formats: {
22
- readonly Line: "LINE";
23
- readonly Json: "JSON";
24
- };
25
- };
26
- /******************************************************************************
27
- Types
28
- ******************************************************************************/
29
- type LoggerModes = (typeof LOGGER_MODES)[keyof typeof LOGGER_MODES];
30
- type Formats = (typeof FORMATS)[keyof typeof FORMATS];
31
- type LogFunction = (content: unknown, printFull?: boolean) => void;
32
- export type CustomLogger = (timestamp: Date, prefix: string, content: unknown) => void;
33
- interface Options {
34
- mode?: LoggerModes;
35
- filepath?: string;
36
- filepathDatetimeParam?: boolean;
37
- timestamp?: boolean;
38
- format?: Formats;
39
- customLogger?: CustomLogger;
40
- }
41
- /******************************************************************************
42
- Functions
43
- ******************************************************************************/
44
- /**
45
- * Default function
46
- */
47
- export declare function jetLogger(options?: Options): {
48
- readonly info: LogFunction;
49
- readonly imp: LogFunction;
50
- readonly warn: LogFunction;
51
- readonly err: LogFunction;
52
- };
53
- /******************************************************************************
54
- Export
55
- ******************************************************************************/
56
- declare const _default: {
57
- readonly info: LogFunction;
58
- readonly imp: LogFunction;
59
- readonly warn: LogFunction;
60
- readonly err: LogFunction;
61
- };
62
- export default _default;