@better-logger/core 0.2.0 → 0.4.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/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var R=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var Z=(e,r)=>{for(var t in r)R(e,t,{get:r[t],enumerable:!0})},j=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of V(r))!X.call(e,s)&&s!==t&&R(e,s,{get:()=>r[s],enumerable:!(n=Q(r,s))||n.enumerable});return e};var ee=e=>j(R({},"__esModule",{value:!0}),e);var xe={};Z(xe,{NOOP_FLOW:()=>a,NOOP_STEP:()=>c,createFlow:()=>Y,getRenderer:()=>E,isEnabled:()=>q,setClock:()=>U,setEnabled:()=>W,setIdGenerator:()=>J,setRenderer:()=>v,subscribe:()=>T,toJSON:()=>P});module.exports=ee(xe);function u(e){return e===void 0?{name:"Error",message:"Unknown error"}:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:typeof e=="string"?{name:"Error",message:e}:{name:"Error",message:String(e)}}var x=class{constructor(r,t){this._trace=r;this._clock=t;this._completed=!1}get isCompleted(){return this._completed}get trace(){return this._trace}success(){this._completed||(this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status="success")}fail(r){this._completed||(this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status="error",this._trace.error=u(r))}};var d=()=>{},c={success:d,fail:d},a={step:()=>c,child:()=>a,tag:d,tags:()=>[],setContext:d,getContext:()=>({}),success:d,fail:d,run:(e,r)=>r()};function D(e){let r=new WeakMap;function t(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(r.has(n))return r.get(n);if(Array.isArray(n)){let i=[];r.set(n,i);for(let o=0;o<n.length;o++)i.push(t(n[o]));return i}let s={};r.set(n,s);for(let i of Object.keys(n))s[i]=t(n[i]);return s}return t(e)}function h(e){if(e===null||typeof e!="object")return e;if(Object.freeze(e),Array.isArray(e))for(let r of e)h(r);else for(let r of Object.keys(e)){let t=e[r];t&&typeof t=="object"&&!Object.isFrozen(t)&&h(t)}return e}function y(e){let r=D(e);return h(r)}var _=new Set;function T(e){return _.add(e),()=>{_.delete(e)}}function re(e){if(_.size!==0)for(let r of _)try{r(e)}catch{}}var S=class e{constructor(r,t,n,s,i){this._trace=r;this._clock=t;this._idGen=n;this._renderer=s;this._options=i;this._completed=!1;this._sequence=0}get isCompleted(){return this._completed}get trace(){return this._trace}step(r,t){if(this._completed)return c;let n=this._options.maxSteps;if(n!==void 0&&this._trace.steps.length>=n)return this._trace.meta===void 0?this._trace.meta={maxStepsExceeded:!0}:this._trace.meta.maxStepsExceeded=!0,c;let s={id:this._idGen.generate(),name:r,sequence:this._sequence++,state:"running",status:"pending",start:this._clock.now(),data:t,children:[]};return this._trace.steps.push(s),new x(s,this._clock)}child(r){if(this._completed)return a;if(this._options.enabled===!1)return a;let t={id:this._idGen.generate(),name:r,parentId:this._trace.id,state:"running",status:void 0,tags:[],start:this._clock.now(),context:{...this._trace.context},steps:[]};return new e(t,this._clock,this._idGen,this._renderer,{...this._options})}tag(r){this._completed||this._trace.tags.includes(r)||this._trace.tags.push(r)}tags(){return[...this._trace.tags]}setContext(r){this._completed||Object.assign(this._trace.context,r)}getContext(){return{...this._trace.context}}success(){this._finalize("success")}fail(r){this._trace.error=u(r),this._finalize("error")}run(r,t){if(this._completed)return Promise.resolve(t());let n=this.step(r);return Promise.resolve(t()).then(s=>(n.success(),s),s=>{throw n.fail(s),s})}_finalize(r){if(this._completed)return;this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status=r;let t=y(this._trace);re(t),this._renderer.render(t)}};var f=class{generate(){return Math.random().toString(36).slice(2,10)}};var p=class{now(){return Date.now()}};function m(e,r){let t=r?.maxDepth??2,n=r?.maxLength??80,s=new WeakSet;function i(o,l){if(typeof o=="function")return`[Fn:${o.name||"?"}]`;if(typeof o=="symbol")return o.toString();if(l>t)return o&&typeof o=="object"?"[...]":o;if(o===null||typeof o!="object")return o;if(o instanceof Map)return`{Map(${o.size})}`;if(o instanceof Set)return`{Set(${o.size})}`;if(o instanceof Date)return o.toISOString();if(o instanceof RegExp)return o.toString();if(s.has(o))return"[Circular]";if(s.add(o),Array.isArray(o))return o.map(g=>i(g,l+1));let H={};for(let g of Object.keys(o)){let K=o[g];H[g]=i(K,l+1)}return H}try{let o=JSON.stringify(i(e,0));return o&&o.length>n?o.slice(0,n)+"\u2026":o}catch{return"[Unserializable]"}}var te=()=>typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0,ne=()=>typeof EdgeRuntime<"u",oe=()=>typeof caches<"u"&&"default"in caches,se=()=>typeof window<"u"||typeof self<"u";function G(){return te()?"node":ne()||oe()?"edge":se()?"browser":"node"}var ie="\x1B[0m",ae="\x1B[32m",ce="\x1B[31m";var de="\x1B[36m";var le="\x1B[2m";function ue(){return!(G()==="browser"||typeof process<"u"&&process.env?.NO_COLOR)}var fe=ue();function k(e,r){return fe?`${r}${e}${ie}`:e}function O(e){return k(e,ae)}function F(e){return k(e,ce)}function I(e){return k(e,de)}function C(e){return k(e,le)}function L(e,r){if(r===void 0)return"\u2014";let t=Math.round(r-e);return t>=1e3?`${(t/1e3).toFixed(1)}s`:`${t}ms`}function A(e,r,t){let n=" ".repeat(r);t.push(`${n}${I("\u2192")} ${e.name}`),e.data!==void 0&&t.push(`${n} ${C("data:")} ${m(e.data,{maxLength:80})}`);let s=L(e.start,e.end);e.status==="success"?t.push(`${n}${O("\u2713")} ${e.name} (${s})`):e.status==="error"?t.push(`${n}${F("\u2717")} ${e.name} (error: ${e.error?.message??"Unknown error"})`):t.push(`${n} ${e.name} (${s})`);for(let i of e.children)A(i,r+1,t)}var w=class{render(r){let t=[],n=r.tags.length>0?` [${r.tags.join(", ")}]`:"",s=r.status==="error"?"\u{1F525}":"\u{1F680}";t.push(`${s} [flow:${r.name}]${n} (${C("tid:")} ${r.id})`);for(let l of r.steps)A(l,1,t);let i=L(r.start,r.end),o=r.meta?.maxStepsExceeded?` ${F("\u26A0\uFE0F maxSteps exceeded")}`:"";r.status==="error"?(t.push(`\u{1F3C1} [flow:${r.name}] ${F("failed")} (${i}, error: ${r.error?.message??"Unknown error"})${o}`),console.error(t.join(`
2
- `))):(t.push(`\u{1F3C1} [flow:${r.name}] ${O("success")} (${i})${o}`),console.log(t.join(`
3
- `)))}};var $=null;function v(e){$=e}function E(){return $}function M(e){return $??e}var b=new f,N=new p,we=new w,z=!0;function W(e){z=e}function q(){return z}function J(e){b=e}function U(e){N=e}function Y(e,r){if(!z)return a;let t=r?.sample??1;if(t<1&&Math.random()>t)return a;if(r?.enabled===!1)return a;let n=M(we),s={id:b.generate(),name:e,state:"running",tags:r?.tags??[],start:N.now(),context:r?.initialContext?{...r.initialContext}:{},steps:[]};return new S(s,N,b,n,r??{})}function ge(e){return typeof e=="object"&&e!==null&&"trace"in e&&typeof e.trace=="object"&&e.trace!==null}function P(e){let r=ge(e)?e.trace:e;return JSON.stringify({version:1,flow:{id:r.id,name:r.name,...r.parentId!==void 0&&{parentId:r.parentId},state:r.state,...r.status!==void 0&&{status:r.status},tags:r.tags,start:r.start,...r.end!==void 0&&{end:r.end},...r.error!==void 0&&{error:r.error},context:r.context,steps:r.steps.map(B),...r.meta!==void 0&&{meta:r.meta}}},null,2)}function B(e){let r={id:e.id,name:e.name,sequence:e.sequence,state:e.state,status:e.status,start:e.start};return e.end!==void 0&&(r.end=e.end),e.data!==void 0&&(r.data=m(e.data)),e.error!==void 0&&(r.error=e.error),e.children.length>0&&(r.children=e.children.map(B)),r}0&&(module.exports={NOOP_FLOW,NOOP_STEP,createFlow,getRenderer,isEnabled,setClock,setEnabled,setIdGenerator,setRenderer,subscribe,toJSON});
1
+ "use strict";var E=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.prototype.hasOwnProperty;var ne=(e,t)=>{for(var r in t)E(e,r,{get:t[r],enumerable:!0})},oe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of te(t))!re.call(e,i)&&i!==r&&E(e,i,{get:()=>t[i],enumerable:!(n=ee(t,i))||n.enumerable});return e};var ie=e=>oe(E({},"__esModule",{value:!0}),e);var Oe={};ne(Oe,{NOOP_FLOW:()=>l,NOOP_STEP:()=>m,createFlow:()=>C,getRenderer:()=>P,isEnabled:()=>Q,log:()=>d,normalizeError:()=>f,safeSerialize:()=>u,setClock:()=>X,setEnabled:()=>K,setIdGenerator:()=>V,setRenderer:()=>I,subscribe:()=>L,toJSON:()=>M});module.exports=ie(Oe);function f(e){return e===void 0?{name:"Error",message:"Unknown error"}:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:typeof e=="string"?{name:"Error",message:e}:{name:"Error",message:String(e)}}var S=class{constructor(t,r){this._trace=t;this._clock=r;this._completed=!1}get isCompleted(){return this._completed}get trace(){return this._trace}success(){this._completed||(this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status="success")}fail(t){this._completed||(this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status="error",this._trace.error=f(t))}};var g=()=>{},m={success:g,fail:g},l={step:()=>m,child:()=>l,tag:g,tags:()=>[],setContext:g,getContext:()=>({}),success:g,fail:g,run:(e,t)=>{try{let r=t();return r instanceof Promise?r:Promise.resolve(r)}catch(r){return Promise.reject(r)}}};function W(e){let t=new WeakMap;function r(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(t.has(n))return t.get(n);if(Array.isArray(n)){let s=[];t.set(n,s);for(let o=0;o<n.length;o++)s.push(r(n[o]));return s}let i={};t.set(n,i);for(let s of Object.keys(n))i[s]=r(n[s]);return i}return r(e)}function k(e){if(e===null||typeof e!="object")return e;if(Object.freeze(e),Array.isArray(e))for(let t of e)k(t);else for(let t of Object.keys(e)){let r=e[t];r&&typeof r=="object"&&!Object.isFrozen(r)&&k(r)}return e}function N(e){let t=W(e);return k(t)}var T=new Set;function L(e){return T.add(e),()=>{T.delete(e)}}function se(e){if(T.size!==0)for(let t of T)try{t(e)}catch{}}var y=class e{constructor(t,r,n,i,s){this._trace=t;this._clock=r;this._idGen=n;this._renderer=i;this._options=s;this._completed=!1;this._sequence=0}get isCompleted(){return this._completed}get trace(){return this._trace}step(t,r){if(this._completed)return m;let n=this._options.maxSteps;if(n!==void 0&&this._trace.steps.length>=n)return this._trace.meta===void 0?this._trace.meta={maxStepsExceeded:!0}:this._trace.meta.maxStepsExceeded=!0,m;let i={id:this._idGen.generate(),name:t,sequence:this._sequence++,state:"running",status:"pending",start:this._clock.now(),data:r,children:[]};return this._trace.steps.push(i),new S(i,this._clock)}child(t){if(this._completed)return l;if(this._options.enabled===!1)return l;let r={id:this._idGen.generate(),name:t,parentId:this._trace.id,state:"running",status:void 0,tags:[],start:this._clock.now(),context:{...this._trace.context},steps:[]};return new e(r,this._clock,this._idGen,this._renderer,{...this._options})}tag(t){this._completed||this._trace.tags.includes(t)||this._trace.tags.push(t)}tags(){return[...this._trace.tags]}setContext(t){this._completed||Object.assign(this._trace.context,t)}getContext(){return{...this._trace.context}}success(){this._finalize("success")}fail(t){this._trace.error=f(t),this._finalize("error")}run(t,r){if(this._completed)return Promise.resolve(r());let n=this.step(t);return Promise.resolve(r()).then(i=>(n.success(),i),i=>{throw n.fail(i),i})}_finalize(t){if(this._completed)return;this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status=t;let r=N(this._trace);se(r),this._renderer.render(r)}};var x=class{generate(){return Math.random().toString(36).slice(2,10)}};var h=class{now(){return Date.now()}};function u(e,t){let r=t?.maxDepth??2,n=t?.maxLength??80,i=new WeakSet;function s(o,c){if(typeof o=="function")return`[Fn:${o.name||"?"}]`;if(typeof o=="symbol")return o.toString();if(c>r)return o&&typeof o=="object"?"[...]":o;if(o===null||typeof o!="object")return o;if(o instanceof Map)return`{Map(${o.size})}`;if(o instanceof Set)return`{Set(${o.size})}`;if(o instanceof Date)return o.toISOString();if(o instanceof RegExp)return o.toString();if(i.has(o))return"[Circular]";if(i.add(o),Array.isArray(o))return o.map(p=>s(p,c+1));let _={};for(let p of Object.keys(o)){let $=o[p];_[p]=s($,c+1)}return _}try{let o=JSON.stringify(s(e,0));return o&&o.length>n?o.slice(0,n)+"\u2026":o}catch{return"[Unserializable]"}}var ae=()=>typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0,le=()=>typeof EdgeRuntime<"u",ce=()=>typeof caches<"u"&&"default"in caches,de=()=>typeof window<"u"||typeof self<"u";function q(){return ae()?"node":le()||ce()?"edge":de()?"browser":"node"}var fe="\x1B[0m",ue="\x1B[32m",pe="\x1B[31m";var me="\x1B[36m";var ge="\x1B[2m";function we(){return!(q()==="browser"||typeof process<"u"&&process.env?.NO_COLOR)}var xe=we();function R(e,t){return xe?`${t}${e}${fe}`:e}function b(e){return R(e,ue)}function O(e){return R(e,pe)}function J(e){return R(e,me)}function z(e){return R(e,ge)}function U(e,t){if(t===void 0)return"\u2014";let r=Math.round(t-e);return r>=1e3?`${(r/1e3).toFixed(1)}s`:`${r}ms`}function B(e,t,r){let n=" ".repeat(t);r.push(`${n}${J("\u2192")} ${e.name}`),e.data!==void 0&&r.push(`${n} ${z("data:")} ${u(e.data,{maxLength:80})}`);let i=U(e.start,e.end);e.status==="success"?r.push(`${n}${b("\u2713")} ${e.name} (${i})`):e.status==="error"?r.push(`${n}${O("\u2717")} ${e.name} (error: ${e.error?.message??"Unknown error"})`):r.push(`${n} ${e.name} (${i})`);for(let s of e.children)B(s,t+1,r)}var F=class{constructor(){this.name="console"}render(t){let r=[],n=t.tags.length>0?` [${t.tags.join(", ")}]`:"",i=t.status==="error"?"\u{1F525}":"\u{1F680}";r.push(`${i} [flow:${t.name}]${n} (${z("tid:")} ${t.id})`);for(let c of t.steps)B(c,1,r);let s=U(t.start,t.end),o=t.meta?.maxStepsExceeded?` ${O("\u26A0\uFE0F maxSteps exceeded")}`:"";t.status==="error"?(r.push(`\u{1F3C1} [flow:${t.name}] ${O("failed")} (${s}, error: ${t.error?.message??"Unknown error"})${o}`),console.error(r.join(`
2
+ `))):(r.push(`\u{1F3C1} [flow:${t.name}] ${b("success")} (${s})${o}`),console.log(r.join(`
3
+ `)))}};var H=null;function I(e){H=e}function P(){return H}function Y(e){return H??e}var D=new x,G=new h,_e=new F,A=!0;function K(e){A=e}function Q(){return A}function V(e){D=e}function X(e){G=e}function C(e,t){if(!A)return l;let r=t?.sample??1;if(r<1&&Math.random()>r)return l;if(t?.enabled===!1)return l;let n=Y(_e),i={id:D.generate(),name:e,state:"running",tags:t?.tags??[],start:G.now(),context:t?.initialContext?{...t.initialContext}:{},steps:[]};return new y(i,G,D,n,t??{})}var w={idleTimeout:100,flowName:"default",defaultTags:[]},a=null;function Se(e){if(a&&e===void 0&&!a.completed)return a.flow;let t=e??w.flowName,r=C(t,{tags:[...w.defaultTags]});return a={flow:r,timer:null,lastError:null,completed:!1},r}function ke(){a&&(a.timer&&clearTimeout(a.timer),a.timer=setTimeout(()=>{Z()},w.idleTimeout))}function Z(){!a||a.completed||(a.timer&&(clearTimeout(a.timer),a.timer=null),a.completed=!0,a.lastError?a.flow.fail(a.lastError):a.flow.success(),a=null)}function Te(e){return e!==null&&typeof e=="object"&&("flow"in e||"tags"in e)}function v(e,t,r,n){let i,s;t===void 0?(i=void 0,s=void 0):Te(t)?r===void 0?(i=void 0,s=t):(i=void 0,s={...t,...r}):(i=t,s=r);let o=s?.flow,c=Se(o);if(s?.tags)for(let $ of s.tags)c.tag($);let _=n&&n!=="info"?`${e} [${n}]`:e,p=c.step(_,i);n==="error"?(p.fail(i),a.lastError=i,c.tag("error")):(p.success(),n&&n!=="info"&&c.tag(n)),ke()}var ye=(e,t,r)=>v(e,t,r),d=ye;d.info=(e,t,r)=>v(e,t,r,"info");d.warn=(e,t,r)=>v(e,t,r,"warn");d.error=(e,t,r)=>v(e,t,r,"error");d.setIdleTimeout=e=>{w.idleTimeout=e};d.setFlowName=e=>{w.flowName=e};d.setDefaultTags=e=>{w.defaultTags=e};d.activeFlow=()=>a?.flow??null;d.flush=()=>{Z()};function Re(e){return typeof e=="object"&&e!==null&&"trace"in e&&typeof e.trace=="object"&&e.trace!==null}function M(e){let t=Re(e)?e.trace:e;return JSON.stringify({version:1,flow:{id:t.id,name:t.name,...t.parentId!==void 0&&{parentId:t.parentId},state:t.state,...t.status!==void 0&&{status:t.status},tags:t.tags,start:t.start,...t.end!==void 0&&{end:t.end},...t.error!==void 0&&{error:t.error},context:t.context,steps:t.steps.map(j),...t.meta!==void 0&&{meta:t.meta}}},null,2)}function j(e){let t={id:e.id,name:e.name,sequence:e.sequence,state:e.state,status:e.status,start:e.start};return e.end!==void 0&&(t.end=e.end),e.data!==void 0&&(t.data=u(e.data)),e.error!==void 0&&(t.error=e.error),e.children.length>0&&(t.children=e.children.map(j)),t}0&&(module.exports={NOOP_FLOW,NOOP_STEP,createFlow,getRenderer,isEnabled,log,normalizeError,safeSerialize,setClock,setEnabled,setIdGenerator,setRenderer,subscribe,toJSON});
package/dist/index.d.cts CHANGED
@@ -91,6 +91,24 @@ type FlowListener = (flow: Readonly<FlowTrace>) => void;
91
91
  */
