uni-stacktracey.es.js 21.0 KB
Newer Older
D
DCloud_LXH 已提交
1 2 3
import fs from 'fs';
import { SourceMapConsumer } from 'source-map';

4
/*  ------------------------------------------------------------------------ */
fxy060608's avatar
fxy060608 已提交
5 6 7 8
const O = Object, isBrowser = 
/* eslint-disable */
typeof window !== 'undefined' &&
    /* eslint-disable */
9
    window.window === window &&
fxy060608's avatar
fxy060608 已提交
10
    /* eslint-disable */
11 12 13 14
    window.navigator, nodeRequire = isBrowser ? null : module.require, // to prevent bundlers from expanding the require call
lastOf = (x) => x[x.length - 1], nixSlashes$1 = (x) => x.replace(/\\/g, '/'), pathRoot = isBrowser ? window.location.href : nixSlashes$1(process.cwd()) + '/';
/*  ------------------------------------------------------------------------ */
class StackTracey {
15
    constructor(input, uniPlatform, offset) {
16 17 18 19 20 21 22 23 24 25 26 27 28 29
        this.itemsHeader = [];
        this.isMP = false;
        const originalInput = input, isParseableSyntaxError = input && input instanceof SyntaxError && !isBrowser;
        /*  new StackTracey ()            */
        if (!input) {
            input = new Error();
            offset = offset === undefined ? 1 : offset;
        }
        /*  new StackTracey (Error)      */
        if (input instanceof Error) {
            input = input.stack || '';
        }
        /*  new StackTracey (string)     */
        if (typeof input === 'string') {
30
            this.isMP = uniPlatform === 'mp-weixin';
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
            input = this.rawParse(input)
                .slice(offset)
                .map((x) => this.extractEntryMetadata(x));
        }
        /*  new StackTracey (array)      */
        if (Array.isArray(input)) {
            if (isParseableSyntaxError) {
                const rawLines = nodeRequire('util')
                    .inspect(originalInput)
                    .split('\n'), fileLine = rawLines[0].split(':'), line = fileLine.pop(), file = fileLine.join(':');
                if (file) {
                    input.unshift({
                        file: nixSlashes$1(file),
                        line: line,
                        column: (rawLines[2] || '').indexOf('^') + 1,
                        sourceLine: rawLines[1],
                        callee: '(syntax error)',
                        syntaxError: true,
                    });
                }
            }
            this.items = input;
        }
        else {
            this.items = [];
        }
    }
    extractEntryMetadata(e) {
        const decomposedPath = this.decomposePath(e.file || '');
        const fileRelative = decomposedPath[0];
        const externalDomain = decomposedPath[1];
        return O.assign(e, {
            calleeShort: e.calleeShort || lastOf((e.callee || '').split('.')),
            fileRelative: fileRelative,
            fileShort: this.shortenPath(fileRelative),
            fileName: lastOf((e.file || '').split('/')),
            thirdParty: this.isThirdParty(fileRelative, externalDomain) && !e.index,
            externalDomain: externalDomain,
        });
    }
    shortenPath(relativePath) {
        return relativePath
            .replace(/^node_modules\//, '')
            .replace(/^webpack\/bootstrap\//, '')
            .replace(/^__parcel_source_root\//, '');
    }
    decomposePath(fullPath) {
        let result = fullPath;
        if (isBrowser)
            result = result.replace(pathRoot, '');
81
        const externalDomainMatch = result.match(/^(http|https)\:\/\/?([^\/]+)\/{1,}(.*)/);
82 83 84 85
        const externalDomain = externalDomainMatch
            ? externalDomainMatch[2]
            : undefined;
        result = externalDomainMatch ? externalDomainMatch[3] : result;
86
        // if (!isBrowser) result = nodeRequire!('path').relative(pathRoot, result)
87 88 89 90 91 92 93 94 95 96 97
        return [
            nixSlashes$1(result).replace(/^.*\:\/\/?\/?/, ''),
            externalDomain,
        ];
    }
    isThirdParty(relativePath, externalDomain) {
        if (this.isMP) {
            if (typeof externalDomain === 'undefined')
                return false;
            return externalDomain !== 'usr';
        }
98 99 100 101
        return (
        // 由于 hello-uniapp web 端报错携带 hellouniapp.dcloud.net.cn
        // externalDomain ||
        relativePath[0] === '~' || // webpack-specific heuristic
102 103 104 105 106 107 108 109 110
            relativePath[0] === '/' || // external source
            relativePath.indexOf('@dcloudio') !== -1 ||
            relativePath.indexOf('webpack/bootstrap') === 0);
    }
    rawParse(str) {
        const lines = (str || '').split('\n');
        const entries = lines.map((line, index) => {
            line = line.trim();
            let callee, fileLineColumn = [], native, planA, planB;
111 112 113
            if (line.indexOf('file:') !== -1) {
                line = line.replace(/file:\/\/(.*)www/, 'file://');
            }
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
            if ((planA = line.match(/at (.+) \(eval at .+ \((.+)\), .+\)/)) || // eval calls
                (planA = line.match(/at (.+) \((.+)\)/)) ||
                (line.slice(0, 3) !== 'at ' && (planA = line.match(/(.*)@(.*)/)))) {
                this.itemsHeader.push('%StacktraceyItem%');
                callee = planA[1];
                native = planA[2] === 'native';
                fileLineColumn = (planA[2].match(/(.*):(\d+):(\d+)/) ||
                    planA[2].match(/(.*):(\d+)/) ||
                    planA[2].match(/\[(.*)\]/) ||
                    []).slice(1);
            }
            else if ((planB = line.match(/^(at\s*)*(.*)\s+(.+):(\d+):(\d+)/))) {
                this.itemsHeader.push('%StacktraceyItem%');
                callee = planB[2].trim();
                fileLineColumn = planB.slice(3);
            }
            else {
                this.itemsHeader.push(line);
                return undefined;
            }
            /*  Detect things like Array.reduce
                TODO: detect more built-in types            */
            if (callee && !fileLineColumn[0]) {
                const type = callee.split('.')[0];
                if (type === 'Array') {
                    native = true;
                }
            }
            return {
                beforeParse: line,
                callee: callee || '',
fxy060608's avatar
fxy060608 已提交
145
                /* eslint-disable */
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
                index: isBrowser && fileLineColumn[0] === window.location.href,
                native: native || false,
                file: nixSlashes$1(fileLineColumn[0] || ''),
                line: parseInt(fileLineColumn[1] || '', 10) || undefined,
                column: parseInt(fileLineColumn[2] || '', 10) || undefined,
            };
        });
        return entries.filter((x) => x !== undefined);
    }
    maxColumnWidths() {
        return {
            callee: 30,
            file: 60,
            sourceLine: 80,
        };
    }
    asTable(opts) {
        const maxColumnWidths = (opts && opts.maxColumnWidths) || this.maxColumnWidths();
        const trimmed = this
            .filter((e) => !e.thirdParty)
            .map((e) => parseItem(e, maxColumnWidths, this.isMP));
        const trimmedThirdParty = this
            .filter((e) => e.thirdParty)
            .map((e) => parseItem(e, maxColumnWidths, this.isMP));
        return {
            items: trimmed.items,
            thirdPartyItems: trimmedThirdParty.items,
        };
    }
}
const trimEnd = (s, n) => s && (s.length > n ? s.slice(0, n - 1) + '' : s);
const trimStart = (s, n) => s && (s.length > n ? '' + s.slice(-(n - 1)) : s);
function parseItem(e, maxColumnWidths, isMP) {
179 180 181
    if (!e.parsed) {
        return e.beforeParse;
    }
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
    const filePath = (isMP ? e.file && e.file : e.fileShort && e.fileShort) +
        `${e.line ? ':' + e.line : ''}` +
        `${e.column ? ':' + e.column : ''}`;
    return [
        'at ' + trimEnd(isMP ? e.callee : e.calleeShort, maxColumnWidths.callee),
        trimStart(filePath || '', maxColumnWidths.file),
        trimEnd((e.sourceLine || '').trim() || '', maxColumnWidths.sourceLine),
    ];
}
['map', 'filter', 'slice', 'concat'].forEach((method) => {
    StackTracey.prototype[method] = function ( /*...args */) {
        // no support for ...args in Node v4 :(
        return new StackTracey(this.items[method].apply(this.items, arguments));
    };
});
/*  ------------------------------------------------------------------------ */
var StackTracey$1 = StackTracey;

D
DCloud_LXH 已提交
200 201 202 203 204 205
// @ts-ignore
{
    // @ts-ignore
    if (SourceMapConsumer.initialize) {
        // @ts-ignore
        SourceMapConsumer.initialize({
D
DCloud_LXH 已提交
206
            'lib/mappings.wasm': 'https://unpkg.com/source-map@0.7.3/lib/mappings.wasm',
D
DCloud_LXH 已提交
207 208 209
        });
    }
}
fxy060608's avatar
fxy060608 已提交
210 211 212 213
const nixSlashes = (x) => x.replace(/\\/g, '/');
const sourcemapCatch = {};
function stacktracey(stacktrace, opts) {
    const stack = opts.preset.parseStacktrace(stacktrace);
214
    let parseStack = Promise.resolve();
fxy060608's avatar
fxy060608 已提交
215
    stack.items.forEach((item, index) => {
216
        const fn = (item, index) => {
D
DCloud_LXH 已提交
217
            const { line = 0, column = 0, file, fileName, fileRelative } = item;
218 219 220 221
            if (item.thirdParty) {
                return Promise.resolve();
            }
            function _getSourceMapContent(file, fileName, fileRelative) {
fxy060608's avatar
fxy060608 已提交
222
                return opts.preset
D
DCloud_LXH 已提交
223
                    .getSourceMapContent(file, fileName, fileRelative)
fxy060608's avatar
fxy060608 已提交
224
                    .then((content) => {
D
DCloud_LXH 已提交
225 226
                    if (content) {
                        return getConsumer(content).then((consumer) => {
227
                            return parseSourceMapContent(consumer, {
fxy060608's avatar
fxy060608 已提交
228 229 230 231
                                line,
                                column,
                            });
                        });
D
DCloud_LXH 已提交
232
                    }
fxy060608's avatar
fxy060608 已提交
233 234
                });
            }
235 236 237 238 239 240 241 242 243 244 245 246
            try {
                return _getSourceMapContent(file, fileName, fileRelative).then((sourceMapContent) => {
                    if (sourceMapContent) {
                        const { source, sourcePath, sourceLine, sourceColumn, fileName = '', } = sourceMapContent;
                        stack.items[index] = Object.assign({}, item, {
                            file: source,
                            line: sourceLine,
                            column: sourceColumn,
                            fileShort: sourcePath,
                            fileRelative: source,
                            fileName,
                            thirdParty: isThirdParty(sourcePath),
247
                            parsed: true,
248 249 250 251 252 253 254 255 256 257 258 259 260 261
                        });
                        /**
                         * 以 .js 结尾
                         * 包含 app-service.js 则需要再解析 两次
                         * 不包含 app-service.js 则无需再解析 一次
                         */
                        const curItem = stack.items[index];
                        if (stack.isMP &&
                            curItem.beforeParse.indexOf('app-service') !== -1) {
                            return fn(curItem, index);
                        }
                    }
                });
            }
fxy060608's avatar
fxy060608 已提交
262 263 264 265
            catch (error) {
                return Promise.resolve();
            }
        };
266 267 268 269 270 271 272
        parseStack = parseStack.then(() => {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    fn(item, index).then(resolve);
                }, 0);
            });
        });
fxy060608's avatar
fxy060608 已提交
273
    });
