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

fxy060608's avatar
fxy060608 已提交
5 6 7 8 9 10 11
const nixSlashes = (x) => x.replace(/\\/g, '/');
const sourcemapCatch = {};
function stacktracey(stacktrace, opts) {
    const parseStack = [];
    const stack = opts.preset.parseStacktrace(stacktrace);
    stack.items.forEach((item, index) => {
        const fn = () => {
D
DCloud_LXH 已提交
12
            const { line = 0, column = 0, file, fileName, fileRelative } = item;
fxy060608's avatar
fxy060608 已提交
13 14
            try {
                return opts.preset
D
DCloud_LXH 已提交
15
                    .getSourceMapContent(file, fileName, fileRelative)
fxy060608's avatar
fxy060608 已提交
16
                    .then((content) => {
D
DCloud_LXH 已提交
17 18
                    if (content) {
                        return getConsumer(content).then((consumer) => {
fxy060608's avatar
fxy060608 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
                            const sourceMapContent = parseSourceMapContent(consumer, {
                                line,
                                column,
                            });
                            if (sourceMapContent) {
                                const { source, sourcePath, sourceLine, sourceColumn, fileName = '', } = sourceMapContent;
                                stack.items[index] = Object.assign({}, item, {
                                    file: source,
                                    line: sourceLine,
                                    column: sourceColumn,
                                    fileShort: sourcePath,
                                    fileRelative: sourcePath,
                                    fileName,
                                });
                            }
                        });
D
DCloud_LXH 已提交
35
                    }
fxy060608's avatar
fxy060608 已提交
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
                });
            }
            catch (error) {
                return Promise.resolve();
            }
        };
        parseStack.push(fn());
    });
    return new Promise((resolve, reject) => {
        Promise.all(parseStack)
            .then(() => {
            const parseError = opts.preset.asTableStacktrace({
                stack,
                maxColumnWidths: {
                    callee: 999,
                    file: 999,
                    sourceLine: 999,
                },
                stacktrace,
            });
            resolve(parseError);
        })
            .catch(() => {
            resolve(stacktrace);
        });
    });
}
D
DCloud_LXH 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75
function getConsumer(content) {
    return new Promise((resolve, reject) => {
        if (SourceMapConsumer.with) {
            SourceMapConsumer.with(content, null, (consumer) => {
                resolve(consumer);
            });
        }
        else {
            // @ts-ignore
            resolve(SourceMapConsumer(content));
        }
    });
}
fxy060608's avatar
fxy060608 已提交
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
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) => {
                                sourcemapCatch[sourcemapUrl] = res.data;
                                resolve(sourcemapCatch[sourcemapUrl]);
                            },
                        });
                    }
                    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,
        };
    }
}
function uniStracktraceyPreset(opts) {
    const { base, sourceRoot } = opts;
    return {
D
DCloud_LXH 已提交
123
        parseSourceMapUrl(file, fileName, fileRelative) {
fxy060608's avatar
fxy060608 已提交
124
            // 组合 sourceMapUrl
D
DCloud_LXH 已提交
125 126 127
            if (fileRelative.indexOf('(') !== -1)
                fileRelative = fileRelative.match(/\((.*)/)[1];
            if (!base || !fileRelative)
fxy060608's avatar
fxy060608 已提交
128 129
                return '';
            if (sourceRoot) {
D
DCloud_LXH 已提交
130
                return `${fileRelative.replace(sourceRoot, base + '/')}.map`;
fxy060608's avatar
fxy060608 已提交
131
            }
D
DCloud_LXH 已提交
132
            return `${base}/${fileRelative}.map`;
fxy060608's avatar
fxy060608 已提交
133
        },
D
DCloud_LXH 已提交
134 135
        getSourceMapContent(file, fileName, fileRelative) {
            return Promise.resolve(getSourceMapContent(this.parseSourceMapUrl(file, fileName, fileRelative)));
fxy060608's avatar
fxy060608 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
        },
        parseStacktrace(stacktrace) {
            return new StackTracey(stacktrace);
        },
        asTableStacktrace({ maxColumnWidths, stacktrace, stack }) {
            const errorName = stacktrace.split('\n')[0];
            return ((errorName.indexOf('at') === -1 ? `${errorName}\n` : '') +
                (stack.asTable ? stack.asTable({ maxColumnWidths }) : ''));
        },
    };
}
function utsStracktraceyPreset(opts) {
    const { base, sourceRoot } = opts;
    let errStack = [];
    return {
D
DCloud_LXH 已提交
151
        parseSourceMapUrl(file, fileName, fileRelative) {
fxy060608's avatar
fxy060608 已提交
152 153 154 155 156 157
            // 组合 sourceMapUrl
            if (sourceRoot) {
                return `${file.replace(sourceRoot, base + '/')}.map`;
            }
            return `${base}/${file}.map`;
        },
D
DCloud_LXH 已提交
158
        getSourceMapContent(file, fileName, fileRelative) {
fxy060608's avatar
fxy060608 已提交
159
            // 根据 base,filename 组合 sourceMapUrl
D
DCloud_LXH 已提交
160
            return Promise.resolve(getSourceMapContent(this.parseSourceMapUrl(file, fileName, fileRelative)));
fxy060608's avatar
fxy060608 已提交
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
        },
        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,
            };
        },
        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 已提交
214 215 216
}

export { stacktracey, uniStracktraceyPreset, utsStracktraceyPreset };