@better-logger/core 0.1.0 → 0.3.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 +3 -3
- package/dist/index.d.cts +128 -5
- package/dist/index.d.ts +128 -5
- package/dist/index.js +3 -3
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`))):(r.push(`\u{1F3C1} [flow:${t.name}] ${
|
|
3
|
-
`)))}};var
|
|
1
|
+
"use strict";var $=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,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,i,{get:()=>t[i],enumerable:!(n=ee(t,i))||n.enumerable});return e};var ie=e=>oe($({},"__esModule",{value:!0}),e);var Ce={};ne(Ce,{NOOP_FLOW:()=>l,NOOP_STEP:()=>u,createFlow:()=>v,getRenderer:()=>P,isEnabled:()=>K,log:()=>c,setClock:()=>V,setEnabled:()=>Y,setIdGenerator:()=>Q,setRenderer:()=>H,subscribe:()=>b,toJSON:()=>G});module.exports=ie(Ce);function w(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 k=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=w(t))}};var m=()=>{},u={success:m,fail:m},l={step:()=>u,child:()=>l,tag:m,tags:()=>[],setContext:m,getContext:()=>({}),success:m,fail:m,run:(e,t)=>t()};function M(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 a=[];t.set(n,a);for(let o=0;o<n.length;o++)a.push(r(n[o]));return a}let i={};t.set(n,i);for(let a of Object.keys(n))i[a]=r(n[a]);return i}return r(e)}function S(e){if(e===null||typeof e!="object")return e;if(Object.freeze(e),Array.isArray(e))for(let t of e)S(t);else for(let t of Object.keys(e)){let r=e[t];r&&typeof r=="object"&&!Object.isFrozen(r)&&S(r)}return e}function E(e){let t=M(e);return S(t)}var T=new Set;function b(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,a){this._trace=t;this._clock=r;this._idGen=n;this._renderer=i;this._options=a;this._completed=!1;this._sequence=0}get isCompleted(){return this._completed}get trace(){return this._trace}step(t,r){if(this._completed)return u;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,u;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 k(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=w(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=E(this._trace);se(r),this._renderer.render(r)}};var x=class{generate(){return Math.random().toString(36).slice(2,10)}};var _=class{now(){return Date.now()}};function h(e,t){let r=t?.maxDepth??2,n=t?.maxLength??80,i=new WeakSet;function a(o,d){if(typeof o=="function")return`[Fn:${o.name||"?"}]`;if(typeof o=="symbol")return o.toString();if(d>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=>a(f,d+1));let g={};for(let f of Object.keys(o)){let j=o[f];g[f]=a(j,d+1)}return g}try{let o=JSON.stringify(a(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 W(){return ae()?"node":le()||ce()?"edge":de()?"browser":"node"}var ue="\x1B[0m",fe="\x1B[32m",me="\x1B[31m";var pe="\x1B[36m";var ge="\x1B[2m";function we(){return!(W()==="browser"||typeof process<"u"&&process.env?.NO_COLOR)}var xe=we();function R(e,t){return xe?`${t}${e}${ue}`:e}function L(e){return R(e,fe)}function C(e){return R(e,me)}function q(e){return R(e,pe)}function N(e){return R(e,ge)}function J(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 U(e,t,r){let n=" ".repeat(t);r.push(`${n}${q("\u2192")} ${e.name}`),e.data!==void 0&&r.push(`${n} ${N("data:")} ${h(e.data,{maxLength:80})}`);let i=J(e.start,e.end);e.status==="success"?r.push(`${n}${L("\u2713")} ${e.name} (${i})`):e.status==="error"?r.push(`${n}${C("\u2717")} ${e.name} (error: ${e.error?.message??"Unknown error"})`):r.push(`${n} ${e.name} (${i})`);for(let a of e.children)U(a,t+1,r)}var F=class{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 d of t.steps)U(d,1,r);let a=J(t.start,t.end),o=t.meta?.maxStepsExceeded?` ${C("\u26A0\uFE0F maxSteps exceeded")}`:"";t.status==="error"?(r.push(`\u{1F3C1} [flow:${t.name}] ${C("failed")} (${a}, error: ${t.error?.message??"Unknown error"})${o}`),console.error(r.join(`
|
|
2
|
+
`))):(r.push(`\u{1F3C1} [flow:${t.name}] ${L("success")} (${a})${o}`),console.log(r.join(`
|
|
3
|
+
`)))}};var I=null;function H(e){I=e}function P(){return I}function B(e){return I??e}var z=new x,A=new _,Fe=new F,D=!0;function Y(e){D=e}function K(){return D}function Q(e){z=e}function V(e){A=e}function v(e,t){if(!D)return l;let r=t?.sample??1;if(r<1&&Math.random()>r)return l;if(t?.enabled===!1)return l;let n=B(Fe),i={id:z.generate(),name:e,state:"running",tags:t?.tags??[],start:A.now(),context:t?.initialContext?{...t.initialContext}:{},steps:[]};return new y(i,A,z,n,t??{})}var p={idleTimeout:100,flowName:"default",defaultTags:[]},s=null;function ke(e){if(s&&e===void 0&&!s.completed)return s.flow;let t=e??p.flowName,r=v(t,{tags:[...p.defaultTags]});return s={flow:r,timer:null,lastError:null,completed:!1},r}function Se(){s&&(s.timer&&clearTimeout(s.timer),s.timer=setTimeout(()=>{X()},p.idleTimeout))}function X(){!s||s.completed||(s.timer&&(clearTimeout(s.timer),s.timer=null),s.completed=!0,s.lastError?s.flow.fail(s.lastError):s.flow.success(),s=null)}function Te(e,t,r){return t&&typeof t=="object"&&!Array.isArray(t)&&("flow"in t||"tags"in t)&&r===void 0?{callOptions:t}:t&&typeof t=="object"&&!Array.isArray(t)&&"tags"in t&&!("email"in t||"value"in t||"slow"in t||"message"in t)?{callOptions:t}:{data:t,callOptions:r}}function O(e,t,r,n){let{data:i,callOptions:a}=Te(e,t,r),o=a?.flow,d=ke(o);if(n&&n!=="info"&&d.tag(n),a?.tags)for(let f of a.tags)d.tag(f);let g=d.step(e,i);n==="error"?(g.fail(i),s.lastError=i):g.success(),Se()}var ye=(e,t,r)=>O(e,t,r),c=ye;c.info=(e,t,r)=>O(e,t,r,"info");c.warn=(e,t,r)=>O(e,t,r,"warn");c.error=(e,t,r)=>O(e,t,r,"error");c.setIdleTimeout=e=>{p.idleTimeout=e};c.setFlowName=e=>{p.flowName=e};c.setDefaultTags=e=>{p.defaultTags=e};c.activeFlow=()=>s?.flow??null;c.flush=()=>{X()};function Re(e){return typeof e=="object"&&e!==null&&"trace"in e&&typeof e.trace=="object"&&e.trace!==null}function G(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(Z),...t.meta!==void 0&&{meta:t.meta}}},null,2)}function Z(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=h(e.data)),e.error!==void 0&&(t.error=e.error),e.children.length>0&&(t.children=e.children.map(Z)),t}0&&(module.exports={NOOP_FLOW,NOOP_STEP,createFlow,getRenderer,isEnabled,log,setClock,setEnabled,setIdGenerator,setRenderer,subscribe,toJSON});
|
package/dist/index.d.cts
CHANGED
|
@@ -42,9 +42,26 @@ interface StepTrace {
|
|
|
42
42
|
}
|
|
43
43
|
/** Options for creating a flow */
|
|
44
44
|
interface FlowOptions {
|
|
45
|
+
/** Enable/disable this flow. Default: true. If false, all operations are no-ops */
|
|
45
46
|
enabled?: boolean;
|
|
47
|
+
/** Indexing labels for grouping/filtering */
|
|
46
48
|
tags?: string[];
|
|
49
|
+
/** Safety limit for step count (default: unlimited) */
|
|
47
50
|
maxSteps?: number;
|
|
51
|
+
/** Sampling rate (0.0 to 1.0). Default: 1.0 (all flows logged). V2 */
|
|
52
|
+
sample?: number;
|
|
53
|
+
/** Initial context to seed the flow with. V2 */
|
|
54
|
+
initialContext?: Record<string, unknown>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Contract for clock implementations */
|
|
58
|
+
interface Clock {
|
|
59
|
+
now(): number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Contract for ID generation strategies */
|
|
63
|
+
interface IdGenerator {
|
|
64
|
+
generate(): string;
|
|
48
65
|
}
|
|
49
66
|
|
|
50
67
|
/** Public StepHandle interface */
|
|
@@ -54,8 +71,8 @@ interface StepHandle {
|
|
|
54
71
|
}
|
|
55
72
|
|
|
56
73
|
/** Public FlowHandle interface */
|
|
57
|
-
interface FlowHandle {
|
|
58
|
-
step(name: string, data?:
|
|
74
|
+
interface FlowHandle<Data = unknown> {
|
|
75
|
+
step(name: string, data?: Data): StepHandle;
|
|
59
76
|
child(name: string): FlowHandle;
|
|
60
77
|
tag(tag: string): void;
|
|
61
78
|
tags(): string[];
|
|
@@ -63,6 +80,8 @@ interface FlowHandle {
|
|
|
63
80
|
getContext(): Record<string, unknown>;
|
|
64
81
|
success(): void;
|
|
65
82
|
fail(error?: unknown): void;
|
|
83
|
+
/** V2: Async boundary helper — creates a step, executes fn, auto-completes */
|
|
84
|
+
run<T>(name: string, fn: () => Promise<T> | T): Promise<T>;
|
|
66
85
|
}
|
|
67
86
|
/** Listener type for subscribe */
|
|
68
87
|
type FlowListener = (flow: Readonly<FlowTrace>) => void;
|
|
@@ -72,14 +91,118 @@ type FlowListener = (flow: Readonly<FlowTrace>) => void;
|
|
|
72
91
|
*/
|
|
73
92
|
declare function subscribe(listener: FlowListener): () => void;
|
|
74
93
|
|
|
94
|
+
/**
|
|
95
|
+
* NoOp StepHandle — reused across all disabled/guarded paths.
|
|
96
|
+
* Type matches FlowHandle's StepHandle exactly.
|
|
97
|
+
*/
|
|
98
|
+
interface NoOpStepHandle {
|
|
99
|
+
success(): void;
|
|
100
|
+
fail(error?: unknown): void;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* NoOp FlowHandle — reused across all disabled/guarded paths.
|
|
104
|
+
* Type signature matches FlowHandle interface exactly.
|
|
105
|
+
*/
|
|
106
|
+
interface NoOpFlowHandle {
|
|
107
|
+
step(name: string, data?: unknown): NoOpStepHandle;
|
|
108
|
+
child(name: string): NoOpFlowHandle;
|
|
109
|
+
tag(name: string): void;
|
|
110
|
+
tags(): string[];
|
|
111
|
+
setContext(context: Record<string, unknown>): void;
|
|
112
|
+
getContext(): Record<string, unknown>;
|
|
113
|
+
success(): void;
|
|
114
|
+
fail(error?: unknown): void;
|
|
115
|
+
run<T>(name: string, fn: () => Promise<T>): Promise<T>;
|
|
116
|
+
}
|
|
117
|
+
declare const NOOP_STEP: NoOpStepHandle;
|
|
118
|
+
declare const NOOP_FLOW: NoOpFlowHandle;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Set the global enabled state for all new flows. V2 feature.
|
|
122
|
+
* Affects only flows created after this call — in-flight flows retain their state.
|
|
123
|
+
*
|
|
124
|
+
* @param enabled - true to enable, false to disable all new flows
|
|
125
|
+
*/
|
|
126
|
+
declare function setEnabled(enabled: boolean): void;
|
|
127
|
+
/**
|
|
128
|
+
* Get the current global enabled state. V2 feature.
|
|
129
|
+
*/
|
|
130
|
+
declare function isEnabled(): boolean;
|
|
131
|
+
/**
|
|
132
|
+
* Override the default ID generator. V2 feature.
|
|
133
|
+
* Affects only flows created after this call.
|
|
134
|
+
*
|
|
135
|
+
* @param idGen - The ID generator to use
|
|
136
|
+
*/
|
|
137
|
+
declare function setIdGenerator(idGen: IdGenerator): void;
|
|
138
|
+
/**
|
|
139
|
+
* Override the default clock. V2 feature.
|
|
140
|
+
* Affects only flows created after this call.
|
|
141
|
+
*
|
|
142
|
+
* @param clock - The clock to use
|
|
143
|
+
*/
|
|
144
|
+
declare function setClock(clock: Clock): void;
|
|
75
145
|
/**
|
|
76
146
|
* Create a new execution flow with a human-readable name and optional configuration.
|
|
77
147
|
*
|
|
78
148
|
* @param name - Human-readable flow name
|
|
79
|
-
* @param options - Optional configuration (enabled, tags, maxSteps)
|
|
149
|
+
* @param options - Optional configuration (enabled, tags, maxSteps, sample, initialContext)
|
|
80
150
|
* @returns FlowHandle for interacting with the flow
|
|
81
151
|
*/
|
|
82
|
-
declare function createFlow(name: string, options?: FlowOptions): FlowHandle
|
|
152
|
+
declare function createFlow<Data = unknown>(name: string, options?: FlowOptions): FlowHandle<Data>;
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* V3: Zero-Friction Log API
|
|
156
|
+
*
|
|
157
|
+
* Drop-in console.log replacement with auto-flow management.
|
|
158
|
+
*
|
|
159
|
+
* Usage:
|
|
160
|
+
* log('message')
|
|
161
|
+
* log('message', { data: 'value' })
|
|
162
|
+
* log.warn('warning', data)
|
|
163
|
+
* log.error('error', error)
|
|
164
|
+
*/
|
|
165
|
+
|
|
166
|
+
/** Options for individual log calls */
|
|
167
|
+
interface LogCallOptions {
|
|
168
|
+
/** Override the active flow name */
|
|
169
|
+
flow?: string;
|
|
170
|
+
/** Additional tags for this step */
|
|
171
|
+
tags?: string[];
|
|
172
|
+
}
|
|
173
|
+
/** Public Log API */
|
|
174
|
+
interface LogAPI {
|
|
175
|
+
(message: string, data?: unknown): void;
|
|
176
|
+
(message: string, options?: LogCallOptions): void;
|
|
177
|
+
(message: string, data?: unknown, options?: LogCallOptions): void;
|
|
178
|
+
info: LogFn;
|
|
179
|
+
warn: LogFn;
|
|
180
|
+
error: LogFn;
|
|
181
|
+
setIdleTimeout(ms: number): void;
|
|
182
|
+
setFlowName(name: string): void;
|
|
183
|
+
setDefaultTags(tags: string[]): void;
|
|
184
|
+
activeFlow(): FlowHandle | null;
|
|
185
|
+
flush(): void;
|
|
186
|
+
}
|
|
187
|
+
type LogFn = (message: string, dataOrOptions?: unknown, options?: LogCallOptions) => void;
|
|
188
|
+
declare const log: LogAPI;
|
|
189
|
+
|
|
190
|
+
/** Contract for all renderer implementations */
|
|
191
|
+
interface FlowRenderer {
|
|
192
|
+
/** Render a frozen snapshot of a completed flow */
|
|
193
|
+
render(snapshot: Readonly<FlowTrace>): void;
|
|
194
|
+
/** Optional name for debugging/identification — V2 */
|
|
195
|
+
name?: string;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Set the global renderer. V2 feature.
|
|
199
|
+
* @param renderer - The renderer to use for all new flows
|
|
200
|
+
*/
|
|
201
|
+
declare function setRenderer(renderer: FlowRenderer): void;
|
|
202
|
+
/**
|
|
203
|
+
* Get the current global renderer, or null if none set. V2 feature.
|
|
204
|
+
*/
|
|
205
|
+
declare function getRenderer(): FlowRenderer | null;
|
|
83
206
|
|
|
84
207
|
/**
|
|
85
208
|
* Serialize a FlowTrace to versioned JSON string.
|
|
@@ -90,4 +213,4 @@ declare function toJSON(input: Readonly<FlowTrace> | {
|
|
|
90
213
|
trace: Readonly<FlowTrace>;
|
|
91
214
|
}): string;
|
|
92
215
|
|
|
93
|
-
export { type FlowOptions, type FlowState, type FlowStatus, type FlowTrace, type NormalizedError, type StepStatus, type StepTrace, createFlow, subscribe, toJSON };
|
|
216
|
+
export { type Clock, type FlowOptions, type FlowRenderer, type FlowState, type FlowStatus, type FlowTrace, type IdGenerator, type LogAPI, type LogCallOptions, NOOP_FLOW, NOOP_STEP, type NormalizedError, type StepStatus, type StepTrace, createFlow, getRenderer, isEnabled, log, setClock, setEnabled, setIdGenerator, setRenderer, subscribe, toJSON };
|
package/dist/index.d.ts
CHANGED
|
@@ -42,9 +42,26 @@ interface StepTrace {
|
|
|
42
42
|
}
|
|
43
43
|
/** Options for creating a flow */
|
|
44
44
|
interface FlowOptions {
|
|
45
|
+
/** Enable/disable this flow. Default: true. If false, all operations are no-ops */
|
|
45
46
|
enabled?: boolean;
|
|
47
|
+
/** Indexing labels for grouping/filtering */
|
|
46
48
|
tags?: string[];
|
|
49
|
+
/** Safety limit for step count (default: unlimited) */
|
|
47
50
|
maxSteps?: number;
|
|
51
|
+
/** Sampling rate (0.0 to 1.0). Default: 1.0 (all flows logged). V2 */
|
|
52
|
+
sample?: number;
|
|
53
|
+
/** Initial context to seed the flow with. V2 */
|
|
54
|
+
initialContext?: Record<string, unknown>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Contract for clock implementations */
|
|
58
|
+
interface Clock {
|
|
59
|
+
now(): number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Contract for ID generation strategies */
|
|
63
|
+
interface IdGenerator {
|
|
64
|
+
generate(): string;
|
|
48
65
|
}
|
|
49
66
|
|
|
50
67
|
/** Public StepHandle interface */
|
|
@@ -54,8 +71,8 @@ interface StepHandle {
|
|
|
54
71
|
}
|
|
55
72
|
|
|
56
73
|
/** Public FlowHandle interface */
|
|
57
|
-
interface FlowHandle {
|
|
58
|
-
step(name: string, data?:
|
|
74
|
+
interface FlowHandle<Data = unknown> {
|
|
75
|
+
step(name: string, data?: Data): StepHandle;
|
|
59
76
|
child(name: string): FlowHandle;
|
|
60
77
|
tag(tag: string): void;
|
|
61
78
|
tags(): string[];
|
|
@@ -63,6 +80,8 @@ interface FlowHandle {
|
|
|
63
80
|
getContext(): Record<string, unknown>;
|
|
64
81
|
success(): void;
|
|
65
82
|
fail(error?: unknown): void;
|
|
83
|
+
/** V2: Async boundary helper — creates a step, executes fn, auto-completes */
|
|
84
|
+
run<T>(name: string, fn: () => Promise<T> | T): Promise<T>;
|
|
66
85
|
}
|
|
67
86
|
/** Listener type for subscribe */
|
|
68
87
|
type FlowListener = (flow: Readonly<FlowTrace>) => void;
|
|
@@ -72,14 +91,118 @@ type FlowListener = (flow: Readonly<FlowTrace>) => void;
|
|
|
72
91
|
*/
|
|
73
92
|
declare function subscribe(listener: FlowListener): () => void;
|
|
74
93
|
|
|
94
|
+
/**
|
|
95
|
+
* NoOp StepHandle — reused across all disabled/guarded paths.
|
|
96
|
+
* Type matches FlowHandle's StepHandle exactly.
|
|
97
|
+
*/
|
|
98
|
+
interface NoOpStepHandle {
|
|
99
|
+
success(): void;
|
|
100
|
+
fail(error?: unknown): void;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* NoOp FlowHandle — reused across all disabled/guarded paths.
|
|
104
|
+
* Type signature matches FlowHandle interface exactly.
|
|
105
|
+
*/
|
|
106
|
+
interface NoOpFlowHandle {
|
|
107
|
+
step(name: string, data?: unknown): NoOpStepHandle;
|
|
108
|
+
child(name: string): NoOpFlowHandle;
|
|
109
|
+
tag(name: string): void;
|
|
110
|
+
tags(): string[];
|
|
111
|
+
setContext(context: Record<string, unknown>): void;
|
|
112
|
+
getContext(): Record<string, unknown>;
|
|
113
|
+
success(): void;
|
|
114
|
+
fail(error?: unknown): void;
|
|
115
|
+
run<T>(name: string, fn: () => Promise<T>): Promise<T>;
|
|
116
|
+
}
|
|
117
|
+
declare const NOOP_STEP: NoOpStepHandle;
|
|
118
|
+
declare const NOOP_FLOW: NoOpFlowHandle;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Set the global enabled state for all new flows. V2 feature.
|
|
122
|
+
* Affects only flows created after this call — in-flight flows retain their state.
|
|
123
|
+
*
|
|
124
|
+
* @param enabled - true to enable, false to disable all new flows
|
|
125
|
+
*/
|
|
126
|
+
declare function setEnabled(enabled: boolean): void;
|
|
127
|
+
/**
|
|
128
|
+
* Get the current global enabled state. V2 feature.
|
|
129
|
+
*/
|
|
130
|
+
declare function isEnabled(): boolean;
|
|
131
|
+
/**
|
|
132
|
+
* Override the default ID generator. V2 feature.
|
|
133
|
+
* Affects only flows created after this call.
|
|
134
|
+
*
|
|
135
|
+
* @param idGen - The ID generator to use
|
|
136
|
+
*/
|
|
137
|
+
declare function setIdGenerator(idGen: IdGenerator): void;
|
|
138
|
+
/**
|
|
139
|
+
* Override the default clock. V2 feature.
|
|
140
|
+
* Affects only flows created after this call.
|
|
141
|
+
*
|
|
142
|
+
* @param clock - The clock to use
|
|
143
|
+
*/
|
|
144
|
+
declare function setClock(clock: Clock): void;
|
|
75
145
|
/**
|
|
76
146
|
* Create a new execution flow with a human-readable name and optional configuration.
|
|
77
147
|
*
|
|
78
148
|
* @param name - Human-readable flow name
|
|
79
|
-
* @param options - Optional configuration (enabled, tags, maxSteps)
|
|
149
|
+
* @param options - Optional configuration (enabled, tags, maxSteps, sample, initialContext)
|
|
80
150
|
* @returns FlowHandle for interacting with the flow
|
|
81
151
|
*/
|
|
82
|
-
declare function createFlow(name: string, options?: FlowOptions): FlowHandle
|
|
152
|
+
declare function createFlow<Data = unknown>(name: string, options?: FlowOptions): FlowHandle<Data>;
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* V3: Zero-Friction Log API
|
|
156
|
+
*
|
|
157
|
+
* Drop-in console.log replacement with auto-flow management.
|
|
158
|
+
*
|
|
159
|
+
* Usage:
|
|
160
|
+
* log('message')
|
|
161
|
+
* log('message', { data: 'value' })
|
|
162
|
+
* log.warn('warning', data)
|
|
163
|
+
* log.error('error', error)
|
|
164
|
+
*/
|
|
165
|
+
|
|
166
|
+
/** Options for individual log calls */
|
|
167
|
+
interface LogCallOptions {
|
|
168
|
+
/** Override the active flow name */
|
|
169
|
+
flow?: string;
|
|
170
|
+
/** Additional tags for this step */
|
|
171
|
+
tags?: string[];
|
|
172
|
+
}
|
|
173
|
+
/** Public Log API */
|
|
174
|
+
interface LogAPI {
|
|
175
|
+
(message: string, data?: unknown): void;
|
|
176
|
+
(message: string, options?: LogCallOptions): void;
|
|
177
|
+
(message: string, data?: unknown, options?: LogCallOptions): void;
|
|
178
|
+
info: LogFn;
|
|
179
|
+
warn: LogFn;
|
|
180
|
+
error: LogFn;
|
|
181
|
+
setIdleTimeout(ms: number): void;
|
|
182
|
+
setFlowName(name: string): void;
|
|
183
|
+
setDefaultTags(tags: string[]): void;
|
|
184
|
+
activeFlow(): FlowHandle | null;
|
|
185
|
+
flush(): void;
|
|
186
|
+
}
|
|
187
|
+
type LogFn = (message: string, dataOrOptions?: unknown, options?: LogCallOptions) => void;
|
|
188
|
+
declare const log: LogAPI;
|
|
189
|
+
|
|
190
|
+
/** Contract for all renderer implementations */
|
|
191
|
+
interface FlowRenderer {
|
|
192
|
+
/** Render a frozen snapshot of a completed flow */
|
|
193
|
+
render(snapshot: Readonly<FlowTrace>): void;
|
|
194
|
+
/** Optional name for debugging/identification — V2 */
|
|
195
|
+
name?: string;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Set the global renderer. V2 feature.
|
|
199
|
+
* @param renderer - The renderer to use for all new flows
|
|
200
|
+
*/
|
|
201
|
+
declare function setRenderer(renderer: FlowRenderer): void;
|
|
202
|
+
/**
|
|
203
|
+
* Get the current global renderer, or null if none set. V2 feature.
|
|
204
|
+
*/
|
|
205
|
+
declare function getRenderer(): FlowRenderer | null;
|
|
83
206
|
|
|
84
207
|
/**
|
|
85
208
|
* Serialize a FlowTrace to versioned JSON string.
|
|
@@ -90,4 +213,4 @@ declare function toJSON(input: Readonly<FlowTrace> | {
|
|
|
90
213
|
trace: Readonly<FlowTrace>;
|
|
91
214
|
}): string;
|
|
92
215
|
|
|
93
|
-
export { type FlowOptions, type FlowState, type FlowStatus, type FlowTrace, type NormalizedError, type StepStatus, type StepTrace, createFlow, subscribe, toJSON };
|
|
216
|
+
export { type Clock, type FlowOptions, type FlowRenderer, type FlowState, type FlowStatus, type FlowTrace, type IdGenerator, type LogAPI, type LogCallOptions, NOOP_FLOW, NOOP_STEP, type NormalizedError, type StepStatus, type StepTrace, createFlow, getRenderer, isEnabled, log, setClock, setEnabled, setIdGenerator, setRenderer, subscribe, toJSON };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
function
|
|
2
|
-
`))):(r.push(`\u{1F3C1} [flow:${t.name}] ${
|
|
3
|
-
`)))}};var b=new
|
|
1
|
+
function w(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 k=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=w(t))}};var f=()=>{},m={success:f,fail:f},l={step:()=>m,child:()=>l,tag:f,tags:()=>[],setContext:f,getContext:()=>({}),success:f,fail:f,run:(e,t)=>t()};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 a=[];t.set(n,a);for(let o=0;o<n.length;o++)a.push(r(n[o]));return a}let i={};t.set(n,i);for(let a of Object.keys(n))i[a]=r(n[a]);return i}return r(e)}function S(e){if(e===null||typeof e!="object")return e;if(Object.freeze(e),Array.isArray(e))for(let t of e)S(t);else for(let t of Object.keys(e)){let r=e[t];r&&typeof r=="object"&&!Object.isFrozen(r)&&S(r)}return e}function O(e){let t=P(e);return S(t)}var T=new Set;function z(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,a){this._trace=t;this._clock=r;this._idGen=n;this._renderer=i;this._options=a;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 k(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=w(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=O(this._trace);Q(r),this._renderer.render(r)}};var x=class{generate(){return Math.random().toString(36).slice(2,10)}};var _=class{now(){return Date.now()}};function h(e,t){let r=t?.maxDepth??2,n=t?.maxLength??80,i=new WeakSet;function a(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(u=>a(u,c+1));let g={};for(let u of Object.keys(o)){let K=o[u];g[u]=a(K,c+1)}return g}try{let o=JSON.stringify(a(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 A(){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!(A()==="browser"||typeof process<"u"&&process.env?.NO_COLOR)}var se=ie();function R(e,t){return se?`${t}${e}${ee}`:e}function $(e){return R(e,te)}function C(e){return R(e,re)}function D(e){return R(e,ne)}function E(e){return R(e,oe)}function G(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 M(e,t,r){let n=" ".repeat(t);r.push(`${n}${D("\u2192")} ${e.name}`),e.data!==void 0&&r.push(`${n} ${E("data:")} ${h(e.data,{maxLength:80})}`);let i=G(e.start,e.end);e.status==="success"?r.push(`${n}${$("\u2713")} ${e.name} (${i})`):e.status==="error"?r.push(`${n}${C("\u2717")} ${e.name} (error: ${e.error?.message??"Unknown error"})`):r.push(`${n} ${e.name} (${i})`);for(let a of e.children)M(a,t+1,r)}var F=class{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} (${E("tid:")} ${t.id})`);for(let c of t.steps)M(c,1,r);let a=G(t.start,t.end),o=t.meta?.maxStepsExceeded?` ${C("\u26A0\uFE0F maxSteps exceeded")}`:"";t.status==="error"?(r.push(`\u{1F3C1} [flow:${t.name}] ${C("failed")} (${a}, error: ${t.error?.message??"Unknown error"})${o}`),console.error(r.join(`
|
|
2
|
+
`))):(r.push(`\u{1F3C1} [flow:${t.name}] ${$("success")} (${a})${o}`),console.log(r.join(`
|
|
3
|
+
`)))}};var b=null;function W(e){b=e}function q(){return b}function J(e){return b??e}var L=new x,N=new _,ce=new F,I=!0;function de(e){I=e}function ue(){return I}function fe(e){L=e}function me(e){N=e}function H(e,t){if(!I)return l;let r=t?.sample??1;if(r<1&&Math.random()>r)return l;if(t?.enabled===!1)return l;let n=J(ce),i={id:L.generate(),name:e,state:"running",tags:t?.tags??[],start:N.now(),context:t?.initialContext?{...t.initialContext}:{},steps:[]};return new y(i,N,L,n,t??{})}var p={idleTimeout:100,flowName:"default",defaultTags:[]},s=null;function pe(e){if(s&&e===void 0&&!s.completed)return s.flow;let t=e??p.flowName,r=H(t,{tags:[...p.defaultTags]});return s={flow:r,timer:null,lastError:null,completed:!1},r}function ge(){s&&(s.timer&&clearTimeout(s.timer),s.timer=setTimeout(()=>{U()},p.idleTimeout))}function U(){!s||s.completed||(s.timer&&(clearTimeout(s.timer),s.timer=null),s.completed=!0,s.lastError?s.flow.fail(s.lastError):s.flow.success(),s=null)}function we(e,t,r){return t&&typeof t=="object"&&!Array.isArray(t)&&("flow"in t||"tags"in t)&&r===void 0?{callOptions:t}:t&&typeof t=="object"&&!Array.isArray(t)&&"tags"in t&&!("email"in t||"value"in t||"slow"in t||"message"in t)?{callOptions:t}:{data:t,callOptions:r}}function v(e,t,r,n){let{data:i,callOptions:a}=we(e,t,r),o=a?.flow,c=pe(o);if(n&&n!=="info"&&c.tag(n),a?.tags)for(let u of a.tags)c.tag(u);let g=c.step(e,i);n==="error"?(g.fail(i),s.lastError=i):g.success(),ge()}var xe=(e,t,r)=>v(e,t,r),d=xe;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=>{p.idleTimeout=e};d.setFlowName=e=>{p.flowName=e};d.setDefaultTags=e=>{p.defaultTags=e};d.activeFlow=()=>s?.flow??null;d.flush=()=>{U()};function _e(e){return typeof e=="object"&&e!==null&&"trace"in e&&typeof e.trace=="object"&&e.trace!==null}function B(e){let t=_e(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(Y),...t.meta!==void 0&&{meta:t.meta}}},null,2)}function Y(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=h(e.data)),e.error!==void 0&&(t.error=e.error),e.children.length>0&&(t.children=e.children.map(Y)),t}export{l as NOOP_FLOW,m as NOOP_STEP,H as createFlow,q as getRenderer,ue as isEnabled,d as log,me as setClock,de as setEnabled,fe as setIdGenerator,W as setRenderer,z as subscribe,B as toJSON};
|
package/package.json
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@better-logger/core",
|
|
3
|
-
"version": "0.1.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.3.0"
|
|
56
56
|
}
|