274 275
    const _promise = new Promise((resolve, reject) => {
        parseStack
fxy060608's avatar
fxy060608 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
            .then(() => {
            const parseError = opts.preset.asTableStacktrace({
                stack,
                maxColumnWidths: {
                    callee: 999,
                    file: 999,
                    sourceLine: 999,
                },
                stacktrace,
            });
            resolve(parseError);
        })
            .catch(() => {
            resolve(stacktrace);
        });
    });
292
    return _promise;
fxy060608's avatar
fxy060608 已提交
293
}
294 295 296
function isThirdParty(relativePath) {
    return relativePath.indexOf('@dcloudio') !== -1;
}
D
DCloud_LXH 已提交
297 298
function getConsumer(content) {
    return new Promise((resolve, reject) => {
299 300 301 302 303 304 305 306 307
        try {
            if (SourceMapConsumer.with) {
                SourceMapConsumer.with(content, null, (consumer) => {
                    resolve(consumer);
                });
            }
            else {
                // @ts-ignore
                const consumer = SourceMapConsumer(content);
D
DCloud_LXH 已提交
308
                resolve(consumer);
309
            }
D
DCloud_LXH 已提交
310
        }
311 312
        catch (error) {
            reject();
D
DCloud_LXH 已提交
313 314 315
        }
    });
}
fxy060608's avatar
fxy060608 已提交
316 317 318 319 320 321 322 323 324
function getSourceMapContent(sourcemapUrl) {
    try {
        return (sourcemapCatch[sourcemapUrl] ||
            (sourcemapCatch[sourcemapUrl] = new Promise((resolve, reject) => {
                try {
                    if (/^[http|https]+:/i.test(sourcemapUrl)) {
                        uni.request({
                            url: sourcemapUrl,
                            success: (res) => {
325 326 327 328 329 330 331 332 333 334
                                if (res.statusCode === 200) {
                                    sourcemapCatch[sourcemapUrl] = res.data;
                                    resolve(sourcemapCatch[sourcemapUrl]);
                                }
                                else {
                                    resolve((sourcemapCatch[sourcemapUrl] = ''));
                                }
                            },
                            fail() {
                                resolve((sourcemapCatch[sourcemapUrl] = ''));
fxy060608's avatar
fxy060608 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
                            },
                        });
                    }
                    else {
                        sourcemapCatch[sourcemapUrl] = fs.readFileSync(sourcemapUrl, 'utf-8');
                        resolve(sourcemapCatch[sourcemapUrl]);
                    }
                }
                catch (error) {
                    resolve('');
                }
            })));
    }
    catch (error) {
        return '';
    }
}
function parseSourceMapContent(consumer, obj) {
    // source -> 'uni-app:///node_modules/@sentry/browser/esm/helpers.js'
    const { source, line: sourceLine, column: sourceColumn, } = consumer.originalPositionFor(obj);
    if (source) {
        const sourcePathSplit = source.split('/');
        const sourcePath = sourcePathSplit.slice(3).join('/');
        const fileName = sourcePathSplit.pop();
        return {
            source,
            sourcePath,
            sourceLine: sourceLine === null ? 0 : sourceLine,
            sourceColumn: sourceColumn === null ? 0 : sourceColumn,
            fileName,
        };
    }
}
368
function joinItem(item) {
369 370 371
    if (typeof item === 'string') {
        return item;
    }
372 373 374 375 376
    const a = item[0];
    const b = item[1] ? `  ${item[1]}` : '';
    const c = item[2] ? ` ${item[2]}` : '';
    return `${a}${b}${c}`;
}
fxy060608's avatar
fxy060608 已提交
377
function uniStracktraceyPreset(opts) {
378
    const { base, sourceRoot, splitThirdParty, uniPlatform } = opts;
379
    let stack;
fxy060608's avatar
fxy060608 已提交
380
    return {
381 382 383 384 385 386 387 388
        /**
         *
         * 微信特殊处理
         * 微信解析步骤:
         *    1. //usr/app-service.js -> 'weixin/__APP__/app-service.map.map'
         *    2. //usr/pages/API/app-service.js -> 'weixin/pages/API/app-service.map.map'
         *    3. uni-list-item/uni-list-item.js -> ${base}/uni-list-item/uni-list-item.js.map
         */
D
DCloud_LXH 已提交
389
        parseSourceMapUrl(file, fileName, fileRelative) {
fxy060608's avatar
fxy060608 已提交
390
            // 组合 sourceMapUrl
D
DCloud_LXH 已提交
391 392 393
            if (fileRelative.indexOf('(') !== -1)
                fileRelative = fileRelative.match(/\((.*)/)[1];
            if (!base || !fileRelative)
fxy060608's avatar
fxy060608 已提交
394 395
                return '';
            if (sourceRoot) {
D
DCloud_LXH 已提交
396
                return `${fileRelative.replace(sourceRoot, base + '/')}.map`;
fxy060608's avatar
fxy060608 已提交
397
            }
398 399 400
            let baseAfter = '';
            if (stack.isMP) {
                if (fileRelative.indexOf('app-service.js') !== -1) {
401
                    baseAfter = (base.match(/\w$/) ? '/' : '') + '__WEIXIN__';
402
                    if (fileRelative === fileName) {
fxy060608's avatar
fxy060608 已提交
403
                        baseAfter += '/__APP__';
404 405 406 407 408 409 410
                    }
                    fileRelative = fileRelative.replace('.js', '.map');
                }
                if (baseAfter && !!fileRelative.match(/^\w/))
                    baseAfter += '/';
            }
            return `${base}${baseAfter}${fileRelative}.map`;
fxy060608's avatar
fxy060608 已提交
411
        },
D
DCloud_LXH 已提交
412
        getSourceMapContent(file, fileName, fileRelative) {
413 414 415 416 417
            if (stack.isMP && fileRelative.indexOf('.js') === -1) {
                return Promise.resolve('');
            }
            const sourcemapUrl = this.parseSourceMapUrl(file, fileName, fileRelative);
            return Promise.resolve(getSourceMapContent(sourcemapUrl));
fxy060608's avatar
fxy060608 已提交
418 419
        },
        parseStacktrace(stacktrace) {
420
            stack = new StackTracey$1(stacktrace, uniPlatform);
421
            return stack;
fxy060608's avatar
fxy060608 已提交
422 423 424
        },
        asTableStacktrace({ maxColumnWidths, stacktrace, stack }) {
            const errorName = stacktrace.split('\n')[0];
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
            const lines = stack.asTable
                ? stack.asTable(maxColumnWidths ? { maxColumnWidths } : undefined)
                : { items: [], thirdPartyItems: [] };
            if (lines.items.length || lines.thirdPartyItems.length) {
                const { items: stackLines, thirdPartyItems: stackThirdPartyLines } = lines;
                const userError = stack.itemsHeader
                    .map((item) => {
                    if (item === '%StacktraceyItem%') {
                        const _stack = stackLines.shift();
                        return _stack ? joinItem(_stack) : '';
                    }
                    return item;
                })
                    .filter(Boolean)
                    .join('\n');
                const thirdParty = stackThirdPartyLines.length
                    ? stackThirdPartyLines.map(joinItem).join('\n')
                    : '';
                if (splitThirdParty) {
                    return {
                        userError,
                        thirdParty,
                    };
                }
                return userError + '\n' + thirdParty;
            }
            else {
452 453 454 455 456 457
                if (splitThirdParty) {
                    return {
                        userError: errorName,
                        thirdParty: '',
                    };
                }
458 459
                return errorName;
            }
fxy060608's avatar
fxy060608 已提交
460 461 462 463 464 465 466
        },
    };
}
function utsStracktraceyPreset(opts) {
    const { base, sourceRoot } = opts;
    let errStack = [];
    return {
D
DCloud_LXH 已提交
467
        parseSourceMapUrl(file, fileName, fileRelative) {
fxy060608's avatar
fxy060608 已提交
468 469 470 471 472 473
            // 组合 sourceMapUrl
            if (sourceRoot) {
                return `${file.replace(sourceRoot, base + '/')}.map`;
            }
            return `${base}/${file}.map`;
        },
D
DCloud_LXH 已提交
474
        getSourceMapContent(file, fileName, fileRelative) {
fxy060608's avatar
fxy060608 已提交
475
            // 根据 base,filename 组合 sourceMapUrl
D
DCloud_LXH 已提交
476
            return Promise.resolve(getSourceMapContent(this.parseSourceMapUrl(file, fileName, fileRelative)));
fxy060608's avatar
fxy060608 已提交
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
        },
        parseStacktrace(str) {
            const lines = (str || '').split('\n');
            const entries = lines
                .map((line, index) => {
                line = line.trim();
                let callee, fileLineColumn = [], planA, planB;
                if ((planA = line.match(/e: (.+\.kt)(.+\))*:\s*(.+)*/))) {
                    errStack.push('%StacktraceyItem%');
                    callee = 'e: ';
                    fileLineColumn = (planA[2].match(/.*:.*\((\d+).+?(\d+)\)/) || []).slice(1);
                }
                else {
                    errStack.push(line);
                    return undefined;
                }
                const fileName = planA[1]
                    ? (planB = planA[1].match(/(.*)*\/(.+)/) || [])[2] || ''
                    : '';
                return {
                    beforeParse: line,
                    callee: callee || '',
                    index: false,
                    native: false,
                    file: nixSlashes(planA[1] || ''),
                    line: parseInt(fileLineColumn[0] || '', 10) || undefined,
                    column: parseInt(fileLineColumn[1] || '', 10) || undefined,
                    fileName,
                    fileShort: planB ? planB[1] : '',
                    errMsg: planA[3] || '',
                    calleeShort: '',
                    fileRelative: '',
                    thirdParty: false,
                };
            })
                .filter((x) => x !== undefined);
            return {
                items: entries,
515
                itemsHeader: [],
fxy060608's avatar
fxy060608 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
            };
        },
        asTableStacktrace({ maxColumnWidths, stacktrace, stack }) {
            return errStack
                .map((item) => {
                if (item === '%StacktraceyItem%') {
                    const _stack = stack.items.shift();
                    if (_stack)
                        return `${_stack.callee}${_stack.file}: (${_stack.line}, ${_stack.column}): ${_stack.errMsg}`;
                }
                return item;
            })
                .join('\n');
        },
    };
D
DCloud_LXH 已提交
531 532 533
}

export { stacktracey, uniStracktraceyPreset, utsStracktraceyPreset };