Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | 47x 2647x 2647x 4101x 4101x 1734x 2367x 2047x 2047x 4x 320x 44x 44x 44x 276x 7x 6x 6x 1x 269x 8x 7x 7x 1x 261x 4x 4x 257x 1x 1x 2x 2x 1x 256x 3x 253x 16x 237x 237x 24x 23x 9x 9x 8x 9x 23x 847x 1x 213x 213x 7x 206x 200x 200x 200x 4x 196x 599x 599x 196x 8x 8x 8x 8x 120x 120x 120x 2x 2x 8x 6x 6x 8x 188x 188x 479x 479x 188x 6x 2647x 2647x 2647x 2343x 242x 62x 62x 4x 4x 4x 4x 2647x 2647x 2647x 47x 3749x 3749x 1x | import { emptyRecord } from '../common/empty.ts';
import { exhaustiveCheck } from '../common/exhaustive-check.ts';
/**
* Options for the stringify function
*/
export type StringifyOptions = {
/**
* Whether to include stack traces for errors.
*
* @default false
*/
readonly includeStack?: boolean;
/**
* Whether to prettify the output with indentation.
*
* @default false
*/
readonly pretty?: boolean;
/**
* Maximum depth for recursive object serialization. Use a negative number to disable the depth limit.
*
* @default 5
*/
readonly maxDepth?: number;
/**
* When true, uses `toLocaleString()` instead of `toISOString()` to format dates using the local locale instead of the
* default ISO format.
*
* @default false
*/
readonly useLocale?: boolean;
/**
* Maximum number of array elements to show before truncating. Use a negative number to disable the array element
* limit.
*
* @default 100
*/
readonly maxArrayElements?: number;
/**
* When true, excludes the array truncation element.
*
* By default, stringify adds a truncation element like `'...(4)'` to indicate that an array has been truncated due to
* the `maxArrayElements` option.
*
* @default false
*/
readonly excludeArrayTruncationElement?: boolean;
/**
* Maximum number of object properties to show before truncating. Use a negative number to disable the object property
* limit.
*
* @default 50
*/
readonly maxProperties?: number;
/**
* When true, excludes the object truncation property.
*
* By default, stringify adds a truncation property like `'...(4)':'...'` to indicate that an object has been
* truncated due to the `maxProperties` option.
*
* @default false
*/
readonly excludeObjectTruncationProperty?: boolean;
};
/**
* Converts a given value into a string representation that is appropriate for log events. This function is guaranteed
* to never throw an error, making it safe for logging contexts.
*
* @example Simple usage
*
* ```ts
* import { stringify } from 'emitnlog/utils';
* const str = stringify({ key: 'value' });
* ```
*
* @example With options
*
* ```ts
* import { stringify } from 'emitnlog/utils';
*
* // Include stack trace for errors
* const error = new Error('Something went wrong');
* const strWithStack = stringify(error, { includeStack: true });
*
* // Pretty format objects
* const strPretty = stringify(complexObject, { pretty: true });
*
* // Format dates using locale
* const date = new Date();
* const localDate = stringify(date, { useLocale: true });
* ```
*
* @param {unknown} value - The value to convert into a string.
* @param {StringifyOptions} [options] - Optional configuration for stringification.
* @returns {string} The string representation of the value.
*/
export const stringify = (value: unknown, options?: StringifyOptions): string => {
const {
includeStack = false,
pretty = false,
maxDepth = 5,
useLocale = false,
maxArrayElements = 100,
maxProperties = 50,
} = options ?? emptyRecord<string, undefined>();
const prepare = (val: unknown, depth = 0, seen = new WeakSet()): unknown => {
const type = typeof val;
switch (type) {
case 'string':
case 'number':
case 'bigint':
case 'boolean':
case 'undefined':
case 'symbol':
case 'function':
return val;
case 'object': {
if (safeInstanceOf(val, Date)) {
try {
return useLocale ? val.toLocaleString() : val.toISOString();
} catch {
return '[Invalid Date]';
}
}
if (safeInstanceOf(val, Error)) {
try {
const message = val.message || val.name || '[unknown error]';
return includeStack && val.stack ? `${message}\n${val.stack}` : message;
} catch {
return '[Invalid Error]';
}
}
if (safeInstanceOf(val, Map)) {
if (maxDepth < 0 || depth < maxDepth) {
try {
return prepare(Object.fromEntries(val), depth + 1, seen);
} catch {
// ignore
}
}
return `Map(${val.size})`;
}
if (safeInstanceOf(val, Set)) {
if (maxDepth < 0 || depth < maxDepth) {
try {
return prepare(Array.from(val), depth + 1, seen);
} catch {
// ignore
}
}
return `Set(${val.size})`;
}
if (safeInstanceOf(val, RegExp)) {
try {
return val.toString();
} catch {
return '[RegExp]';
}
}
/* eslint-disable no-undef */
if (
typeof Headers !== 'undefined' &&
safeInstanceOf(val, Headers) &&
'forEach' in val &&
typeof val.forEach === 'function'
) {
const record: Record<string, string> = {};
val.forEach((v, key) => {
Eif (typeof key === 'string' && typeof v === 'string') {
record[key] = v;
}
});
return prepare(record, depth + 1, seen);
}
/* eslint-enable no-undef */
if (!val) {
return val;
}
if (seen.has(val)) {
return '[Circular Reference]';
}
seen.add(val);
if (Array.isArray(val)) {
if (maxDepth < 0 || depth < maxDepth) {
if (maxArrayElements >= 0 && val.length > maxArrayElements) {
const truncatedArray = val.slice(0, maxArrayElements);
if (!options?.excludeArrayTruncationElement) {
truncatedArray.push(`...(${val.length - maxArrayElements})`);
}
val = truncatedArray;
}
try {
return (val as unknown[]).map((item) => prepare(item, depth + 1, seen));
} catch {
// ignore
}
}
return `Array(${(val as unknown[]).length})`;
}
// eslint-disable-next-line @typescript-eslint/no-base-to-string
const stringValue = String(val);
if (stringValue !== '[object Object]') {
return stringValue;
}
if (maxDepth < 0 || depth < maxDepth) {
try {
const keys = Object.keys(val);
if (!keys.length) {
return {};
}
const prepareValue = (key: string) => {
const v = (val as Record<string, unknown>)[key];
return prepare(v, depth + 1, seen);
};
if (maxProperties >= 0 && keys.length > maxProperties) {
const length = keys.length;
const truncatedObj: Record<string, unknown> = {};
let max = maxProperties;
for (let i = 0; i < max; i++) {
const key = keys[i];
try {
truncatedObj[key] = prepareValue(key);
} catch {
Eif (max < length) {
max++;
}
}
}
if (length > max && !options?.excludeObjectTruncationProperty) {
const truncatedKey = `...(${length - max})`;
truncatedObj[truncatedKey] = '...';
}
return truncatedObj;
}
const result: Record<string, unknown> = {};
for (const key of keys) {
try {
result[key] = prepareValue(key);
} catch {
// ignore
}
}
return result;
} catch {
// ignore
}
}
return '[object Object]';
}
default:
exhaustiveCheck(type);
return val;
}
};
const convert = (val: unknown): string => {
const type = typeof val;
switch (type) {
case 'string':
return val as string;
case 'number':
case 'bigint':
case 'boolean':
case 'undefined':
case 'symbol':
case 'function':
return String(val);
case 'object': {
try {
return pretty ? JSON.stringify(val, undefined, 2) : JSON.stringify(val);
} catch {
Iif (Array.isArray(val)) {
return `Array(${val.length})`;
}
try {
const keys = Object.keys(val as object);
return `{${keys.join(', ')}}`;
} catch {
return String(val);
}
}
}
default:
exhaustiveCheck(type);
return String(val);
}
};
try {
const converted = prepare(value);
return convert(converted);
} catch {
return '[Stringify Error]';
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const safeInstanceOf = <C extends abstract new (...args: any) => any>(
value: unknown,
constructor: C,
): value is InstanceType<C> => {
try {
return value instanceof constructor;
} catch {
return false;
}
};
|