@socketsecurity/lib 2.10.1 → 2.10.3
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/CHANGELOG.md +24 -0
- package/dist/dlx-package.js +6 -6
- package/dist/dlx-package.js.map +3 -3
- package/dist/external/@socketregistry/packageurl-js.js +2 -5
- package/dist/memoization.d.ts +6 -6
- package/dist/memoization.js.map +1 -1
- package/dist/performance.d.ts +10 -10
- package/dist/performance.js.map +1 -1
- package/dist/spinner.d.ts +8 -8
- package/dist/spinner.js.map +1 -1
- package/dist/suppress-warnings.d.ts +4 -4
- package/dist/suppress-warnings.js.map +1 -1
- package/dist/tables.d.ts +2 -2
- package/dist/tables.js.map +1 -1
- package/dist/versions.js +1 -1
- package/dist/versions.js.map +3 -3
- package/package.json +2 -2
package/dist/memoization.d.ts
CHANGED
|
@@ -24,7 +24,7 @@ type MemoizeOptions<Args extends unknown[], _Result = unknown> = {
|
|
|
24
24
|
* @returns Memoized version of the function
|
|
25
25
|
*
|
|
26
26
|
* @example
|
|
27
|
-
* import { memoize } from '@socketsecurity/
|
|
27
|
+
* import { memoize } from '@socketsecurity/lib/memoization'
|
|
28
28
|
*
|
|
29
29
|
* const expensiveOperation = memoize((n: number) => {
|
|
30
30
|
* // Heavy computation
|
|
@@ -44,7 +44,7 @@ export declare function memoize<Args extends unknown[], Result>(fn: (...args: Ar
|
|
|
44
44
|
* @returns Memoized version of the async function
|
|
45
45
|
*
|
|
46
46
|
* @example
|
|
47
|
-
* import { memoizeAsync } from '@socketsecurity/
|
|
47
|
+
* import { memoizeAsync } from '@socketsecurity/lib/memoization'
|
|
48
48
|
*
|
|
49
49
|
* const fetchUser = memoizeAsync(async (id: string) => {
|
|
50
50
|
* const response = await fetch(`/api/users/${id}`)
|
|
@@ -65,7 +65,7 @@ export declare function memoizeAsync<Args extends unknown[], Result>(fn: (...arg
|
|
|
65
65
|
* @returns Modified descriptor with memoized method
|
|
66
66
|
*
|
|
67
67
|
* @example
|
|
68
|
-
* import { Memoize } from '@socketsecurity/
|
|
68
|
+
* import { Memoize } from '@socketsecurity/lib/memoization'
|
|
69
69
|
*
|
|
70
70
|
* class Calculator {
|
|
71
71
|
* @Memoize()
|
|
@@ -90,7 +90,7 @@ export declare function clearAllMemoizationCaches(): void;
|
|
|
90
90
|
* @returns Memoized version using WeakMap
|
|
91
91
|
*
|
|
92
92
|
* @example
|
|
93
|
-
* import { memoizeWeak } from '@socketsecurity/
|
|
93
|
+
* import { memoizeWeak } from '@socketsecurity/lib/memoization'
|
|
94
94
|
*
|
|
95
95
|
* const processConfig = memoizeWeak((config: Config) => {
|
|
96
96
|
* return expensiveTransform(config)
|
|
@@ -109,7 +109,7 @@ export declare function memoizeWeak<K extends object, Result>(fn: (key: K) => Re
|
|
|
109
109
|
* @returns Memoized version that only executes once
|
|
110
110
|
*
|
|
111
111
|
* @example
|
|
112
|
-
* import { once } from '@socketsecurity/
|
|
112
|
+
* import { once } from '@socketsecurity/lib/memoization'
|
|
113
113
|
*
|
|
114
114
|
* const initialize = once(() => {
|
|
115
115
|
* console.log('Initializing…')
|
|
@@ -130,7 +130,7 @@ export declare function once<Result>(fn: () => Result): () => Result;
|
|
|
130
130
|
* @returns Debounced memoized function
|
|
131
131
|
*
|
|
132
132
|
* @example
|
|
133
|
-
* import { memoizeDebounced } from '@socketsecurity/
|
|
133
|
+
* import { memoizeDebounced } from '@socketsecurity/lib/memoization'
|
|
134
134
|
*
|
|
135
135
|
* const search = memoizeDebounced(
|
|
136
136
|
* (query: string) => performSearch(query),
|
package/dist/memoization.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/memoization.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Memoization utilities for caching function results.\n * Provides function result caching to optimize repeated computations and expensive operations.\n */\n\nimport { debugLog } from './debug'\n\n/**\n * Options for memoization behavior.\n */\ntype MemoizeOptions<Args extends unknown[], _Result = unknown> = {\n /** Custom cache key generator (defaults to JSON.stringify) */\n keyGen?: (...args: Args) => string\n /** Maximum cache size (LRU eviction when exceeded) */\n maxSize?: number\n /** TTL in milliseconds (cache entries expire after this time) */\n ttl?: number\n /** Cache name for debugging */\n name?: string\n /** Weak cache for object keys (enables GC) */\n weak?: boolean\n /** Custom equality check for cache hits */\n equals?: (a: Args, b: Args) => boolean\n}\n\n/**\n * Cache entry with metadata.\n */\ntype CacheEntry<T> = {\n value: T\n timestamp: number\n hits: number\n}\n\n/**\n * Memoize a function with configurable caching behavior.\n * Caches function results to avoid repeated computation.\n *\n * @param fn - Function to memoize\n * @param options - Memoization options\n * @returns Memoized version of the function\n *\n * @example\n * import { memoize } from '@socketsecurity/registry/lib/memoization'\n *\n * const expensiveOperation = memoize((n: number) => {\n * // Heavy computation\n * return Array(n).fill(0).reduce((a, _, i) => a + i, 0)\n * }, { maxSize: 100, ttl: 60000, name: 'sum' })\n *\n * expensiveOperation(1000) // Computed\n * expensiveOperation(1000) // Cached\n */\nexport function memoize<Args extends unknown[], Result>(\n fn: (...args: Args) => Result,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Result {\n const {\n keyGen = (...args) => JSON.stringify(args),\n maxSize = Number.POSITIVE_INFINITY,\n name = fn.name || 'anonymous',\n ttl = Number.POSITIVE_INFINITY,\n } = options\n\n const cache = new Map<string, CacheEntry<Result>>()\n const accessOrder: string[] = []\n\n function evictLRU(): void {\n if (cache.size >= maxSize && accessOrder.length > 0) {\n const oldest = accessOrder.shift()\n if (oldest) {\n cache.delete(oldest)\n debugLog(`[memoize:${name}] clear`, {\n key: oldest,\n reason: 'LRU',\n })\n }\n }\n }\n\n function isExpired(entry: CacheEntry<Result>): boolean {\n if (ttl === Number.POSITIVE_INFINITY) {\n return false\n }\n return Date.now() - entry.timestamp > ttl\n }\n\n return function memoized(...args: Args): Result {\n const key = keyGen(...args)\n\n // Check cache\n const cached = cache.get(key)\n if (cached && !isExpired(cached)) {\n cached.hits++\n // Move to end of access order (LRU)\n const index = accessOrder.indexOf(key)\n if (index !== -1) {\n accessOrder.splice(index, 1)\n }\n accessOrder.push(key)\n\n debugLog(`[memoize:${name}] hit`, { key, hits: cached.hits })\n return cached.value\n }\n\n // Cache miss - compute value\n debugLog(`[memoize:${name}] miss`, { key })\n const value = fn(...args)\n\n // Store in cache\n evictLRU()\n cache.set(key, {\n value,\n timestamp: Date.now(),\n hits: 0,\n })\n accessOrder.push(key)\n\n debugLog(`[memoize:${name}] set`, { key, cacheSize: cache.size })\n return value\n }\n}\n\n/**\n * Memoize an async function.\n * Similar to memoize() but handles promises properly.\n *\n * @param fn - Async function to memoize\n * @param options - Memoization options\n * @returns Memoized version of the async function\n *\n * @example\n * import { memoizeAsync } from '@socketsecurity/registry/lib/memoization'\n *\n * const fetchUser = memoizeAsync(async (id: string) => {\n * const response = await fetch(`/api/users/${id}`)\n * return response.json()\n * }, { ttl: 300000, name: 'fetchUser' })\n *\n * await fetchUser('123') // Fetches from API\n * await fetchUser('123') // Returns cached result\n */\nexport function memoizeAsync<Args extends unknown[], Result>(\n fn: (...args: Args) => Promise<Result>,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Promise<Result> {\n const {\n keyGen = (...args) => JSON.stringify(args),\n maxSize = Number.POSITIVE_INFINITY,\n name = fn.name || 'anonymous',\n ttl = Number.POSITIVE_INFINITY,\n } = options\n\n const cache = new Map<string, CacheEntry<Promise<Result>>>()\n const accessOrder: string[] = []\n\n function evictLRU(): void {\n if (cache.size >= maxSize && accessOrder.length > 0) {\n const oldest = accessOrder.shift()\n if (oldest) {\n cache.delete(oldest)\n debugLog(`[memoizeAsync:${name}] clear`, {\n key: oldest,\n reason: 'LRU',\n })\n }\n }\n }\n\n function isExpired(entry: CacheEntry<Promise<Result>>): boolean {\n if (ttl === Number.POSITIVE_INFINITY) {\n return false\n }\n return Date.now() - entry.timestamp > ttl\n }\n\n return async function memoized(...args: Args): Promise<Result> {\n const key = keyGen(...args)\n\n // Check cache\n const cached = cache.get(key)\n if (cached && !isExpired(cached)) {\n cached.hits++\n // Move to end of access order (LRU)\n const index = accessOrder.indexOf(key)\n if (index !== -1) {\n accessOrder.splice(index, 1)\n }\n accessOrder.push(key)\n\n debugLog(`[memoizeAsync:${name}] hit`, { key, hits: cached.hits })\n return await cached.value\n }\n\n // Cache miss - compute value\n debugLog(`[memoizeAsync:${name}] miss`, { key })\n const promise = fn(...args)\n\n // Store promise in cache (handles concurrent calls)\n evictLRU()\n cache.set(key, {\n value: promise,\n timestamp: Date.now(),\n hits: 0,\n })\n accessOrder.push(key)\n\n debugLog(`[memoizeAsync:${name}] set`, { key, cacheSize: cache.size })\n\n try {\n const result = await promise\n return result\n } catch (e) {\n // Remove failed promise from cache\n cache.delete(key)\n const orderIndex = accessOrder.indexOf(key)\n if (orderIndex !== -1) {\n accessOrder.splice(orderIndex, 1)\n }\n debugLog(`[memoizeAsync:${name}] clear`, { key, reason: 'error' })\n throw e\n }\n }\n}\n\n/**\n * Create a memoized version of a method.\n * Preserves 'this' context for class methods.\n *\n * @param target - Object containing the method\n * @param propertyKey - Method name\n * @param descriptor - Property descriptor\n * @returns Modified descriptor with memoized method\n *\n * @example\n * import { Memoize } from '@socketsecurity/registry/lib/memoization'\n *\n * class Calculator {\n * @Memoize()\n * fibonacci(n: number): number {\n * if (n <= 1) return n\n * return this.fibonacci(n - 1) + this.fibonacci(n - 2)\n * }\n * }\n */\nexport function Memoize(options: MemoizeOptions<unknown[], unknown> = {}) {\n return (\n _target: unknown,\n propertyKey: string,\n descriptor: PropertyDescriptor,\n ): PropertyDescriptor => {\n const originalMethod = descriptor.value as (...args: unknown[]) => unknown\n\n descriptor.value = memoize(originalMethod, {\n ...options,\n name: options.name || propertyKey,\n })\n\n return descriptor\n }\n}\n\n/**\n * Clear all memoization caches.\n * Useful for testing or when you need to force recomputation.\n */\nexport function clearAllMemoizationCaches(): void {\n // Note: This requires the memoized functions to be tracked globally.\n // For now, this is a placeholder that logs the intent.\n debugLog('[memoize:all] clear', { action: 'clear-all-caches' })\n}\n\n/**\n * Memoize with WeakMap for object keys.\n * Allows garbage collection when objects are no longer referenced.\n * Only works when first argument is an object.\n *\n * @param fn - Function to memoize\n * @returns Memoized version using WeakMap\n *\n * @example\n * import { memoizeWeak } from '@socketsecurity/registry/lib/memoization'\n *\n * const processConfig = memoizeWeak((config: Config) => {\n * return expensiveTransform(config)\n * })\n *\n * processConfig(config1) // Computed\n * processConfig(config1) // Cached\n * // When config1 is no longer referenced, cache entry is GC'd\n */\nexport function memoizeWeak<K extends object, Result>(\n fn: (key: K) => Result,\n): (key: K) => Result {\n const cache = new WeakMap<K, Result>()\n\n return function memoized(key: K): Result {\n const cached = cache.get(key)\n if (cached !== undefined) {\n debugLog(`[memoizeWeak:${fn.name}] hit`)\n return cached\n }\n\n debugLog(`[memoizeWeak:${fn.name}] miss`)\n const result = fn(key)\n cache.set(key, result)\n return result\n }\n}\n\n/**\n * Simple once() implementation - caches single result forever.\n * Useful for initialization functions that should only run once.\n *\n * @param fn - Function to run once\n * @returns Memoized version that only executes once\n *\n * @example\n * import { once } from '@socketsecurity/registry/lib/memoization'\n *\n * const initialize = once(() => {\n * console.log('Initializing\u2026')\n * return loadConfig()\n * })\n *\n * initialize() // Logs \"Initializing\u2026\" and returns config\n * initialize() // Returns cached config (no log)\n */\nexport function once<Result>(fn: () => Result): () => Result {\n let called = false\n let result: Result\n\n return function memoized(): Result {\n if (!called) {\n result = fn()\n called = true\n debugLog(`[once:${fn.name}] set`)\n } else {\n debugLog(`[once:${fn.name}] hit`)\n }\n return result\n }\n}\n\n/**\n * Create a debounced memoized function.\n * Combines memoization with debouncing for expensive operations.\n *\n * @param fn - Function to memoize and debounce\n * @param wait - Debounce wait time in milliseconds\n * @param options - Memoization options\n * @returns Debounced memoized function\n *\n * @example\n * import { memoizeDebounced } from '@socketsecurity/registry/lib/memoization'\n *\n * const search = memoizeDebounced(\n * (query: string) => performSearch(query),\n * 300,\n * { name: 'search' }\n * )\n */\nexport function memoizeDebounced<Args extends unknown[], Result>(\n fn: (...args: Args) => Result,\n wait: number,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Result {\n const memoized = memoize(fn, options)\n let timeoutId: NodeJS.Timeout | undefined\n\n return function debounced(...args: Args): Result {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n\n timeoutId = setTimeout(() => {\n memoized(...args)\n }, wait)\n\n // For immediate return, try cached value or compute synchronously\n return memoized(...args)\n }\n}\n"],
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Memoization utilities for caching function results.\n * Provides function result caching to optimize repeated computations and expensive operations.\n */\n\nimport { debugLog } from './debug'\n\n/**\n * Options for memoization behavior.\n */\ntype MemoizeOptions<Args extends unknown[], _Result = unknown> = {\n /** Custom cache key generator (defaults to JSON.stringify) */\n keyGen?: (...args: Args) => string\n /** Maximum cache size (LRU eviction when exceeded) */\n maxSize?: number\n /** TTL in milliseconds (cache entries expire after this time) */\n ttl?: number\n /** Cache name for debugging */\n name?: string\n /** Weak cache for object keys (enables GC) */\n weak?: boolean\n /** Custom equality check for cache hits */\n equals?: (a: Args, b: Args) => boolean\n}\n\n/**\n * Cache entry with metadata.\n */\ntype CacheEntry<T> = {\n value: T\n timestamp: number\n hits: number\n}\n\n/**\n * Memoize a function with configurable caching behavior.\n * Caches function results to avoid repeated computation.\n *\n * @param fn - Function to memoize\n * @param options - Memoization options\n * @returns Memoized version of the function\n *\n * @example\n * import { memoize } from '@socketsecurity/lib/memoization'\n *\n * const expensiveOperation = memoize((n: number) => {\n * // Heavy computation\n * return Array(n).fill(0).reduce((a, _, i) => a + i, 0)\n * }, { maxSize: 100, ttl: 60000, name: 'sum' })\n *\n * expensiveOperation(1000) // Computed\n * expensiveOperation(1000) // Cached\n */\nexport function memoize<Args extends unknown[], Result>(\n fn: (...args: Args) => Result,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Result {\n const {\n keyGen = (...args) => JSON.stringify(args),\n maxSize = Number.POSITIVE_INFINITY,\n name = fn.name || 'anonymous',\n ttl = Number.POSITIVE_INFINITY,\n } = options\n\n const cache = new Map<string, CacheEntry<Result>>()\n const accessOrder: string[] = []\n\n function evictLRU(): void {\n if (cache.size >= maxSize && accessOrder.length > 0) {\n const oldest = accessOrder.shift()\n if (oldest) {\n cache.delete(oldest)\n debugLog(`[memoize:${name}] clear`, {\n key: oldest,\n reason: 'LRU',\n })\n }\n }\n }\n\n function isExpired(entry: CacheEntry<Result>): boolean {\n if (ttl === Number.POSITIVE_INFINITY) {\n return false\n }\n return Date.now() - entry.timestamp > ttl\n }\n\n return function memoized(...args: Args): Result {\n const key = keyGen(...args)\n\n // Check cache\n const cached = cache.get(key)\n if (cached && !isExpired(cached)) {\n cached.hits++\n // Move to end of access order (LRU)\n const index = accessOrder.indexOf(key)\n if (index !== -1) {\n accessOrder.splice(index, 1)\n }\n accessOrder.push(key)\n\n debugLog(`[memoize:${name}] hit`, { key, hits: cached.hits })\n return cached.value\n }\n\n // Cache miss - compute value\n debugLog(`[memoize:${name}] miss`, { key })\n const value = fn(...args)\n\n // Store in cache\n evictLRU()\n cache.set(key, {\n value,\n timestamp: Date.now(),\n hits: 0,\n })\n accessOrder.push(key)\n\n debugLog(`[memoize:${name}] set`, { key, cacheSize: cache.size })\n return value\n }\n}\n\n/**\n * Memoize an async function.\n * Similar to memoize() but handles promises properly.\n *\n * @param fn - Async function to memoize\n * @param options - Memoization options\n * @returns Memoized version of the async function\n *\n * @example\n * import { memoizeAsync } from '@socketsecurity/lib/memoization'\n *\n * const fetchUser = memoizeAsync(async (id: string) => {\n * const response = await fetch(`/api/users/${id}`)\n * return response.json()\n * }, { ttl: 300000, name: 'fetchUser' })\n *\n * await fetchUser('123') // Fetches from API\n * await fetchUser('123') // Returns cached result\n */\nexport function memoizeAsync<Args extends unknown[], Result>(\n fn: (...args: Args) => Promise<Result>,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Promise<Result> {\n const {\n keyGen = (...args) => JSON.stringify(args),\n maxSize = Number.POSITIVE_INFINITY,\n name = fn.name || 'anonymous',\n ttl = Number.POSITIVE_INFINITY,\n } = options\n\n const cache = new Map<string, CacheEntry<Promise<Result>>>()\n const accessOrder: string[] = []\n\n function evictLRU(): void {\n if (cache.size >= maxSize && accessOrder.length > 0) {\n const oldest = accessOrder.shift()\n if (oldest) {\n cache.delete(oldest)\n debugLog(`[memoizeAsync:${name}] clear`, {\n key: oldest,\n reason: 'LRU',\n })\n }\n }\n }\n\n function isExpired(entry: CacheEntry<Promise<Result>>): boolean {\n if (ttl === Number.POSITIVE_INFINITY) {\n return false\n }\n return Date.now() - entry.timestamp > ttl\n }\n\n return async function memoized(...args: Args): Promise<Result> {\n const key = keyGen(...args)\n\n // Check cache\n const cached = cache.get(key)\n if (cached && !isExpired(cached)) {\n cached.hits++\n // Move to end of access order (LRU)\n const index = accessOrder.indexOf(key)\n if (index !== -1) {\n accessOrder.splice(index, 1)\n }\n accessOrder.push(key)\n\n debugLog(`[memoizeAsync:${name}] hit`, { key, hits: cached.hits })\n return await cached.value\n }\n\n // Cache miss - compute value\n debugLog(`[memoizeAsync:${name}] miss`, { key })\n const promise = fn(...args)\n\n // Store promise in cache (handles concurrent calls)\n evictLRU()\n cache.set(key, {\n value: promise,\n timestamp: Date.now(),\n hits: 0,\n })\n accessOrder.push(key)\n\n debugLog(`[memoizeAsync:${name}] set`, { key, cacheSize: cache.size })\n\n try {\n const result = await promise\n return result\n } catch (e) {\n // Remove failed promise from cache\n cache.delete(key)\n const orderIndex = accessOrder.indexOf(key)\n if (orderIndex !== -1) {\n accessOrder.splice(orderIndex, 1)\n }\n debugLog(`[memoizeAsync:${name}] clear`, { key, reason: 'error' })\n throw e\n }\n }\n}\n\n/**\n * Create a memoized version of a method.\n * Preserves 'this' context for class methods.\n *\n * @param target - Object containing the method\n * @param propertyKey - Method name\n * @param descriptor - Property descriptor\n * @returns Modified descriptor with memoized method\n *\n * @example\n * import { Memoize } from '@socketsecurity/lib/memoization'\n *\n * class Calculator {\n * @Memoize()\n * fibonacci(n: number): number {\n * if (n <= 1) return n\n * return this.fibonacci(n - 1) + this.fibonacci(n - 2)\n * }\n * }\n */\nexport function Memoize(options: MemoizeOptions<unknown[], unknown> = {}) {\n return (\n _target: unknown,\n propertyKey: string,\n descriptor: PropertyDescriptor,\n ): PropertyDescriptor => {\n const originalMethod = descriptor.value as (...args: unknown[]) => unknown\n\n descriptor.value = memoize(originalMethod, {\n ...options,\n name: options.name || propertyKey,\n })\n\n return descriptor\n }\n}\n\n/**\n * Clear all memoization caches.\n * Useful for testing or when you need to force recomputation.\n */\nexport function clearAllMemoizationCaches(): void {\n // Note: This requires the memoized functions to be tracked globally.\n // For now, this is a placeholder that logs the intent.\n debugLog('[memoize:all] clear', { action: 'clear-all-caches' })\n}\n\n/**\n * Memoize with WeakMap for object keys.\n * Allows garbage collection when objects are no longer referenced.\n * Only works when first argument is an object.\n *\n * @param fn - Function to memoize\n * @returns Memoized version using WeakMap\n *\n * @example\n * import { memoizeWeak } from '@socketsecurity/lib/memoization'\n *\n * const processConfig = memoizeWeak((config: Config) => {\n * return expensiveTransform(config)\n * })\n *\n * processConfig(config1) // Computed\n * processConfig(config1) // Cached\n * // When config1 is no longer referenced, cache entry is GC'd\n */\nexport function memoizeWeak<K extends object, Result>(\n fn: (key: K) => Result,\n): (key: K) => Result {\n const cache = new WeakMap<K, Result>()\n\n return function memoized(key: K): Result {\n const cached = cache.get(key)\n if (cached !== undefined) {\n debugLog(`[memoizeWeak:${fn.name}] hit`)\n return cached\n }\n\n debugLog(`[memoizeWeak:${fn.name}] miss`)\n const result = fn(key)\n cache.set(key, result)\n return result\n }\n}\n\n/**\n * Simple once() implementation - caches single result forever.\n * Useful for initialization functions that should only run once.\n *\n * @param fn - Function to run once\n * @returns Memoized version that only executes once\n *\n * @example\n * import { once } from '@socketsecurity/lib/memoization'\n *\n * const initialize = once(() => {\n * console.log('Initializing\u2026')\n * return loadConfig()\n * })\n *\n * initialize() // Logs \"Initializing\u2026\" and returns config\n * initialize() // Returns cached config (no log)\n */\nexport function once<Result>(fn: () => Result): () => Result {\n let called = false\n let result: Result\n\n return function memoized(): Result {\n if (!called) {\n result = fn()\n called = true\n debugLog(`[once:${fn.name}] set`)\n } else {\n debugLog(`[once:${fn.name}] hit`)\n }\n return result\n }\n}\n\n/**\n * Create a debounced memoized function.\n * Combines memoization with debouncing for expensive operations.\n *\n * @param fn - Function to memoize and debounce\n * @param wait - Debounce wait time in milliseconds\n * @param options - Memoization options\n * @returns Debounced memoized function\n *\n * @example\n * import { memoizeDebounced } from '@socketsecurity/lib/memoization'\n *\n * const search = memoizeDebounced(\n * (query: string) => performSearch(query),\n * 300,\n * { name: 'search' }\n * )\n */\nexport function memoizeDebounced<Args extends unknown[], Result>(\n fn: (...args: Args) => Result,\n wait: number,\n options: MemoizeOptions<Args, Result> = {},\n): (...args: Args) => Result {\n const memoized = memoize(fn, options)\n let timeoutId: NodeJS.Timeout | undefined\n\n return function debounced(...args: Args): Result {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n\n timeoutId = setTimeout(() => {\n memoized(...args)\n }, wait)\n\n // For immediate return, try cached value or compute synchronously\n return memoized(...args)\n }\n}\n"],
|
|
5
5
|
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,8BAAAC,EAAA,YAAAC,EAAA,iBAAAC,EAAA,qBAAAC,EAAA,gBAAAC,EAAA,SAAAC,IAAA,eAAAC,EAAAT,GAKA,IAAAU,EAAyB,mBAgDlB,SAASN,EACdO,EACAC,EAAwC,CAAC,EACd,CAC3B,KAAM,CACJ,OAAAC,EAAS,IAAIC,IAAS,KAAK,UAAUA,CAAI,EACzC,QAAAC,EAAU,OAAO,kBACjB,KAAAC,EAAOL,EAAG,MAAQ,YAClB,IAAAM,EAAM,OAAO,iBACf,EAAIL,EAEEM,EAAQ,IAAI,IACZC,EAAwB,CAAC,EAE/B,SAAS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Memoize", "clearAllMemoizationCaches", "memoize", "memoizeAsync", "memoizeDebounced", "memoizeWeak", "once", "__toCommonJS", "import_debug", "fn", "options", "keyGen", "args", "maxSize", "name", "ttl", "cache", "accessOrder", "evictLRU", "oldest", "isExpired", "entry", "key", "cached", "index", "value", "promise", "e", "orderIndex", "_target", "propertyKey", "descriptor", "originalMethod", "result", "called", "wait", "memoized", "timeoutId"]
|
|
7
7
|
}
|
package/dist/performance.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ type PerformanceMetrics = {
|
|
|
16
16
|
* @returns Stop function that completes the timing
|
|
17
17
|
*
|
|
18
18
|
* @example
|
|
19
|
-
* import { perfTimer } from '@socketsecurity/
|
|
19
|
+
* import { perfTimer } from '@socketsecurity/lib/performance'
|
|
20
20
|
*
|
|
21
21
|
* const stop = perfTimer('api-call')
|
|
22
22
|
* await fetchData()
|
|
@@ -32,7 +32,7 @@ export declare function perfTimer(operation: string, metadata?: Record<string, u
|
|
|
32
32
|
* @returns Result of the function and duration
|
|
33
33
|
*
|
|
34
34
|
* @example
|
|
35
|
-
* import { measure } from '@socketsecurity/
|
|
35
|
+
* import { measure } from '@socketsecurity/lib/performance'
|
|
36
36
|
*
|
|
37
37
|
* const { result, duration } = await measure('fetch-packages', async () => {
|
|
38
38
|
* return await fetchPackages()
|
|
@@ -52,7 +52,7 @@ export declare function measure<T>(operation: string, fn: () => Promise<T>, meta
|
|
|
52
52
|
* @returns Result of the function and duration
|
|
53
53
|
*
|
|
54
54
|
* @example
|
|
55
|
-
* import { measureSync } from '@socketsecurity/
|
|
55
|
+
* import { measureSync } from '@socketsecurity/lib/performance'
|
|
56
56
|
*
|
|
57
57
|
* const { result, duration } = measureSync('parse-json', () => {
|
|
58
58
|
* return JSON.parse(data)
|
|
@@ -69,7 +69,7 @@ export declare function measureSync<T>(operation: string, fn: () => T, metadata?
|
|
|
69
69
|
* @returns Array of performance metrics
|
|
70
70
|
*
|
|
71
71
|
* @example
|
|
72
|
-
* import { getPerformanceMetrics } from '@socketsecurity/
|
|
72
|
+
* import { getPerformanceMetrics } from '@socketsecurity/lib/performance'
|
|
73
73
|
*
|
|
74
74
|
* const metrics = getPerformanceMetrics()
|
|
75
75
|
* console.log(metrics)
|
|
@@ -79,7 +79,7 @@ export declare function getPerformanceMetrics(): PerformanceMetrics[];
|
|
|
79
79
|
* Clear all collected performance metrics.
|
|
80
80
|
*
|
|
81
81
|
* @example
|
|
82
|
-
* import { clearPerformanceMetrics } from '@socketsecurity/
|
|
82
|
+
* import { clearPerformanceMetrics } from '@socketsecurity/lib/performance'
|
|
83
83
|
*
|
|
84
84
|
* clearPerformanceMetrics()
|
|
85
85
|
*/
|
|
@@ -90,7 +90,7 @@ export declare function clearPerformanceMetrics(): void;
|
|
|
90
90
|
* @returns Summary of metrics grouped by operation
|
|
91
91
|
*
|
|
92
92
|
* @example
|
|
93
|
-
* import { getPerformanceSummary } from '@socketsecurity/
|
|
93
|
+
* import { getPerformanceSummary } from '@socketsecurity/lib/performance'
|
|
94
94
|
*
|
|
95
95
|
* const summary = getPerformanceSummary()
|
|
96
96
|
* console.log(summary)
|
|
@@ -111,7 +111,7 @@ export declare function getPerformanceSummary(): Record<string, {
|
|
|
111
111
|
* Only prints when DEBUG=perf is enabled.
|
|
112
112
|
*
|
|
113
113
|
* @example
|
|
114
|
-
* import { printPerformanceSummary } from '@socketsecurity/
|
|
114
|
+
* import { printPerformanceSummary } from '@socketsecurity/lib/performance'
|
|
115
115
|
*
|
|
116
116
|
* printPerformanceSummary()
|
|
117
117
|
* // Performance Summary:
|
|
@@ -127,7 +127,7 @@ export declare function printPerformanceSummary(): void;
|
|
|
127
127
|
* @param metadata - Optional metadata
|
|
128
128
|
*
|
|
129
129
|
* @example
|
|
130
|
-
* import { perfCheckpoint } from '@socketsecurity/
|
|
130
|
+
* import { perfCheckpoint } from '@socketsecurity/lib/performance'
|
|
131
131
|
*
|
|
132
132
|
* perfCheckpoint('start-scan')
|
|
133
133
|
* // ... do work ...
|
|
@@ -145,7 +145,7 @@ export declare function perfCheckpoint(checkpoint: string, metadata?: Record<str
|
|
|
145
145
|
* @returns Memory usage in MB
|
|
146
146
|
*
|
|
147
147
|
* @example
|
|
148
|
-
* import { trackMemory } from '@socketsecurity/
|
|
148
|
+
* import { trackMemory } from '@socketsecurity/lib/performance'
|
|
149
149
|
*
|
|
150
150
|
* const memBefore = trackMemory('before-operation')
|
|
151
151
|
* await heavyOperation()
|
|
@@ -160,7 +160,7 @@ export declare function trackMemory(label: string): number;
|
|
|
160
160
|
* @returns Formatted performance report
|
|
161
161
|
*
|
|
162
162
|
* @example
|
|
163
|
-
* import { generatePerformanceReport } from '@socketsecurity/
|
|
163
|
+
* import { generatePerformanceReport } from '@socketsecurity/lib/performance'
|
|
164
164
|
*
|
|
165
165
|
* console.log(generatePerformanceReport())
|
|
166
166
|
* // ╔═══════════════════════════════════════════════╗
|
package/dist/performance.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/performance.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Performance monitoring utilities for profiling and optimization.\n * Provides timing, profiling, and performance metric collection for identifying bottlenecks.\n */\n\nimport { debugLog } from './debug'\n\n/**\n * Performance metrics collected during execution.\n */\ntype PerformanceMetrics = {\n operation: string\n duration: number\n timestamp: number\n metadata?: Record<string, unknown>\n}\n\n/**\n * Global metrics collection (only in debug mode).\n */\nconst performanceMetrics: PerformanceMetrics[] = []\n\n/**\n * Check if performance tracking is enabled.\n */\nfunction isPerfEnabled(): boolean {\n return process.env['DEBUG']?.includes('perf') || false\n}\n\n/**\n * Start a performance timer for an operation.\n * Returns a stop function that records the duration.\n *\n * @param operation - Name of the operation being timed\n * @param metadata - Optional metadata to attach to the metric\n * @returns Stop function that completes the timing\n *\n * @example\n * import { perfTimer } from '@socketsecurity/registry/lib/performance'\n *\n * const stop = perfTimer('api-call')\n * await fetchData()\n * stop({ endpoint: '/npm/lodash/score' })\n */\nexport function perfTimer(\n operation: string,\n metadata?: Record<string, unknown>,\n): (additionalMetadata?: Record<string, unknown>) => void {\n if (!isPerfEnabled()) {\n // No-op if perf tracking disabled\n return () => {}\n }\n\n const start = performance.now()\n debugLog(`[perf] [START] ${operation}`)\n\n return (additionalMetadata?: Record<string, unknown>) => {\n const duration = performance.now() - start\n const metric: PerformanceMetrics = {\n operation,\n // Round to 2 decimals\n duration: Math.round(duration * 100) / 100,\n timestamp: Date.now(),\n metadata: { ...metadata, ...additionalMetadata },\n }\n\n performanceMetrics.push(metric)\n debugLog(`[perf] [END] ${operation} - ${metric.duration}ms`)\n }\n}\n\n/**\n * Measure execution time of an async function.\n *\n * @param operation - Name of the operation\n * @param fn - Async function to measure\n * @param metadata - Optional metadata\n * @returns Result of the function and duration\n *\n * @example\n * import { measure } from '@socketsecurity/registry/lib/performance'\n *\n * const { result, duration } = await measure('fetch-packages', async () => {\n * return await fetchPackages()\n * })\n * console.log(`Fetched packages in ${duration}ms`)\n */\nexport async function measure<T>(\n operation: string,\n fn: () => Promise<T>,\n metadata?: Record<string, unknown>,\n): Promise<{ result: T; duration: number }> {\n const stop = perfTimer(operation, metadata)\n\n try {\n const result = await fn()\n stop({ success: true })\n\n const metric = performanceMetrics[performanceMetrics.length - 1]\n return { result, duration: metric?.duration || 0 }\n } catch (e) {\n stop({\n success: false,\n error: e instanceof Error ? e.message : 'Unknown',\n })\n throw e\n }\n}\n\n/**\n * Measure synchronous function execution time.\n *\n * @param operation - Name of the operation\n * @param fn - Synchronous function to measure\n * @param metadata - Optional metadata\n * @returns Result of the function and duration\n *\n * @example\n * import { measureSync } from '@socketsecurity/registry/lib/performance'\n *\n * const { result, duration } = measureSync('parse-json', () => {\n * return JSON.parse(data)\n * })\n */\nexport function measureSync<T>(\n operation: string,\n fn: () => T,\n metadata?: Record<string, unknown>,\n): { result: T; duration: number } {\n const stop = perfTimer(operation, metadata)\n\n try {\n const result = fn()\n stop({ success: true })\n\n const metric = performanceMetrics[performanceMetrics.length - 1]\n return { result, duration: metric?.duration || 0 }\n } catch (e) {\n stop({\n success: false,\n error: e instanceof Error ? e.message : 'Unknown',\n })\n throw e\n }\n}\n\n/**\n * Get all collected performance metrics.\n * Only available when DEBUG=perf is enabled.\n *\n * @returns Array of performance metrics\n *\n * @example\n * import { getPerformanceMetrics } from '@socketsecurity/registry/lib/performance'\n *\n * const metrics = getPerformanceMetrics()\n * console.log(metrics)\n */\nexport function getPerformanceMetrics(): PerformanceMetrics[] {\n return [...performanceMetrics]\n}\n\n/**\n * Clear all collected performance metrics.\n *\n * @example\n * import { clearPerformanceMetrics } from '@socketsecurity/registry/lib/performance'\n *\n * clearPerformanceMetrics()\n */\nexport function clearPerformanceMetrics(): void {\n performanceMetrics.length = 0\n debugLog('[perf] Cleared performance metrics')\n}\n\n/**\n * Get performance summary statistics.\n *\n * @returns Summary of metrics grouped by operation\n *\n * @example\n * import { getPerformanceSummary } from '@socketsecurity/registry/lib/performance'\n *\n * const summary = getPerformanceSummary()\n * console.log(summary)\n * // {\n * // 'api-call': { count: 5, total: 1234, avg: 246.8, min: 100, max: 500 },\n * // 'file-read': { count: 10, total: 50, avg: 5, min: 2, max: 15 }\n * // }\n */\nexport function getPerformanceSummary(): Record<\n string,\n {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n> {\n const summary: Record<\n string,\n { count: number; total: number; min: number; max: number }\n > = Object.create(null)\n\n for (const metric of performanceMetrics) {\n const { duration, operation } = metric\n\n if (!summary[operation]) {\n summary[operation] = {\n count: 0,\n total: 0,\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n }\n }\n\n const stats = summary[operation] as {\n count: number\n total: number\n min: number\n max: number\n }\n stats.count++\n stats.total += duration\n stats.min = Math.min(stats.min, duration)\n stats.max = Math.max(stats.max, duration)\n }\n\n // Calculate averages and return with proper typing\n const result: Record<\n string,\n { count: number; total: number; avg: number; min: number; max: number }\n > = Object.create(null)\n\n for (const { 0: operation, 1: stats } of Object.entries(summary)) {\n result[operation] = {\n count: stats.count,\n total: Math.round(stats.total * 100) / 100,\n avg: Math.round((stats.total / stats.count) * 100) / 100,\n min: Math.round(stats.min * 100) / 100,\n max: Math.round(stats.max * 100) / 100,\n }\n }\n\n return result\n}\n\n/**\n * Print performance summary to console.\n * Only prints when DEBUG=perf is enabled.\n *\n * @example\n * import { printPerformanceSummary } from '@socketsecurity/registry/lib/performance'\n *\n * printPerformanceSummary()\n * // Performance Summary:\n * // api-call: 5 calls, avg 246.8ms (min 100ms, max 500ms, total 1234ms)\n * // file-read: 10 calls, avg 5ms (min 2ms, max 15ms, total 50ms)\n */\nexport function printPerformanceSummary(): void {\n if (!isPerfEnabled() || performanceMetrics.length === 0) {\n return\n }\n\n const summary = getPerformanceSummary()\n const operations = Object.keys(summary).sort()\n\n debugLog('[perf]\\n=== Performance Summary ===')\n\n for (const operation of operations) {\n const stats = summary[operation] as {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n debugLog(\n `[perf] ${operation}: ${stats.count} calls, avg ${stats.avg}ms (min ${stats.min}ms, max ${stats.max}ms, total ${stats.total}ms)`,\n )\n }\n\n debugLog('[perf] =========================\\n')\n}\n\n/**\n * Mark a checkpoint in performance tracking.\n * Useful for tracking progress through complex operations.\n *\n * @param checkpoint - Name of the checkpoint\n * @param metadata - Optional metadata\n *\n * @example\n * import { perfCheckpoint } from '@socketsecurity/registry/lib/performance'\n *\n * perfCheckpoint('start-scan')\n * // ... do work ...\n * perfCheckpoint('fetch-packages', { count: 50 })\n * // ... do work ...\n * perfCheckpoint('analyze-issues', { issueCount: 10 })\n * perfCheckpoint('end-scan')\n */\nexport function perfCheckpoint(\n checkpoint: string,\n metadata?: Record<string, unknown>,\n): void {\n if (!isPerfEnabled()) {\n return\n }\n\n const metric: PerformanceMetrics = {\n operation: `checkpoint:${checkpoint}`,\n duration: 0,\n timestamp: Date.now(),\n ...(metadata ? { metadata } : {}),\n }\n\n performanceMetrics.push(metric)\n debugLog(`[perf] [CHECKPOINT] ${checkpoint}`)\n}\n\n/**\n * Track memory usage at a specific point.\n * Only available when DEBUG=perf is enabled.\n *\n * @param label - Label for this memory snapshot\n * @returns Memory usage in MB\n *\n * @example\n * import { trackMemory } from '@socketsecurity/registry/lib/performance'\n *\n * const memBefore = trackMemory('before-operation')\n * await heavyOperation()\n * const memAfter = trackMemory('after-operation')\n * console.log(`Memory increased by ${memAfter - memBefore}MB`)\n */\nexport function trackMemory(label: string): number {\n if (!isPerfEnabled()) {\n return 0\n }\n\n const usage = process.memoryUsage()\n const heapUsedMB = Math.round((usage.heapUsed / 1024 / 1024) * 100) / 100\n\n debugLog(`[perf] [MEMORY] ${label}: ${heapUsedMB}MB heap used`)\n\n const metric: PerformanceMetrics = {\n operation: `checkpoint:memory:${label}`,\n duration: 0,\n timestamp: Date.now(),\n metadata: {\n heapUsed: heapUsedMB,\n heapTotal: Math.round((usage.heapTotal / 1024 / 1024) * 100) / 100,\n external: Math.round((usage.external / 1024 / 1024) * 100) / 100,\n },\n }\n\n performanceMetrics.push(metric)\n\n return heapUsedMB\n}\n\n/**\n * Create a performance report for the current execution.\n * Only available when DEBUG=perf is enabled.\n *\n * @returns Formatted performance report\n *\n * @example\n * import { generatePerformanceReport } from '@socketsecurity/registry/lib/performance'\n *\n * console.log(generatePerformanceReport())\n * // \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n * // \u2551 Performance Report \u2551\n * // \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\n * //\n * // api-call:\n * // Calls: 5\n * // Avg: 246.8ms\n * // Min: 100ms\n * // Max: 500ms\n * // Total: 1234ms\n */\nexport function generatePerformanceReport(): string {\n if (!isPerfEnabled() || performanceMetrics.length === 0) {\n return '(no performance data collected - enable with DEBUG=perf)'\n }\n\n const summary = getPerformanceSummary()\n const operations = Object.keys(summary).sort()\n\n let report = '\\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\\n'\n report += '\u2551 Performance Report \u2551\\n'\n report += '\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\\n\\n'\n\n for (const operation of operations) {\n const stats = summary[operation] as {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n report += `${operation}:\\n`\n report += ` Calls: ${stats.count}\\n`\n report += ` Avg: ${stats.avg}ms\\n`\n report += ` Min: ${stats.min}ms\\n`\n report += ` Max: ${stats.max}ms\\n`\n report += ` Total: ${stats.total}ms\\n\\n`\n }\n\n const totalDuration = Object.values(summary).reduce(\n (sum, s) => sum + s.total,\n 0,\n )\n report += `Total measured time: ${Math.round(totalDuration * 100) / 100}ms\\n`\n\n return report\n}\n"],
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Performance monitoring utilities for profiling and optimization.\n * Provides timing, profiling, and performance metric collection for identifying bottlenecks.\n */\n\nimport { debugLog } from './debug'\n\n/**\n * Performance metrics collected during execution.\n */\ntype PerformanceMetrics = {\n operation: string\n duration: number\n timestamp: number\n metadata?: Record<string, unknown>\n}\n\n/**\n * Global metrics collection (only in debug mode).\n */\nconst performanceMetrics: PerformanceMetrics[] = []\n\n/**\n * Check if performance tracking is enabled.\n */\nfunction isPerfEnabled(): boolean {\n return process.env['DEBUG']?.includes('perf') || false\n}\n\n/**\n * Start a performance timer for an operation.\n * Returns a stop function that records the duration.\n *\n * @param operation - Name of the operation being timed\n * @param metadata - Optional metadata to attach to the metric\n * @returns Stop function that completes the timing\n *\n * @example\n * import { perfTimer } from '@socketsecurity/lib/performance'\n *\n * const stop = perfTimer('api-call')\n * await fetchData()\n * stop({ endpoint: '/npm/lodash/score' })\n */\nexport function perfTimer(\n operation: string,\n metadata?: Record<string, unknown>,\n): (additionalMetadata?: Record<string, unknown>) => void {\n if (!isPerfEnabled()) {\n // No-op if perf tracking disabled\n return () => {}\n }\n\n const start = performance.now()\n debugLog(`[perf] [START] ${operation}`)\n\n return (additionalMetadata?: Record<string, unknown>) => {\n const duration = performance.now() - start\n const metric: PerformanceMetrics = {\n operation,\n // Round to 2 decimals\n duration: Math.round(duration * 100) / 100,\n timestamp: Date.now(),\n metadata: { ...metadata, ...additionalMetadata },\n }\n\n performanceMetrics.push(metric)\n debugLog(`[perf] [END] ${operation} - ${metric.duration}ms`)\n }\n}\n\n/**\n * Measure execution time of an async function.\n *\n * @param operation - Name of the operation\n * @param fn - Async function to measure\n * @param metadata - Optional metadata\n * @returns Result of the function and duration\n *\n * @example\n * import { measure } from '@socketsecurity/lib/performance'\n *\n * const { result, duration } = await measure('fetch-packages', async () => {\n * return await fetchPackages()\n * })\n * console.log(`Fetched packages in ${duration}ms`)\n */\nexport async function measure<T>(\n operation: string,\n fn: () => Promise<T>,\n metadata?: Record<string, unknown>,\n): Promise<{ result: T; duration: number }> {\n const stop = perfTimer(operation, metadata)\n\n try {\n const result = await fn()\n stop({ success: true })\n\n const metric = performanceMetrics[performanceMetrics.length - 1]\n return { result, duration: metric?.duration || 0 }\n } catch (e) {\n stop({\n success: false,\n error: e instanceof Error ? e.message : 'Unknown',\n })\n throw e\n }\n}\n\n/**\n * Measure synchronous function execution time.\n *\n * @param operation - Name of the operation\n * @param fn - Synchronous function to measure\n * @param metadata - Optional metadata\n * @returns Result of the function and duration\n *\n * @example\n * import { measureSync } from '@socketsecurity/lib/performance'\n *\n * const { result, duration } = measureSync('parse-json', () => {\n * return JSON.parse(data)\n * })\n */\nexport function measureSync<T>(\n operation: string,\n fn: () => T,\n metadata?: Record<string, unknown>,\n): { result: T; duration: number } {\n const stop = perfTimer(operation, metadata)\n\n try {\n const result = fn()\n stop({ success: true })\n\n const metric = performanceMetrics[performanceMetrics.length - 1]\n return { result, duration: metric?.duration || 0 }\n } catch (e) {\n stop({\n success: false,\n error: e instanceof Error ? e.message : 'Unknown',\n })\n throw e\n }\n}\n\n/**\n * Get all collected performance metrics.\n * Only available when DEBUG=perf is enabled.\n *\n * @returns Array of performance metrics\n *\n * @example\n * import { getPerformanceMetrics } from '@socketsecurity/lib/performance'\n *\n * const metrics = getPerformanceMetrics()\n * console.log(metrics)\n */\nexport function getPerformanceMetrics(): PerformanceMetrics[] {\n return [...performanceMetrics]\n}\n\n/**\n * Clear all collected performance metrics.\n *\n * @example\n * import { clearPerformanceMetrics } from '@socketsecurity/lib/performance'\n *\n * clearPerformanceMetrics()\n */\nexport function clearPerformanceMetrics(): void {\n performanceMetrics.length = 0\n debugLog('[perf] Cleared performance metrics')\n}\n\n/**\n * Get performance summary statistics.\n *\n * @returns Summary of metrics grouped by operation\n *\n * @example\n * import { getPerformanceSummary } from '@socketsecurity/lib/performance'\n *\n * const summary = getPerformanceSummary()\n * console.log(summary)\n * // {\n * // 'api-call': { count: 5, total: 1234, avg: 246.8, min: 100, max: 500 },\n * // 'file-read': { count: 10, total: 50, avg: 5, min: 2, max: 15 }\n * // }\n */\nexport function getPerformanceSummary(): Record<\n string,\n {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n> {\n const summary: Record<\n string,\n { count: number; total: number; min: number; max: number }\n > = Object.create(null)\n\n for (const metric of performanceMetrics) {\n const { duration, operation } = metric\n\n if (!summary[operation]) {\n summary[operation] = {\n count: 0,\n total: 0,\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n }\n }\n\n const stats = summary[operation] as {\n count: number\n total: number\n min: number\n max: number\n }\n stats.count++\n stats.total += duration\n stats.min = Math.min(stats.min, duration)\n stats.max = Math.max(stats.max, duration)\n }\n\n // Calculate averages and return with proper typing\n const result: Record<\n string,\n { count: number; total: number; avg: number; min: number; max: number }\n > = Object.create(null)\n\n for (const { 0: operation, 1: stats } of Object.entries(summary)) {\n result[operation] = {\n count: stats.count,\n total: Math.round(stats.total * 100) / 100,\n avg: Math.round((stats.total / stats.count) * 100) / 100,\n min: Math.round(stats.min * 100) / 100,\n max: Math.round(stats.max * 100) / 100,\n }\n }\n\n return result\n}\n\n/**\n * Print performance summary to console.\n * Only prints when DEBUG=perf is enabled.\n *\n * @example\n * import { printPerformanceSummary } from '@socketsecurity/lib/performance'\n *\n * printPerformanceSummary()\n * // Performance Summary:\n * // api-call: 5 calls, avg 246.8ms (min 100ms, max 500ms, total 1234ms)\n * // file-read: 10 calls, avg 5ms (min 2ms, max 15ms, total 50ms)\n */\nexport function printPerformanceSummary(): void {\n if (!isPerfEnabled() || performanceMetrics.length === 0) {\n return\n }\n\n const summary = getPerformanceSummary()\n const operations = Object.keys(summary).sort()\n\n debugLog('[perf]\\n=== Performance Summary ===')\n\n for (const operation of operations) {\n const stats = summary[operation] as {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n debugLog(\n `[perf] ${operation}: ${stats.count} calls, avg ${stats.avg}ms (min ${stats.min}ms, max ${stats.max}ms, total ${stats.total}ms)`,\n )\n }\n\n debugLog('[perf] =========================\\n')\n}\n\n/**\n * Mark a checkpoint in performance tracking.\n * Useful for tracking progress through complex operations.\n *\n * @param checkpoint - Name of the checkpoint\n * @param metadata - Optional metadata\n *\n * @example\n * import { perfCheckpoint } from '@socketsecurity/lib/performance'\n *\n * perfCheckpoint('start-scan')\n * // ... do work ...\n * perfCheckpoint('fetch-packages', { count: 50 })\n * // ... do work ...\n * perfCheckpoint('analyze-issues', { issueCount: 10 })\n * perfCheckpoint('end-scan')\n */\nexport function perfCheckpoint(\n checkpoint: string,\n metadata?: Record<string, unknown>,\n): void {\n if (!isPerfEnabled()) {\n return\n }\n\n const metric: PerformanceMetrics = {\n operation: `checkpoint:${checkpoint}`,\n duration: 0,\n timestamp: Date.now(),\n ...(metadata ? { metadata } : {}),\n }\n\n performanceMetrics.push(metric)\n debugLog(`[perf] [CHECKPOINT] ${checkpoint}`)\n}\n\n/**\n * Track memory usage at a specific point.\n * Only available when DEBUG=perf is enabled.\n *\n * @param label - Label for this memory snapshot\n * @returns Memory usage in MB\n *\n * @example\n * import { trackMemory } from '@socketsecurity/lib/performance'\n *\n * const memBefore = trackMemory('before-operation')\n * await heavyOperation()\n * const memAfter = trackMemory('after-operation')\n * console.log(`Memory increased by ${memAfter - memBefore}MB`)\n */\nexport function trackMemory(label: string): number {\n if (!isPerfEnabled()) {\n return 0\n }\n\n const usage = process.memoryUsage()\n const heapUsedMB = Math.round((usage.heapUsed / 1024 / 1024) * 100) / 100\n\n debugLog(`[perf] [MEMORY] ${label}: ${heapUsedMB}MB heap used`)\n\n const metric: PerformanceMetrics = {\n operation: `checkpoint:memory:${label}`,\n duration: 0,\n timestamp: Date.now(),\n metadata: {\n heapUsed: heapUsedMB,\n heapTotal: Math.round((usage.heapTotal / 1024 / 1024) * 100) / 100,\n external: Math.round((usage.external / 1024 / 1024) * 100) / 100,\n },\n }\n\n performanceMetrics.push(metric)\n\n return heapUsedMB\n}\n\n/**\n * Create a performance report for the current execution.\n * Only available when DEBUG=perf is enabled.\n *\n * @returns Formatted performance report\n *\n * @example\n * import { generatePerformanceReport } from '@socketsecurity/lib/performance'\n *\n * console.log(generatePerformanceReport())\n * // \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n * // \u2551 Performance Report \u2551\n * // \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\n * //\n * // api-call:\n * // Calls: 5\n * // Avg: 246.8ms\n * // Min: 100ms\n * // Max: 500ms\n * // Total: 1234ms\n */\nexport function generatePerformanceReport(): string {\n if (!isPerfEnabled() || performanceMetrics.length === 0) {\n return '(no performance data collected - enable with DEBUG=perf)'\n }\n\n const summary = getPerformanceSummary()\n const operations = Object.keys(summary).sort()\n\n let report = '\\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\\n'\n report += '\u2551 Performance Report \u2551\\n'\n report += '\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D\\n\\n'\n\n for (const operation of operations) {\n const stats = summary[operation] as {\n count: number\n total: number\n avg: number\n min: number\n max: number\n }\n report += `${operation}:\\n`\n report += ` Calls: ${stats.count}\\n`\n report += ` Avg: ${stats.avg}ms\\n`\n report += ` Min: ${stats.min}ms\\n`\n report += ` Max: ${stats.max}ms\\n`\n report += ` Total: ${stats.total}ms\\n\\n`\n }\n\n const totalDuration = Object.values(summary).reduce(\n (sum, s) => sum + s.total,\n 0,\n )\n report += `Total measured time: ${Math.round(totalDuration * 100) / 100}ms\\n`\n\n return report\n}\n"],
|
|
5
5
|
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,8BAAAC,EAAA,0BAAAC,EAAA,0BAAAC,EAAA,YAAAC,EAAA,gBAAAC,EAAA,mBAAAC,EAAA,cAAAC,EAAA,4BAAAC,EAAA,gBAAAC,IAAA,eAAAC,EAAAZ,GAKA,IAAAa,EAAyB,mBAezB,MAAMC,EAA2C,CAAC,EAKlD,SAASC,GAAyB,CAChC,OAAO,QAAQ,IAAI,OAAU,SAAS,MAAM,GAAK,EACnD,CAiBO,SAASN,EACdO,EACAC,EACwD,CACxD,GAAI,CAACF,EAAc,EAEjB,MAAO,IAAM,CAAC,EAGhB,MAAMG,EAAQ,YAAY,IAAI,EAC9B,qBAAS,kBAAkBF,CAAS,EAAE,EAE9BG,GAAiD,CACvD,MAAMC,EAAW,YAAY,IAAI,EAAIF,EAC/BG,EAA6B,CACjC,UAAAL,EAEA,SAAU,KAAK,MAAMI,EAAW,GAAG,EAAI,IACvC,UAAW,KAAK,IAAI,EACpB,SAAU,CAAE,GAAGH,EAAU,GAAGE,CAAmB,CACjD,EAEAL,EAAmB,KAAKO,CAAM,KAC9B,YAAS,gBAAgBL,CAAS,MAAMK,EAAO,QAAQ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getPerformanceMetrics", "getPerformanceSummary", "measure", "measureSync", "perfCheckpoint", "perfTimer", "printPerformanceSummary", "trackMemory", "__toCommonJS", "import_debug", "performanceMetrics", "isPerfEnabled", "operation", "metadata", "start", "additionalMetadata", "duration", "metric", "fn", "stop", "result", "e", "summary", "stats", "operations", "checkpoint", "label", "usage", "heapUsedMB", "report", "totalDuration", "sum", "s"]
|
|
7
7
|
}
|
package/dist/spinner.d.ts
CHANGED
|
@@ -61,7 +61,7 @@ export type ShimmerInfo = ShimmerState & {
|
|
|
61
61
|
*
|
|
62
62
|
* @example
|
|
63
63
|
* ```ts
|
|
64
|
-
* import { Spinner } from '@socketsecurity/
|
|
64
|
+
* import { Spinner } from '@socketsecurity/lib/spinner'
|
|
65
65
|
*
|
|
66
66
|
* const spinner = Spinner({ text: 'Loading…' })
|
|
67
67
|
* spinner.start()
|
|
@@ -243,7 +243,7 @@ export declare function getCliSpinners(styleName?: string | undefined): SpinnerS
|
|
|
243
243
|
*
|
|
244
244
|
* @example
|
|
245
245
|
* ```ts
|
|
246
|
-
* import { Spinner } from '@socketsecurity/
|
|
246
|
+
* import { Spinner } from '@socketsecurity/lib/spinner'
|
|
247
247
|
*
|
|
248
248
|
* // Basic usage
|
|
249
249
|
* const spinner = Spinner({ text: 'Loading data…' })
|
|
@@ -279,7 +279,7 @@ export declare function Spinner(options?: SpinnerOptions | undefined): Spinner;
|
|
|
279
279
|
*
|
|
280
280
|
* @example
|
|
281
281
|
* ```ts
|
|
282
|
-
* import { getDefaultSpinner } from '@socketsecurity/
|
|
282
|
+
* import { getDefaultSpinner } from '@socketsecurity/lib/spinner'
|
|
283
283
|
*
|
|
284
284
|
* const spinner = getDefaultSpinner()
|
|
285
285
|
* spinner.start('Loading…')
|
|
@@ -294,11 +294,11 @@ export declare function getDefaultSpinner(): ReturnType<typeof Spinner>;
|
|
|
294
294
|
* @example
|
|
295
295
|
* ```ts
|
|
296
296
|
* // Old (deprecated):
|
|
297
|
-
* import { spinner } from '@socketsecurity/
|
|
297
|
+
* import { spinner } from '@socketsecurity/lib/spinner'
|
|
298
298
|
* spinner.start('Loading…')
|
|
299
299
|
*
|
|
300
300
|
* // New (recommended):
|
|
301
|
-
* import { getDefaultSpinner } from '@socketsecurity/
|
|
301
|
+
* import { getDefaultSpinner } from '@socketsecurity/lib/spinner'
|
|
302
302
|
* const spinner = getDefaultSpinner()
|
|
303
303
|
* spinner.start('Loading…')
|
|
304
304
|
* ```
|
|
@@ -334,7 +334,7 @@ export type WithSpinnerOptions<T> = {
|
|
|
334
334
|
*
|
|
335
335
|
* @example
|
|
336
336
|
* ```ts
|
|
337
|
-
* import { Spinner, withSpinner } from '@socketsecurity/
|
|
337
|
+
* import { Spinner, withSpinner } from '@socketsecurity/lib/spinner'
|
|
338
338
|
*
|
|
339
339
|
* const spinner = Spinner()
|
|
340
340
|
*
|
|
@@ -384,7 +384,7 @@ export type WithSpinnerRestoreOptions<T> = {
|
|
|
384
384
|
*
|
|
385
385
|
* @example
|
|
386
386
|
* ```ts
|
|
387
|
-
* import { getDefaultSpinner, withSpinnerRestore } from '@socketsecurity/
|
|
387
|
+
* import { getDefaultSpinner, withSpinnerRestore } from '@socketsecurity/lib/spinner'
|
|
388
388
|
*
|
|
389
389
|
* const spinner = getDefaultSpinner()
|
|
390
390
|
* const wasSpinning = spinner.isSpinning
|
|
@@ -432,7 +432,7 @@ export type WithSpinnerSyncOptions<T> = {
|
|
|
432
432
|
*
|
|
433
433
|
* @example
|
|
434
434
|
* ```ts
|
|
435
|
-
* import { Spinner, withSpinnerSync } from '@socketsecurity/
|
|
435
|
+
* import { Spinner, withSpinnerSync } from '@socketsecurity/lib/spinner'
|
|
436
436
|
*
|
|
437
437
|
* const spinner = Spinner()
|
|
438
438
|
*
|