92
92
  declare function subscribe(listener: FlowListener): () => void;
93
93
 
94
+ /**
95
+ * Normalizes any error input into a consistent NormalizedError shape.
96
+ *
97
+ * Rules:
98
+ * - Error instance → { name, message, stack }
99
+ * - String → { name: 'Error', message }
100
+ * - Other → { name: 'Error', message: String(input) }
101
+ * - undefined/no arg → { name: 'Error', message: 'Unknown error' }
102
+ */
103
+ declare function normalizeError(input: unknown): NormalizedError;
104
+
105
+ interface SerializeOptions {
106
+ maxDepth?: number;
107
+ maxLength?: number;
108
+ }
109
+ /** Safely serialize arbitrary data to JSON string. Never throws. */
110
+ declare function safeSerialize(data: unknown, options?: SerializeOptions): string;
111
+
94
112
  /**
95
113
  * NoOp StepHandle — reused across all disabled/guarded paths.
96
114
  * Type matches FlowHandle's StepHandle exactly.
@@ -151,6 +169,44 @@ declare function setClock(clock: Clock): void;
151
169
  */
152
170
  declare function createFlow<Data = unknown>(name: string, options?: FlowOptions): FlowHandle<Data>;
153
171
 
172
+ /**
173
+ * V3: Zero-Friction Log API
174
+ *
175
+ * Drop-in console.log replacement with auto-flow management.
176
+ *
177
+ * Usage:
178
+ * log('message')
179
+ * log('message', data)
180
+ * log('message', { tags: ['x'] })
181
+ * log('message', data, { tags: ['x'], flow: 'custom' })
182
+ * log.warn('warning', data)
183
+ * log.error('error', error)
184
+ */
185
+
186
+ /** Options for individual log calls */
187
+ interface LogCallOptions {
188
+ /** Override the active flow name */
189
+ flow?: string;
190
+ /** Additional tags for this step */
191
+ tags?: string[];
192
+ }
193
+ /** Public Log API */
194
+ interface LogAPI {
195
+ (message: string, data?: unknown): void;
196
+ (message: string, options?: LogCallOptions): void;
197
+ (message: string, data?: unknown, options?: LogCallOptions): void;
198
+ info: LogFn;
199
+ warn: LogFn;
200
+ error: LogFn;
201
+ setIdleTimeout(ms: number): void;
202
+ setFlowName(name: string): void;
203
+ setDefaultTags(tags: string[]): void;
204
+ activeFlow(): FlowHandle | null;
205
+ flush(): void;
206
+ }
207
+ type LogFn = (message: string, dataOrOptions?: unknown, options?: LogCallOptions) => void;
208
+ declare const log: LogAPI;
209
+
154
210
  /** Contract for all renderer implementations */
155
211
  interface FlowRenderer {
156
212
  /** Render a frozen snapshot of a completed flow */
@@ -177,4 +233,4 @@ declare function toJSON(input: Readonly<FlowTrace> | {
177
233
  trace: Readonly<FlowTrace>;
178
234
  }): string;
179
235
 
180
- export { type Clock, type FlowOptions, type FlowRenderer, type FlowState, type FlowStatus, type FlowTrace, type IdGenerator, NOOP_FLOW, NOOP_STEP, type NormalizedError, type StepStatus, type StepTrace, createFlow, getRenderer, isEnabled, setClock, setEnabled, setIdGenerator, setRenderer, subscribe, toJSON };
236
+ export { type Clock, type FlowListener, type FlowOptions, type FlowRenderer, type FlowState, type FlowStatus, type FlowTrace, type IdGenerator, type LogAPI, type LogCallOptions, NOOP_FLOW, NOOP_STEP, type NoOpFlowHandle, type NoOpStepHandle, type NormalizedError, type SerializeOptions, type StepStatus, type StepTrace, createFlow, getRenderer, isEnabled, log, normalizeError, safeSerialize, setClock, setEnabled, setIdGenerator, setRenderer, subscribe, toJSON };
package/dist/index.d.ts CHANGED
@@ -91,6 +91,24 @@ type FlowListener = (flow: Readonly<FlowTrace>) => void;
91
91
  */
92
92
  declare function subscribe(listener: FlowListener): () => void;
93
93
 
94
+ /**
95
+ * Normalizes any error input into a consistent NormalizedError shape.
96
+ *
97
+ * Rules:
98
+ * - Error instance → { name, message, stack }
99
+ * - String → { name: 'Error', message }
100
+ * - Other → { name: 'Error', message: String(input) }
101
+ * - undefined/no arg → { name: 'Error', message: 'Unknown error' }
102
+ */
103
+ declare function normalizeError(input: unknown): NormalizedError;
104
+
105
+ interface SerializeOptions {
106
+ maxDepth?: number;
107
+ maxLength?: number;
108
+ }
109
+ /** Safely serialize arbitrary data to JSON string. Never throws. */
110
+ declare function safeSerialize(data: unknown, options?: SerializeOptions): string;
111
+
94
112
  /**
95
113
  * NoOp StepHandle — reused across all disabled/guarded paths.
96
114
  * Type matches FlowHandle's StepHandle exactly.
@@ -151,6 +169,44 @@ declare function setClock(clock: Clock): void;
151
169
  */
152
170
  declare function createFlow<Data = unknown>(name: string, options?: FlowOptions): FlowHandle<Data>;
153
171
 
172
+ /**
173
+ * V3: Zero-Friction Log API
174
+ *
175
+ * Drop-in console.log replacement with auto-flow management.
176
+ *
177
+ * Usage:
178
+ * log('message')
179
+ * log('message', data)
180
+ * log('message', { tags: ['x'] })
181
+ * log('message', data, { tags: ['x'], flow: 'custom' })
182
+ * log.warn('warning', data)
183
+ * log.error('error', error)
184
+ */
185
+
186
+ /** Options for individual log calls */
187
+ interface LogCallOptions {
188
+ /** Override the active flow name */
189
+ flow?: string;
190
+ /** Additional tags for this step */
191
+ tags?: string[];
192
+ }
193
+ /** Public Log API */
194
+ interface LogAPI {
195
+ (message: string, data?: unknown): void;
196
+ (message: string, options?: LogCallOptions): void;
197
+ (message: string, data?: unknown, options?: LogCallOptions): void;
198
+ info: LogFn;
199
+ warn: LogFn;
200
+ error: LogFn;
201
+ setIdleTimeout(ms: number): void;
202
+ setFlowName(name: string): void;
203
+ setDefaultTags(tags: string[]): void;
204
+ activeFlow(): FlowHandle | null;
205
+ flush(): void;
206
+ }
207
+ type LogFn = (message: string, dataOrOptions?: unknown, options?: LogCallOptions) => void;
208
+ declare const log: LogAPI;
209
+
154
210
  /** Contract for all renderer implementations */
155
211
  interface FlowRenderer {
156
212
  /** Render a frozen snapshot of a completed flow */
@@ -177,4 +233,4 @@ declare function toJSON(input: Readonly<FlowTrace> | {
177
233
  trace: Readonly<FlowTrace>;
178
234
  }): string;
179
235
 
180
- export { type Clock, type FlowOptions, type FlowRenderer, type FlowState, type FlowStatus, type FlowTrace, type IdGenerator, NOOP_FLOW, NOOP_STEP, type NormalizedError, type StepStatus, type StepTrace, createFlow, getRenderer, isEnabled, setClock, setEnabled, setIdGenerator, setRenderer, subscribe, toJSON };
236
+ export { type Clock, type FlowListener, type FlowOptions, type FlowRenderer, type FlowState, type FlowStatus, type FlowTrace, type IdGenerator, type LogAPI, type LogCallOptions, NOOP_FLOW, NOOP_STEP, type NoOpFlowHandle, type NoOpStepHandle, type NormalizedError, type SerializeOptions, type StepStatus, type StepTrace, createFlow, getRenderer, isEnabled, log, normalizeError, safeSerialize, setClock, setEnabled, setIdGenerator, setRenderer, subscribe, toJSON };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- function u(e){return e===void 0?{name:"Error",message:"Unknown error"}:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:typeof e=="string"?{name:"Error",message:e}:{name:"Error",message:String(e)}}var x=class{constructor(r,t){this._trace=r;this._clock=t;this._completed=!1}get isCompleted(){return this._completed}get trace(){return this._trace}success(){this._completed||(this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status="success")}fail(r){this._completed||(this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status="error",this._trace.error=u(r))}};var c=()=>{},d={success:c,fail:c},a={step:()=>d,child:()=>a,tag:c,tags:()=>[],setContext:c,getContext:()=>({}),success:c,fail:c,run:(e,r)=>r()};function b(e){let r=new WeakMap;function t(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(r.has(n))return r.get(n);if(Array.isArray(n)){let i=[];r.set(n,i);for(let o=0;o<n.length;o++)i.push(t(n[o]));return i}let s={};r.set(n,s);for(let i of Object.keys(n))s[i]=t(n[i]);return s}return t(e)}function h(e){if(e===null||typeof e!="object")return e;if(Object.freeze(e),Array.isArray(e))for(let r of e)h(r);else for(let r of Object.keys(e)){let t=e[r];t&&typeof t=="object"&&!Object.isFrozen(t)&&h(t)}return e}function R(e){let r=b(e);return h(r)}var _=new Set;function N(e){return _.add(e),()=>{_.delete(e)}}function q(e){if(_.size!==0)for(let r of _)try{r(e)}catch{}}var S=class e{constructor(r,t,n,s,i){this._trace=r;this._clock=t;this._idGen=n;this._renderer=s;this._options=i;this._completed=!1;this._sequence=0}get isCompleted(){return this._completed}get trace(){return this._trace}step(r,t){if(this._completed)return d;let n=this._options.maxSteps;if(n!==void 0&&this._trace.steps.length>=n)return this._trace.meta===void 0?this._trace.meta={maxStepsExceeded:!0}:this._trace.meta.maxStepsExceeded=!0,d;let s={id:this._idGen.generate(),name:r,sequence:this._sequence++,state:"running",status:"pending",start:this._clock.now(),data:t,children:[]};return this._trace.steps.push(s),new x(s,this._clock)}child(r){if(this._completed)return a;if(this._options.enabled===!1)return a;let t={id:this._idGen.generate(),name:r,parentId:this._trace.id,state:"running",status:void 0,tags:[],start:this._clock.now(),context:{...this._trace.context},steps:[]};return new e(t,this._clock,this._idGen,this._renderer,{...this._options})}tag(r){this._completed||this._trace.tags.includes(r)||this._trace.tags.push(r)}tags(){return[...this._trace.tags]}setContext(r){this._completed||Object.assign(this._trace.context,r)}getContext(){return{...this._trace.context}}success(){this._finalize("success")}fail(r){this._trace.error=u(r),this._finalize("error")}run(r,t){if(this._completed)return Promise.resolve(t());let n=this.step(r);return Promise.resolve(t()).then(s=>(n.success(),s),s=>{throw n.fail(s),s})}_finalize(r){if(this._completed)return;this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status=r;let t=R(this._trace);q(t),this._renderer.render(t)}};var f=class{generate(){return Math.random().toString(36).slice(2,10)}};var p=class{now(){return Date.now()}};function m(e,r){let t=r?.maxDepth??2,n=r?.maxLength??80,s=new WeakSet;function i(o,l){if(typeof o=="function")return`[Fn:${o.name||"?"}]`;if(typeof o=="symbol")return o.toString();if(l>t)return o&&typeof o=="object"?"[...]":o;if(o===null||typeof o!="object")return o;if(o instanceof Map)return`{Map(${o.size})}`;if(o instanceof Set)return`{Set(${o.size})}`;if(o instanceof Date)return o.toISOString();if(o instanceof RegExp)return o.toString();if(s.has(o))return"[Circular]";if(s.add(o),Array.isArray(o))return o.map(g=>i(g,l+1));let E={};for(let g of Object.keys(o)){let W=o[g];E[g]=i(W,l+1)}return E}try{let o=JSON.stringify(i(e,0));return o&&o.length>n?o.slice(0,n)+"\u2026":o}catch{return"[Unserializable]"}}var J=()=>typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0,U=()=>typeof EdgeRuntime<"u",Y=()=>typeof caches<"u"&&"default"in caches,B=()=>typeof window<"u"||typeof self<"u";function z(){return J()?"node":U()||Y()?"edge":B()?"browser":"node"}var K="\x1B[0m",Q="\x1B[32m",V="\x1B[31m";var X="\x1B[36m";var Z="\x1B[2m";function j(){return!(z()==="browser"||typeof process<"u"&&process.env?.NO_COLOR)}var ee=j();function k(e,r){return ee?`${r}${e}${K}`:e}function y(e){return k(e,Q)}function F(e){return k(e,V)}function P(e){return k(e,X)}function T(e){return k(e,Z)}function H(e,r){if(r===void 0)return"\u2014";let t=Math.round(r-e);return t>=1e3?`${(t/1e3).toFixed(1)}s`:`${t}ms`}function D(e,r,t){let n=" ".repeat(r);t.push(`${n}${P("\u2192")} ${e.name}`),e.data!==void 0&&t.push(`${n} ${T("data:")} ${m(e.data,{maxLength:80})}`);let s=H(e.start,e.end);e.status==="success"?t.push(`${n}${y("\u2713")} ${e.name} (${s})`):e.status==="error"?t.push(`${n}${F("\u2717")} ${e.name} (error: ${e.error?.message??"Unknown error"})`):t.push(`${n} ${e.name} (${s})`);for(let i of e.children)D(i,r+1,t)}var w=class{render(r){let t=[],n=r.tags.length>0?` [${r.tags.join(", ")}]`:"",s=r.status==="error"?"\u{1F525}":"\u{1F680}";t.push(`${s} [flow:${r.name}]${n} (${T("tid:")} ${r.id})`);for(let l of r.steps)D(l,1,t);let i=H(r.start,r.end),o=r.meta?.maxStepsExceeded?` ${F("\u26A0\uFE0F maxSteps exceeded")}`:"";r.status==="error"?(t.push(`\u{1F3C1} [flow:${r.name}] ${F("failed")} (${i}, error: ${r.error?.message??"Unknown error"})${o}`),console.error(t.join(`
2
- `))):(t.push(`\u{1F3C1} [flow:${r.name}] ${y("success")} (${i})${o}`),console.log(t.join(`
3
- `)))}};var O=null;function G(e){O=e}function I(){return O}function L(e){return O??e}var C=new f,$=new p,ne=new w,v=!0;function oe(e){v=e}function se(){return v}function ie(e){C=e}function ae(e){$=e}function ce(e,r){if(!v)return a;let t=r?.sample??1;if(t<1&&Math.random()>t)return a;if(r?.enabled===!1)return a;let n=L(ne),s={id:C.generate(),name:e,state:"running",tags:r?.tags??[],start:$.now(),context:r?.initialContext?{...r.initialContext}:{},steps:[]};return new S(s,$,C,n,r??{})}function de(e){return typeof e=="object"&&e!==null&&"trace"in e&&typeof e.trace=="object"&&e.trace!==null}function A(e){let r=de(e)?e.trace:e;return JSON.stringify({version:1,flow:{id:r.id,name:r.name,...r.parentId!==void 0&&{parentId:r.parentId},state:r.state,...r.status!==void 0&&{status:r.status},tags:r.tags,start:r.start,...r.end!==void 0&&{end:r.end},...r.error!==void 0&&{error:r.error},context:r.context,steps:r.steps.map(M),...r.meta!==void 0&&{meta:r.meta}}},null,2)}function M(e){let r={id:e.id,name:e.name,sequence:e.sequence,state:e.state,status:e.status,start:e.start};return e.end!==void 0&&(r.end=e.end),e.data!==void 0&&(r.data=m(e.data)),e.error!==void 0&&(r.error=e.error),e.children.length>0&&(r.children=e.children.map(M)),r}export{a as NOOP_FLOW,d as NOOP_STEP,ce as createFlow,I as getRenderer,se as isEnabled,ae as setClock,oe as setEnabled,ie as setIdGenerator,G as setRenderer,N as subscribe,A as toJSON};
1
+ function u(e){return e===void 0?{name:"Error",message:"Unknown error"}:e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:typeof e=="string"?{name:"Error",message:e}:{name:"Error",message:String(e)}}var S=class{constructor(t,r){this._trace=t;this._clock=r;this._completed=!1}get isCompleted(){return this._completed}get trace(){return this._trace}success(){this._completed||(this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status="success")}fail(t){this._completed||(this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status="error",this._trace.error=u(t))}};var m=()=>{},g={success:m,fail:m},c={step:()=>g,child:()=>c,tag:m,tags:()=>[],setContext:m,getContext:()=>({}),success:m,fail:m,run:(e,t)=>{try{let r=t();return r instanceof Promise?r:Promise.resolve(r)}catch(r){return Promise.reject(r)}}};function P(e){let t=new WeakMap;function r(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(t.has(n))return t.get(n);if(Array.isArray(n)){let s=[];t.set(n,s);for(let o=0;o<n.length;o++)s.push(r(n[o]));return s}let i={};t.set(n,i);for(let s of Object.keys(n))i[s]=r(n[s]);return i}return r(e)}function k(e){if(e===null||typeof e!="object")return e;if(Object.freeze(e),Array.isArray(e))for(let t of e)k(t);else for(let t of Object.keys(e)){let r=e[t];r&&typeof r=="object"&&!Object.isFrozen(r)&&k(r)}return e}function $(e){let t=P(e);return k(t)}var T=new Set;function D(e){return T.add(e),()=>{T.delete(e)}}function Q(e){if(T.size!==0)for(let t of T)try{t(e)}catch{}}var y=class e{constructor(t,r,n,i,s){this._trace=t;this._clock=r;this._idGen=n;this._renderer=i;this._options=s;this._completed=!1;this._sequence=0}get isCompleted(){return this._completed}get trace(){return this._trace}step(t,r){if(this._completed)return g;let n=this._options.maxSteps;if(n!==void 0&&this._trace.steps.length>=n)return this._trace.meta===void 0?this._trace.meta={maxStepsExceeded:!0}:this._trace.meta.maxStepsExceeded=!0,g;let i={id:this._idGen.generate(),name:t,sequence:this._sequence++,state:"running",status:"pending",start:this._clock.now(),data:r,children:[]};return this._trace.steps.push(i),new S(i,this._clock)}child(t){if(this._completed)return c;if(this._options.enabled===!1)return c;let r={id:this._idGen.generate(),name:t,parentId:this._trace.id,state:"running",status:void 0,tags:[],start:this._clock.now(),context:{...this._trace.context},steps:[]};return new e(r,this._clock,this._idGen,this._renderer,{...this._options})}tag(t){this._completed||this._trace.tags.includes(t)||this._trace.tags.push(t)}tags(){return[...this._trace.tags]}setContext(t){this._completed||Object.assign(this._trace.context,t)}getContext(){return{...this._trace.context}}success(){this._finalize("success")}fail(t){this._trace.error=u(t),this._finalize("error")}run(t,r){if(this._completed)return Promise.resolve(r());let n=this.step(t);return Promise.resolve(r()).then(i=>(n.success(),i),i=>{throw n.fail(i),i})}_finalize(t){if(this._completed)return;this._completed=!0,this._trace.end=this._clock.now(),this._trace.state="completed",this._trace.status=t;let r=$(this._trace);Q(r),this._renderer.render(r)}};var x=class{generate(){return Math.random().toString(36).slice(2,10)}};var h=class{now(){return Date.now()}};function p(e,t){let r=t?.maxDepth??2,n=t?.maxLength??80,i=new WeakSet;function s(o,l){if(typeof o=="function")return`[Fn:${o.name||"?"}]`;if(typeof o=="symbol")return o.toString();if(l>r)return o&&typeof o=="object"?"[...]":o;if(o===null||typeof o!="object")return o;if(o instanceof Map)return`{Map(${o.size})}`;if(o instanceof Set)return`{Set(${o.size})}`;if(o instanceof Date)return o.toISOString();if(o instanceof RegExp)return o.toString();if(i.has(o))return"[Circular]";if(i.add(o),Array.isArray(o))return o.map(f=>s(f,l+1));let _={};for(let f of Object.keys(o)){let v=o[f];_[f]=s(v,l+1)}return _}try{let o=JSON.stringify(s(e,0));return o&&o.length>n?o.slice(0,n)+"\u2026":o}catch{return"[Unserializable]"}}var V=()=>typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0,X=()=>typeof EdgeRuntime<"u",Z=()=>typeof caches<"u"&&"default"in caches,j=()=>typeof window<"u"||typeof self<"u";function G(){return V()?"node":X()||Z()?"edge":j()?"browser":"node"}var ee="\x1B[0m",te="\x1B[32m",re="\x1B[31m";var ne="\x1B[36m";var oe="\x1B[2m";function ie(){return!(G()==="browser"||typeof process<"u"&&process.env?.NO_COLOR)}var se=ie();function R(e,t){return se?`${t}${e}${ee}`:e}function E(e){return R(e,te)}function O(e){return R(e,re)}function A(e){return R(e,ne)}function N(e){return R(e,oe)}function M(e,t){if(t===void 0)return"\u2014";let r=Math.round(t-e);return r>=1e3?`${(r/1e3).toFixed(1)}s`:`${r}ms`}function W(e,t,r){let n=" ".repeat(t);r.push(`${n}${A("\u2192")} ${e.name}`),e.data!==void 0&&r.push(`${n} ${N("data:")} ${p(e.data,{maxLength:80})}`);let i=M(e.start,e.end);e.status==="success"?r.push(`${n}${E("\u2713")} ${e.name} (${i})`):e.status==="error"?r.push(`${n}${O("\u2717")} ${e.name} (error: ${e.error?.message??"Unknown error"})`):r.push(`${n} ${e.name} (${i})`);for(let s of e.children)W(s,t+1,r)}var F=class{constructor(){this.name="console"}render(t){let r=[],n=t.tags.length>0?` [${t.tags.join(", ")}]`:"",i=t.status==="error"?"\u{1F525}":"\u{1F680}";r.push(`${i} [flow:${t.name}]${n} (${N("tid:")} ${t.id})`);for(let l of t.steps)W(l,1,r);let s=M(t.start,t.end),o=t.meta?.maxStepsExceeded?` ${O("\u26A0\uFE0F maxSteps exceeded")}`:"";t.status==="error"?(r.push(`\u{1F3C1} [flow:${t.name}] ${O("failed")} (${s}, error: ${t.error?.message??"Unknown error"})${o}`),console.error(r.join(`
2
+ `))):(r.push(`\u{1F3C1} [flow:${t.name}] ${E("success")} (${s})${o}`),console.log(r.join(`
3
+ `)))}};var L=null;function q(e){L=e}function J(){return L}function U(e){return L??e}var b=new x,z=new h,ce=new F,H=!0;function de(e){H=e}function fe(){return H}function ue(e){b=e}function pe(e){z=e}function I(e,t){if(!H)return c;let r=t?.sample??1;if(r<1&&Math.random()>r)return c;if(t?.enabled===!1)return c;let n=U(ce),i={id:b.generate(),name:e,state:"running",tags:t?.tags??[],start:z.now(),context:t?.initialContext?{...t.initialContext}:{},steps:[]};return new y(i,z,b,n,t??{})}var w={idleTimeout:100,flowName:"default",defaultTags:[]},a=null;function me(e){if(a&&e===void 0&&!a.completed)return a.flow;let t=e??w.flowName,r=I(t,{tags:[...w.defaultTags]});return a={flow:r,timer:null,lastError:null,completed:!1},r}function ge(){a&&(a.timer&&clearTimeout(a.timer),a.timer=setTimeout(()=>{B()},w.idleTimeout))}function B(){!a||a.completed||(a.timer&&(clearTimeout(a.timer),a.timer=null),a.completed=!0,a.lastError?a.flow.fail(a.lastError):a.flow.success(),a=null)}function we(e){return e!==null&&typeof e=="object"&&("flow"in e||"tags"in e)}function C(e,t,r,n){let i,s;t===void 0?(i=void 0,s=void 0):we(t)?r===void 0?(i=void 0,s=t):(i=void 0,s={...t,...r}):(i=t,s=r);let o=s?.flow,l=me(o);if(s?.tags)for(let v of s.tags)l.tag(v);let _=n&&n!=="info"?`${e} [${n}]`:e,f=l.step(_,i);n==="error"?(f.fail(i),a.lastError=i,l.tag("error")):(f.success(),n&&n!=="info"&&l.tag(n)),ge()}var xe=(e,t,r)=>C(e,t,r),d=xe;d.info=(e,t,r)=>C(e,t,r,"info");d.warn=(e,t,r)=>C(e,t,r,"warn");d.error=(e,t,r)=>C(e,t,r,"error");d.setIdleTimeout=e=>{w.idleTimeout=e};d.setFlowName=e=>{w.flowName=e};d.setDefaultTags=e=>{w.defaultTags=e};d.activeFlow=()=>a?.flow??null;d.flush=()=>{B()};function he(e){return typeof e=="object"&&e!==null&&"trace"in e&&typeof e.trace=="object"&&e.trace!==null}function Y(e){let t=he(e)?e.trace:e;return JSON.stringify({version:1,flow:{id:t.id,name:t.name,...t.parentId!==void 0&&{parentId:t.parentId},state:t.state,...t.status!==void 0&&{status:t.status},tags:t.tags,start:t.start,...t.end!==void 0&&{end:t.end},...t.error!==void 0&&{error:t.error},context:t.context,steps:t.steps.map(K),...t.meta!==void 0&&{meta:t.meta}}},null,2)}function K(e){let t={id:e.id,name:e.name,sequence:e.sequence,state:e.state,status:e.status,start:e.start};return e.end!==void 0&&(t.end=e.end),e.data!==void 0&&(t.data=p(e.data)),e.error!==void 0&&(t.error=e.error),e.children.length>0&&(t.children=e.children.map(K)),t}export{c as NOOP_FLOW,g as NOOP_STEP,I as createFlow,J as getRenderer,fe as isEnabled,d as log,u as normalizeError,p as safeSerialize,pe as setClock,de as setEnabled,ue as setIdGenerator,q as setRenderer,D as subscribe,Y as toJSON};
package/package.json CHANGED
@@ -1,6 +1,5 @@
1
1
  {
2
2
  "name": "@better-logger/core",
3
- "version": "0.2.0",
4
3
  "description": "Execution flow debugger for modern apps. Zero deps. Works everywhere. <10KB.",
5
4
  "license": "MIT",
6
5
  "repository": {
@@ -52,5 +51,6 @@
52
51
  "@typescript-eslint/parser": "8.58.0",
53
52
  "@typescript-eslint/eslint-plugin": "8.58.0",
54
53
  "@types/node": "20.11.0"
55
- }
54
+ },
55
+ "version": "0.4.0"
56
56
  }