Compare commits

..
1 Commits
Author SHA1 Message Date
Jonathan Chan 27a82a2ee7 1.5.2 2019-10-10 18:26:54 -07:00
117 changed files with 9899 additions and 29177 deletions
+4 -11
View File
@@ -1,20 +1,13 @@
module.exports = {
parser: '@typescript-eslint/parser',
parser: 'typescript-eslint-parser',
parserOptions: {
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
plugins: ['prettier', '@typescript-eslint', 'react-hooks'],
plugins: ['prettier'],
rules: {
'@typescript-eslint/explicit-function-return-type': 'off',
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': [
'error',
{
additionalHooks: '(useSelector|useAppSelector|useActionCreator)',
},
],
'prettier/prettier': 'error',
},
}
};
-43
View File
@@ -1,43 +0,0 @@
name: Node.js CI
on:
push:
branches:
- master
pull_request:
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [10.x, 12.x, 14.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
env:
CI: true
- name: Coveralls Parallel
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.github_token }}
flag-name: run-${{ matrix.node-version }}
parallel: true
finish:
needs: test
runs-on: ubuntu-latest
steps:
- name: Coveralls Finished
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.github_token }}
parallel-finished: true
+3
View File
@@ -0,0 +1,3 @@
language: node_js
node_js:
- '9'
+40 -107
View File
@@ -1,225 +1,158 @@
## Unreleased
## [1.11.0] - 2020-10-13
### Added
- Support remapping profiles using source maps [[#317](https://github.com/jlfwong/speedscope/pull/317)]
### Fixed
- Fix line & column numbers in imports from Chrome & Firefox [[#318](https://github.com/jlfwong/speedscope/pull/318)]
## [1.10.0] - 2020-09-29
### Added
- Support for importing profiles from Safari [[#300](https://github.com/jlfwong/speedscope/pull/300)] (by [@radex](https://github.com/radex))
### Fixed
- Fixed browser not opening on Windows when using the CLI [[#307](https://github.com/jlfwong/speedscope/pull/307)] (by [@spillerrec](https://github.com/spillerrec))
- Fixed import of UTF-16 encoded files w/ BOM [[#314](https://github.com/jlfwong/speedscope/pull/314)]
- Removed accidental dependency on React [[#315](https://github.com/jlfwong/speedscope/pull/315)]
## [1.9.0] - 2020-08-05
### Added
- Provide prev/next buttons to cycle through search results, make search results more visually prominen [[#304](https://github.com/jlfwong/speedscope/pull/304)]
### Fixed
- Fix accumulated errors in Chrome profile imports caused by zeroed negative timeDeltas [[#305](https://github.com/jlfwong/speedscope/pull/305)] (by [@taneliang](https://github.com/taneliang))
## [1.8.0] - 2020-07-19
### Added
- Added search highlighting in time order & left heavy views [[#297](https://github.com/jlfwong/speedscope/pull/297)]
### Fixed
- Fix performance issues for the caller/callee flamegraphs in the sandwich view [[#296](https://github.com/jlfwong/speedscope/pull/296)]
## [1.7.0] - 2020-07-13
### Added
- Introduced filtering via Ctrl+F/Cmd+F into the sandwich view [[#293](https://github.com/jlfwong/speedscope/pull/293)]
## [1.6.0] - 2020-05-30
### Added
- Improved profile/thread selection UI [[#282](https://github.com/jlfwong/speedscope/pull/282)]
### Fixed
- Crash instead of incorrectly interpreting profiles with incorrectly ordered events [[#273](https://github.com/jlfwong/speedscope/pull/273)]
- A large refactor to upgrade to Preact X was performed [[#267](https://github.com/jlfwong/speedscope/pull/267)]
## [1.5.3] - 2020-01-16
### Fixed
- Bump dependency versions to unbreak build [[#253](https://github.com/jlfwong/speedscope/pull/253)] (by [@jlfwong](https://github.com/jlfwong), with changes from [@Archerlly](https://github.com/Archerlly)'s [#215](https://github.com/jlfwong/speedscope/pull/215))
- Trace event: Prevent event re-ordering from generating incorrect flamegraphs ([#252](https://github.com/jlfwong/speedscope/pull/252), with changes from [@hwajaywang](https://github.com/hwajaywang)'s [#249](https://github.com/jlfwong/speedscope/pull/249))
- Make tooltip width wider [[#239](https://github.com/jlfwong/speedscope/pull/239)] (by [@miso11](https://github.com/miso11))
## [1.5.2] - 2019-10-10
### Fixed
- Fix emscripten remapping when symbols are hex-escaped, like `a\20b` [[#233](https://github.com/jlfwong/speedscope/pull/233)] (by [@jyc](https://github.com/jyc))
* Fix emscripten remapping when symbols are hex-escaped, like `a\20b` [#233] (by @jyc)
## [1.5.1] - 2019-06-06
### Fixed
- Fixed import of trace event files which contain unmatched "E" events ([#222](https://github.com/jlfwong/speedscope/pull/222)) (by [@jlfwong](https://github.com/jlfwong))
* Fixed import of trace event files which contain unmatched "E" events (#222) (by @jlfwong)
## [1.5.0] - 2019-02-17
### Added
- Support importing unterminated JSON in simple cases ([#208](https://github.com/jlfwong/speedscope/pull/208)) (by [@jlfwong](https://github.com/jlfwong))
* Support importing unterminated JSON in simple cases (#208) (by @jlfwong)
### Fixed
- Fix crash when importing from stackprof without raw_timestamp_deltas ([#207](https://github.com/jlfwong/speedscope/pull/207)) (by [@jlfwong](https://github.com/jlfwong))
- Alert instead of crash when importing a file containing no profiles ([#205](https://github.com/jlfwong/speedscope/pull/205)) (by [@jlfwong](https://github.com/jlfwong))
- Fixed import of multithreaded profiles from Chrome 66 ([#206](https://github.com/jlfwong/speedscope/pull/206)) (by [@jlfwong](https://github.com/jlfwong))
- Fixed import of instruments trace files with missing run number ([#203](https://github.com/jlfwong/speedscope/pull/203)) (by [@Archerlly](https://github.com/Archerlly))
* Fix crash when importing from stackpro without raw_timestamp_deltas (#207) (by @jlfwong)
* Alert instead of crash when importing a file containing no profiles (#205) (by @jlfwong)
* Fixed import of multithreaded profiles from Chrome 66 (#206) (by @jlfwong)
* Fixed import of instruments trace files with missing run number (#203) (by @Archerlly)
## [1.4.1] - 2019-01-22
### Fixed
- Fix importing of Trace Event Format files with no ts field on M events [[#198](https://github.com/jlfwong/speedscope/pull/198)] (by [@jlfwong](https://github.com/jlfwong))
* Fix importing of Trace Event Format files with no ts field on M events [#198] (by @jlfwong)
## [1.4.0] - 2019-01-22
### Added
- Import v8 cpu profile (old format) [[#177](https://github.com/jlfwong/speedscope/pull/177)] (by [@vmarchaud](https://github.com/vmarchaud))
- Import basic "Trace Event Format" profiles [[#197](https://github.com/jlfwong/speedscope/pull/197)] (by [@jlfwong](https://github.com/jlfwong))
* Import v8 cpu profile (old format) [#177] (by @vmarchaud)
* Import basic "Trace Event Format" profiles [#197] (by @jlfwong)
## [1.3.2] - 2018-12-03
### Fixed
- Fixed import of multithreaded Chrome profiles [[#19](https://github.com/jlfwong/speedscope/pull/19)] (by [@jlfwong](https://github.com/jlfwong))
* Fixed import of multithreaded Chrome profiles [#19] (by @jlfwong)
## [1.3.1] - 2018-11-08
### Fixed
- Fixed a file import performance regression by using TextDecoder [[#188](https://github.com/jlfwong/speedscope/pull/188)] (by [@jlfwong](https://github.com/jlfwong))
* Fixed a file import performance regression by using TextDecoder [#188] (by @jlfwong)
## [1.3.0] - 2018-10-29
### Added
- Support import from Haskell GHC JSON format support [[#183](https://github.com/jlfwong/speedscope/pull/183)] (by [@trishume](https://github.com/trishume))
* Support import from Haskell GHC JSON format support [#183] (by @trishume)
### Fixed
- Make the wasd keymappings work on azerty keyboards [[#184](https://github.com/jlfwong/speedscope/pull/184)] (by [@vrischmann](https://github.com/vrischmann))
- Fix import of binary formats via profileURL [[#179](https://github.com/jlfwong/speedscope/pull/179)] (by [@f](https://github.com/f)-hj)
* Make the wasd keymappings work on azerty keyboards [#184] (by @vrischmann)
* Fix import of binary formats via profileURL [#179] (by @f-hj)
## [1.2.0] - 2018-10-08
### Added
- Add import of v8 heap allocation profile [[#170](https://github.com/jlfwong/speedscope/pull/170)] (by [@vmarchaud](https://github.com/vmarchaud))
* Add import of v8 heap allocation profile [#170] (by @vmarchaud)
## [1.1.0] - 2018-09-26
### Added
- Add go tool pprof import support [[#165](https://github.com/jlfwong/speedscope/pull/165)]
* Add go tool pprof import support [#165]
## [1.0.4] - 2018-09-12
### Fixed
- Fix import from Chrome < 69 when there are multiple profiles [[#161](https://github.com/jlfwong/speedscope/pull/161)]
* Fix import from Chrome < 69 when there are multiple profiles [#161]
## [1.0.3] - 2018-09-10
### Fixed
- Fix import for Chrome 69, support leading idle time before first call [[#160](https://github.com/jlfwong/speedscope/pull/160)]
* Fix import for Chrome 69, support leading idle time before first call [#160]
## [1.0.2] - 2018-09-04
### Fixed
- Allow optional CR before LF when probing collapsed stacks files [[#154](https://github.com/jlfwong/speedscope/pull/154)]
- Fix import for Firefox 63 [[#156](https://github.com/jlfwong/speedscope/pull/156)]
- Change time formatting for minutes from 1.50min to 1:30 [[#153](https://github.com/jlfwong/speedscope/pull/153)] (by [@Alex](https://github.com/Alex)-Diez)
* Allow optional CR before LF when probing collapsed stacks files [#154]
* Fix import for Firefox 63 [#156]
* Change time formatting for minutes from 1.50min to 1:30 [#153] (by @Alex-Diez)
## [1.0.1] - 2018-08-23
- Fixed an issue where flamegraph bounds were not always being cleared correctly, leading to visual artifacts [[#150](https://github.com/jlfwong/speedscope/pull/150)]
* Fixed an issue where flamegraph bounds were not always being cleared correctly, leading to visual artifacts [#150]
## [1.0.0] - 2018-08-23
### Fixed
- Fixed rendering issues when switching between screens w/ different `devicePixelRatios` [[#147](https://github.com/jlfwong/speedscope/pull/147)]
* Fixed rendering issues when switching between screens w/ different `devicePixelRatios` [#147]
## [0.7.1] - 2018-08-20
### Fixed
- Removed dependency on regl in order to allow speedscope to run in strict content-security-policy environments [[#140](https://github.com/jlfwong/speedscope/pull/140)]
- Fixed text culling bug [[#143](https://github.com/jlfwong/speedscope/pull/143)]
* Removed dependency on regl in order to allow speedscope to run in strict content-security-policy environments [#140]
* Fixed text culling bug [#143]
## [0.7.0] - 2018-08-16
### Added
- Added support to import from linux `perf script` [[#135](https://github.com/jlfwong/speedscope/pull/135)]
* Added support to import from linux `perf script` [#135]
## [0.6.0] - 2018-08-14
### Added
- Added support for multiple threads/processes [[#130](https://github.com/jlfwong/speedscope/pull/130)]
- Import all runs & threads from Instruments .trace files instead of just main thread from selected run [[#130](https://github.com/jlfwong/speedscope/pull/130)]
* Added support for multiple threads/processes [#130]
* Import all runs & threads from Instruments .trace files instead of just main thread from selected run [#130]
### Fixed
- Ensure the JSON schema has actual contents [[#133](https://github.com/jlfwong/speedscope/pull/133)]
* Ensure the JSON schema has actual contents [#133]
## [0.5.1] - 2018-08-09
### Fixed
- Fixed broken CLI
* Fixed broken CLI
## [0.5.0] - 2018-08-09
### Fixed
- Fix emscripten remapping when symbols contain dashes, like `527:i32s-div` [[#129](https://github.com/jlfwong/speedscope/pull/129)]
- Improved firefox import speed and fixed bugs in it [[#128](https://github.com/jlfwong/speedscope/pull/128)]
- Prevent non-contiguous blocks in the time ordered flamechart from appearing as a single node for selection [[#123](https://github.com/jlfwong/speedscope/pull/123)]
- Prevent dragging from changing selection [[#122](https://github.com/jlfwong/speedscope/pull/122)]
- Clamp zoom to prevent floating point issues [[#121](https://github.com/jlfwong/speedscope/pull/121)]
- Preserve view state when switching tabs [[#100](https://github.com/jlfwong/speedscope/pull/100)]
* Fix emscripten remapping when symbols contain dashes, like `527:i32s-div` [#129]
* Improved firefox import speed and fixed bugs in it [#128]
* Prevent non-contiguous blocks in the time ordered flamechart from appearing as a single node for selection [#123]
* Prevent dragging from changing selection [#122]
* Clamp zoom to prevent floating point issues [#121]
* Preserve view state when switching tabs [#100]
## [0.4.0] - 2018-07-21
### Added
- Support for importing v8 logs from node [[#98](https://github.com/jlfwong/speedscope/pull/98)]
- Optionally read from stdin via cli [[#99](https://github.com/jlfwong/speedscope/pull/99)]
* Support for importing v8 logs from node [#98]
* Optionally read from stdin via cli [#99]
## [0.3.0] - 2018-07-18
### Added
- Support for remapping profiles using a wasm symbol file [[#93](https://github.com/jlfwong/speedscope/pull/93)]
* Support for remapping profiles using a wasm symbol file [#93]
-6
View File
@@ -36,16 +36,13 @@ speedscope is designed to ingest profiles from a variety of different profilers
- JavaScript
- [Importing from Chrome](https://github.com/jlfwong/speedscope/wiki/Importing-from-Chrome)
- [Importing from Firefox](https://github.com/jlfwong/speedscope/wiki/Importing-from-Firefox)
- [Importing from Safari](https://github.com/jlfwong/speedscope/wiki/Importing-from-Safari)
- [Importing from Node.js](https://github.com/jlfwong/speedscope/wiki/Importing-from-Node.js)
- Ruby
- [Importing from stackprof](https://github.com/jlfwong/speedscope/wiki/Importing-from-stackprof-(ruby))
- [Importing from rbspy](https://github.com/jlfwong/speedscope/wiki/Importing-from-rbspy-(ruby))
- [Importing from ruby-prof](https://github.com/jlfwong/speedscope/wiki/Importing-from-ruby-prof)
- Python
- [Importing from py-spy](https://github.com/jlfwong/speedscope/wiki/Importing-from-py-spy-(python))
- [pyspeedscope](https://github.com/windelbouwman/pyspeedscope)
- [Importing from Austin](https://github.com/P403n1x87/austin-python#format-conversion)
- Go
- [Importing from pprof](https://github.com/jlfwong/speedscope/wiki/Importing-from-pprof-(go))
- Rust
@@ -53,7 +50,6 @@ speedscope is designed to ingest profiles from a variety of different profilers
- Native code
- [Importing from Instruments.app](https://github.com/jlfwong/speedscope/wiki/Importing-from-Instruments.app) (macOS)
- [Importing from `perf`](https://github.com/jlfwong/speedscope/wiki/Importing-from-perf-(linux)) (linux)
- [Importing from .NET Core](https://github.com/jlfwong/speedscope/wiki/Importing-from-.NET-Core)
- [Importing from GHC (Haskell)](https://github.com/jlfwong/speedscope/wiki/Importing-from-Haskell)
- [Importing from custom sources](https://github.com/jlfwong/speedscope/wiki/Importing-from-custom-sources)
@@ -117,8 +113,6 @@ Once a profile has loaded, the main view is split into two: the top area is the
* `Cmd+O`/`Ctrl+O` to open a new profile
* `n`: Go to next profile/thread if one is available
* `p`: Go to previous profile/thread if one is available
* `t`: Open the profile/thread selector if available
* `Cmd+F`/`Ctrl+F`: to open search. While open, `Enter` and `Shift+Enter` cycle through results
## Contributing
+2 -6
View File
@@ -4,7 +4,7 @@ const fs = require('fs')
const os = require('os')
const stream = require('stream')
const open = require('open')
const opn = require('opn')
const helpString = `Usage: speedscope [filepath]
@@ -89,11 +89,7 @@ async function main() {
console.log('Opening', urlToOpen, 'in your default browser')
// We'd like to avoid blocking the terminal on the browsing closing,
// but for some reason this doesn't work at all on Windows if we
// don't use wait: true.
const wait = process.platform === "win32";
await open(urlToOpen, {wait})
await opn(urlToOpen, {wait: false})
}
main()
+8102 -6316
View File
File diff suppressed because it is too large Load Diff
+16 -23
View File
@@ -1,6 +1,6 @@
{
"name": "speedscope",
"version": "1.11.0",
"version": "1.5.2",
"description": "",
"repository": "jlfwong/speedscope",
"main": "index.js",
@@ -13,9 +13,8 @@
"prettier": "prettier --write 'src/**/*.ts' 'src/**/*.tsx'",
"lint": "eslint 'src/**/*.ts' 'src/**/*.tsx'",
"jest": "./scripts/test-setup.sh && jest --runInBand",
"coverage": "npm run jest -- --coverage",
"typecheck": "tsc --noEmit",
"test": "./scripts/ci.sh",
"coverage": "npm run jest -- --coverage && coveralls < coverage/lcov.info",
"test": "tsc --noEmit && npm run lint && npm run coverage",
"serve": "parcel assets/index.html --open --no-autoinstall"
},
"files": [
@@ -32,38 +31,32 @@
"devDependencies": {
"@types/jest": "22.2.3",
"@types/jszip": "3.1.4",
"@types/node": "14.0.1",
"@types/node": "10.1.4",
"@types/pako": "1.0.0",
"@typescript-eslint/eslint-plugin": "2.33.0",
"@typescript-eslint/parser": "2.33.0",
"acorn": "7.2.0",
"aphrodite": "2.1.0",
"eslint": "6.0.0",
"coveralls": "3.0.1",
"eslint": "4.19.1",
"eslint-plugin-prettier": "2.6.0",
"eslint-plugin-react-hooks": "4.0.2",
"jest": "24.3.0",
"jest": "23.0.1",
"jsverify": "0.8.3",
"jszip": "3.1.5",
"pako": "1.0.6",
"parcel-bundler": "1.12.4",
"preact": "10.4.1",
"prettier": "2.0.4",
"parcel-bundler": "1.9.2",
"preact": "8.2.7",
"preact-redux": "jlfwong/preact-redux#a56dcc4",
"prettier": "1.12.0",
"protobufjs": "6.8.8",
"redux": "^4.0.5",
"source-map": "0.6.1",
"ts-jest": "24.3.0",
"typescript": "3.9.2",
"quicktype": "15.0.45",
"redux": "^4.0.0",
"ts-jest": "22.4.6",
"typescript": "2.8.1",
"typescript-eslint-parser": "17.0.1",
"typescript-json-schema": "0.42.0",
"uglify-es": "3.2.2"
},
"jest": {
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"setupFilesAfterEnv": [
"./src/jest-setup.js"
],
"testRegex": "\\.test\\.tsx?$",
"collectCoverageFrom": [
"**/*.{ts,tsx}",
@@ -78,6 +71,6 @@
]
},
"dependencies": {
"open": "7.2.0"
"opn": "5.3.0"
}
}
+1 -2
View File
@@ -4,5 +4,4 @@ module.exports = {
semi: false,
singleQuote: true,
trailingComma: 'all',
arrowParens: 'avoid'
}
};
File diff suppressed because one or more lines are too long
-4
View File
@@ -1,4 +0,0 @@
This directory contains profiles & source-maps to test if source-map
remapping of profiles is working correctly. See the corresponding
"sourcemaps" directory in programs/javascript to see how these were
generated.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,7 +0,0 @@
{
"version": 3,
"sources": ["gamma.ts", "beta.ts", "delta.ts", "alpha.ts", "kludge.ts", "typescript-source-map-test.ts"],
"sourcesContent": ["export const gamma = () => {\n let prod = 1\n for (let i = 1; i < 1000; i++) {\n prod *= i\n }\n return prod\n}\n", "import {gamma} from './gamma'\n\nexport function beta() {\n for (let i = 0; i < 10; i++) {\n gamma()\n }\n}\n", "import {gamma} from './gamma'\n\nexport const delta = function () {\n for (let i = 0; i < 10; i++) {\n gamma()\n }\n}\n", "import {beta} from './beta'\nimport {delta} from './delta'\n\nexport function alpha() {\n ;(function () {\n for (let i = 0; i < 1000; i++) {\n beta()\n delta()\n }\n })()\n}\n", "import {alpha} from './alpha'\n\nexport class Kludge {\n constructor() {\n alpha()\n console.log(this.floop)\n }\n\n zap() {\n alpha()\n }\n\n get floop(): number {\n alpha()\n return 1\n }\n}\n", "import {Kludge} from './kludge'\n\nconst k = new Kludge()\nk.zap()\n"],
"mappings": "MAAO,KAAM,GAAQ,KACnB,GAAI,GAAO,EACX,OAAS,GAAI,EAAG,EAAI,IAAM,IACxB,GAAQ,EAEV,MAAO,ICHF,aACL,OAAS,GAAI,EAAG,EAAI,GAAI,IACtB,ICFG,KAAM,GAAQ,WACnB,OAAS,GAAI,EAAG,EAAI,GAAI,IACtB,KCDG,aACJ,AAAC,YACA,OAAS,GAAI,EAAG,EAAI,IAAM,IACxB,IACA,QCPN,QAGE,cACE,IACA,QAAQ,IAAI,KAAK,OAGnB,MACE,OAGE,SACF,WACO,GCZX,KAAM,GAAI,GAAI,GACd,EAAE",
"names": []
}
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
{"version":3,"sources":["gamma.ts","beta.ts","delta.ts","alpha.ts","kludge.ts","typescript-source-map-test.ts"],"names":[],"mappings":";AAAO,aAAA,OAAA,eAAA,QAAA,aAAA,CAAA,OAAA,IAAA,QAAA,WAAA,EAAA,IAAM,EAAQ,WAEd,IADD,IAAA,EAAO,EACF,EAAI,EAAG,EAAI,IAAM,IACxB,GAAQ,EAEH,OAAA,GALF,QAAA,MAAA;;ACMN,aAAA,OAAA,eAAA,QAAA,aAAA,CAAA,OAAA,IAAA,QAAA,KAAA,EAND,IAAA,EAAA,QAAA,WAEM,SAAU,IACT,IAAA,IAAI,EAAI,EAAG,EAAI,GAAI,KACtB,EAAA,EAAA;;ACFG,aAAA,OAAA,eAAA,QAAA,aAAA,CAAA,OAAA,IAAA,QAAA,WAAA,EAFP,IAAA,EAAA,QAAA,WAEa,EAAQ,WACd,IAAA,IAAI,EAAI,EAAG,EAAI,GAAI,KACtB,EAAA,EAAA,UAFG,QAAA,MAAA;;ACQN,aAAA,OAAA,eAAA,QAAA,aAAA,CAAA,OAAA,IAAA,QAAA,MAAA,EAVD,IAAA,EAAA,QAAA,UACA,EAAA,QAAA,WAEM,SAAU,KACZ,WACK,IAAA,IAAI,EAAI,EAAG,EAAI,IAAM,KACxB,EAAA,EAAA,SACA,EAAA,EAAA,SAHF;;ACFJ,aAAA,OAAA,eAAA,QAAA,aAAA,CAAA,OAAA,IAAA,QAAA,YAAA,EAFA,IAAA,EAAA,QAAA,WAEA,EAAA,WACE,SAAA,KACE,EAAA,EAAA,SACA,QAAQ,IAAI,KAAK,OAWrB,OARE,EAAA,UAAA,IAAA,YACE,EAAA,EAAA,UAGF,OAAA,eAAI,EAAA,UAAA,QAAK,CAAT,IAAA,WAES,OADP,EAAA,EAAA,SACO,GAFA,YAAA,EAVX,cAAA,IAcA,EAdA,GAAA,QAAA,OAAA;;ACCA,aAHA,IAAA,EAAA,QAAA,YAEM,EAAI,IAAI,EAAJ,OACV,EAAE","file":"typescript-source-map-test.js","sourceRoot":"..","sourcesContent":["export const gamma = () => {\n let prod = 1\n for (let i = 1; i < 1000; i++) {\n prod *= i\n }\n return prod\n}\n","import {gamma} from './gamma'\n\nexport function beta() {\n for (let i = 0; i < 10; i++) {\n gamma()\n }\n}\n","import {gamma} from './gamma'\n\nexport const delta = function () {\n for (let i = 0; i < 10; i++) {\n gamma()\n }\n}\n","import {beta} from './beta'\nimport {delta} from './delta'\n\nexport function alpha() {\n ;(function () {\n for (let i = 0; i < 1000; i++) {\n beta()\n delta()\n }\n })()\n}\n","import {alpha} from './alpha'\n\nexport class Kludge {\n constructor() {\n alpha()\n console.log(this.floop)\n }\n\n zap() {\n alpha()\n }\n\n get floop(): number {\n alpha()\n return 1\n }\n}\n","import {Kludge} from './kludge'\n\nconst k = new Kludge()\nk.zap()\n"]}
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
{"version":3,"sources":["webpack://speedscope-sourcemap-test-project/./gamma.ts","webpack://speedscope-sourcemap-test-project/./beta.ts","webpack://speedscope-sourcemap-test-project/./delta.ts","webpack://speedscope-sourcemap-test-project/./alpha.ts","webpack://speedscope-sourcemap-test-project/./typescript-source-map-test.ts","webpack://speedscope-sourcemap-test-project/./kludge.ts"],"names":["gamma","prod","i","beta","delta","alpha","console","log","this","floop","zap"],"mappings":"mBAAO,IAAMA,EAAQ,WAEnB,IADA,IAAIC,EAAO,EACFC,EAAI,EAAGA,EAAI,IAAMA,IACxBD,GAAQC,EAEV,OAAOD,GCHF,SAASE,IACd,IAAK,IAAID,EAAI,EAAGA,EAAI,GAAIA,IACtBF,ICFG,IAAMI,EAAQ,WACnB,IAAK,IAAIF,EAAI,EAAGA,EAAI,GAAIA,IACtBF,KCDG,SAASK,KACb,WACC,IAAK,IAAIH,EAAI,EAAGA,EAAI,IAAMA,IACxBC,IACAC,IAHH,ICFO,ICAV,WACE,aACEC,IACAC,QAAQC,IAAIC,KAAKC,OAWrB,OARE,YAAAC,IAAA,WACEL,KAGF,sBAAI,oBAAK,C,IAAT,WAEE,OADAA,IACO,G,gCAEX,EAdA,KDCEK,O","file":"typescript-source-map-test.js","sourcesContent":["export const gamma = () => {\n let prod = 1\n for (let i = 1; i < 1000; i++) {\n prod *= i\n }\n return prod\n}\n","import {gamma} from './gamma'\n\nexport function beta() {\n for (let i = 0; i < 10; i++) {\n gamma()\n }\n}\n","import {gamma} from './gamma'\n\nexport const delta = function () {\n for (let i = 0; i < 10; i++) {\n gamma()\n }\n}\n","import {beta} from './beta'\nimport {delta} from './delta'\n\nexport function alpha() {\n ;(function () {\n for (let i = 0; i < 1000; i++) {\n beta()\n delta()\n }\n })()\n}\n","import {Kludge} from './kludge'\n\nconst k = new Kludge()\nk.zap()\n","import {alpha} from './alpha'\n\nexport class Kludge {\n constructor() {\n alpha()\n console.log(this.floop)\n }\n\n zap() {\n alpha()\n }\n\n get floop(): number {\n alpha()\n return 1\n }\n}\n"],"sourceRoot":""}
@@ -1,16 +0,0 @@
{
"$schema": "https://www.speedscope.app/file-format-schema.json",
"shared": {
"frames": [{"name": "A"}]
},
"profiles": [
{
"type": "evented",
"name": "p1",
"unit": "none",
"startValue": 0,
"endValue": 100,
"events": [{"type": "O", "frame": 0, "at": 0}]
}
]
}
@@ -1,25 +0,0 @@
{
"$schema": "https://www.speedscope.app/file-format-schema.json",
"shared": {
"frames": [{"name": "A"}, {"name": "B"}]
},
"profiles": [
{
"type": "evented",
"name": "p1",
"unit": "none",
"startValue": 0,
"endValue": 100,
"events": [
{"type": "O", "frame": 0, "at": 0},
{"type": "C", "frame": 0, "at": 1},
{"type": "O", "frame": 1, "at": 2},
{"type": "O", "frame": 0, "at": 2},
{"type": "O", "frame": 0, "at": 3},
{"type": "C", "frame": 0, "at": 4},
{"type": "C", "frame": 1, "at": 4},
{"type": "C", "frame": 0, "at": 5}
]
}
]
}
Binary file not shown.
Binary file not shown.
@@ -1,16 +0,0 @@
[
{"tid": 1, "ph": "B", "pid": 0, "name": "A", "ts": 0},
{"tid": 1, "ph": "B", "pid": 0, "name": "B", "ts": 0},
{"tid": 1, "ph": "B", "pid": 0, "name": "C", "ts": 0},
{"tid": 1, "ph": "E", "pid": 0, "name": "C", "ts": 1},
{"tid": 1, "ph": "E", "pid": 0, "name": "B", "ts": 2},
{"tid": 1, "ph": "E", "pid": 0, "name": "A", "ts": 3},
{"tid": 1, "ph": "B", "pid": 0, "name": "A", "ts": 4},
{"tid": 1, "ph": "B", "pid": 0, "name": "B", "ts": 5},
{"tid": 1, "ph": "B", "pid": 0, "name": "C", "ts": 6},
{"tid": 1, "ph": "E", "pid": 0, "name": "C", "ts": 7},
{"tid": 1, "ph": "E", "pid": 0, "name": "B", "ts": 7},
{"tid": 1, "ph": "E", "pid": 0, "name": "A", "ts": 7},
{"tid": 1, "ph": "B", "pid": 0, "name": "X", "ts": 7},
{"tid": 1, "ph": "E", "pid": 0, "name": "X", "ts": 10}
]
@@ -1,22 +0,0 @@
## Source Map Test Project
This directory contains test files used to test whether the remapping of
performance profiles using sourcemaps work correctly.
Run `npm run build` to build the artifacts, then open the appropriate files in
the `html` directory in whatever browser you're testing.
The idea is to sourcemaps generated by a variety of tools, and also to take
profiles from a variety of browsers, and hopefully see that they all get
remapped as expected.
This project is set up to go through three levels of source-map indirection,
and also using multiple different build chains.
1. TypeScript -> JavaScript source generation
2. JavaScript source -> JavaScript bundling
3. Minification
Some bundlers will swap the order of steps 2 & 3, or potentially merge them,
but it's complex yet realistic enough that this will hoepfully suss out
problems.
@@ -1,11 +0,0 @@
import {beta} from './beta'
import {delta} from './delta'
export function alpha() {
;(function () {
for (let i = 0; i < 1000; i++) {
beta()
delta()
}
})()
}
@@ -1,7 +0,0 @@
import {gamma} from './gamma'
export function beta() {
for (let i = 0; i < 10; i++) {
gamma()
}
}
@@ -1,7 +0,0 @@
import {gamma} from './gamma'
export const delta = function () {
for (let i = 0; i < 10; i++) {
gamma()
}
}
@@ -1,7 +0,0 @@
export const gamma = () => {
let prod = 1
for (let i = 1; i < 1000; i++) {
prod *= i
}
return prod
}
@@ -1,3 +0,0 @@
<title>ESbuild</title>
<script src="../dist/esbuild/typescript-source-map-test.js"></script>
<h1>ESbuild Source Map Test</h1>
@@ -1,3 +0,0 @@
<title>Parcel</title>
<script src="../dist/parcel/typescript-source-map-test.js"></script>
<h1>Parcel Source Map Test</h1>
@@ -1,3 +0,0 @@
<title>Webpack</title>
<script src="../dist/webpack/typescript-source-map-test.js"></script>
<h1>Webpack Source Map Test</h1>
@@ -1,17 +0,0 @@
import {alpha} from './alpha'
export class Kludge {
constructor() {
alpha()
console.log(this.floop)
}
zap() {
alpha()
}
get floop(): number {
alpha()
return 1
}
}
File diff suppressed because it is too large Load Diff
@@ -1,23 +0,0 @@
{
"name": "speedscope-sourcemap-test-project",
"version": "1.0.0",
"description": "",
"private": "true",
"main": "index.js",
"scripts": {
"build": "npm run parcel && npm run webpack && npm run esbuild",
"parcel": "parcel build -o parcel/typescript-source-map-test typescript-source-map-test.ts",
"webpack": "webpack",
"esbuild": "esbuild --sourcemap --minify --bundle --outdir=dist/esbuild typescript-source-map-test.ts"
},
"author": "",
"license": "ISC",
"devDependencies": {
"esbuild": "^0.7.14",
"parcel": "^1.12.4",
"ts-loader": "^8.0.4",
"typescript": "^4.0.3",
"webpack": "^5.0.0",
"webpack-cli": "^4.0.0"
}
}
@@ -1,10 +0,0 @@
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"sourceMap": true,
"module": "es6",
"target": "es5",
"jsx": "react"
}
}
@@ -1,4 +0,0 @@
import {Kludge} from './kludge'
const k = new Kludge()
k.zap()
@@ -1,22 +0,0 @@
const path = require('path')
module.exports = {
entry: './typescript-source-map-test.ts',
devtool: 'source-map',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'typescript-source-map-test.js',
path: path.resolve(__dirname, 'dist', 'webpack'),
},
}
-8
View File
@@ -1,8 +0,0 @@
#!/bin/bash
set -euxo pipefail
npm run typecheck
npm run lint
npm run coverage
node scripts/generate-file-format-schema-json.js > /dev/null
+1 -1
View File
@@ -3,7 +3,7 @@ const child_process = require('child_process')
// Convert the file-format-spec.ts file into a json schema file
let jsonSchema = child_process.execSync(
'node_modules/.bin/typescript-json-schema ./src/lib/file-format-spec.ts --titles --required --topRef "*"',
'node_modules/.bin/quicktype --lang schema ./src/lib/file-format-spec.ts',
{
encoding: 'utf8',
},
+3 -1
View File
@@ -24,7 +24,9 @@ export class CanvasContext {
const webGLInfo = this.gl.getWebGLInfo()
if (webGLInfo) {
console.log(
`WebGL initialized. renderer: ${webGLInfo.renderer}, vendor: ${webGLInfo.vendor}, version: ${webGLInfo.version}`,
`WebGL initialized. renderer: ${webGLInfo.renderer}, vendor: ${
webGLInfo.vendor
}, version: ${webGLInfo.version}`,
)
}
;(window as any)['testContextLoss'] = () => {
+4 -4
View File
@@ -175,8 +175,8 @@ export class FlamechartRenderer {
// and the blue channel to indicate the color bucket to render.
// We add one to each so we have zero reserved for the background color.
const color = new Color(
(1 + (i % 255)) / 256,
(1 + (stackDepth % 255)) / 256,
(1 + i % 255) / 256,
(1 + stackDepth % 255) / 256,
(1 + this.flamechart.getColorBucketForFrame(frame.node.frame)) / 256,
)
batch.addRect(configSpaceBounds, color)
@@ -288,10 +288,10 @@ export class FlamechartRenderer {
const configSpaceContentWidth = this.flamechart.getTotalWeight()
const numAtlasEntriesPerLayer = Math.pow(2, zoomLevel)
const left = Math.floor(
(numAtlasEntriesPerLayer * configSpaceSrcRect.left()) / configSpaceContentWidth,
numAtlasEntriesPerLayer * configSpaceSrcRect.left() / configSpaceContentWidth,
)
const right = Math.ceil(
(numAtlasEntriesPerLayer * configSpaceSrcRect.right()) / configSpaceContentWidth,
numAtlasEntriesPerLayer * configSpaceSrcRect.right() / configSpaceContentWidth,
)
const nLayers = this.flamechart.getLayers().length
+2 -8
View File
@@ -455,8 +455,7 @@ export namespace WebGL {
widthInAppUnits: number,
heightInAppUnits: number,
) {
let canvas = this._gl.canvas as HTMLCanvasElement
const bounds = canvas.getBoundingClientRect()
const bounds = this._gl.canvas.getBoundingClientRect()
if (
this._width === widthInAppUnits &&
@@ -468,6 +467,7 @@ export namespace WebGL {
return
}
let canvas = this._gl.canvas
let style = canvas.style
canvas.width = widthInPixels
canvas.height = heightInPixels
@@ -1086,17 +1086,11 @@ export namespace WebGL {
_compileShader(gl: WebGLRenderingContext, type: GLenum, source: string) {
let shader = gl.createShader(type)
if (!shader) {
throw new Error('Failed to create shader')
}
gl.shaderSource(shader, source)
gl.compileShader(shader)
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error(`${gl.getShaderInfoLog(shader)}`)
}
if (!this._program) {
throw new Error('Tried to attach shader before program was created')
}
gl.attachShader(this._program, shader)
}
+1 -6
View File
@@ -65,12 +65,7 @@ export class ViewportRectangleRenderer {
private buffer: Graphics.VertexBuffer
constructor(private gl: Graphics.Context) {
const vertices = [
[-1, 1],
[1, 1],
[-1, -1],
[1, -1],
]
const vertices = [[-1, 1], [1, 1], [-1, -1], [1, -1]]
const floats: number[] = []
for (let v of vertices) {
floats.push(v[0])
+1 -8
View File
@@ -45,14 +45,7 @@ export class RectangleBatch {
return this.buffer
}
const corners = [
[0, 0],
[1, 0],
[0, 1],
[1, 0],
[0, 1],
[1, 1],
]
const corners = [[0, 0], [1, 0], [0, 1], [1, 0], [0, 1], [1, 1]]
const bytes = new Uint8Array(vertexFormat.stride * corners.length * this.rects.length)
const floats = new Float32Array(bytes.buffer)
@@ -104,114 +104,6 @@ exports[`importFromBGFlameGraph with CRLF: indexToView 1`] = `0`;
exports[`importFromBGFlameGraph with CRLF: profileGroup.name 1`] = `"simple-crlf.txt"`;
exports[`importFromBGFlameGraph with UTF-16, Big Endian 1`] = `
Object {
"frames": Array [
Frame {
"col": undefined,
"file": undefined,
"key": "a",
"line": undefined,
"name": "a",
"selfWeight": 0,
"totalWeight": 14,
},
Frame {
"col": undefined,
"file": undefined,
"key": "b",
"line": undefined,
"name": "b",
"selfWeight": 5,
"totalWeight": 14,
},
Frame {
"col": undefined,
"file": undefined,
"key": "c",
"line": undefined,
"name": "c",
"selfWeight": 5,
"totalWeight": 5,
},
Frame {
"col": undefined,
"file": undefined,
"key": "d",
"line": undefined,
"name": "d",
"selfWeight": 4,
"totalWeight": 4,
},
],
"name": "simple-utf16-be.txt",
"stacks": Array [
"a;b;c 2",
"a;b;d 4",
"a;b;c 3",
"a;b 5",
],
}
`;
exports[`importFromBGFlameGraph with UTF-16, Big Endian: indexToView 1`] = `0`;
exports[`importFromBGFlameGraph with UTF-16, Big Endian: profileGroup.name 1`] = `"simple-utf16-be.txt"`;
exports[`importFromBGFlameGraph with UTF-16, Little Endian 1`] = `
Object {
"frames": Array [
Frame {
"col": undefined,
"file": undefined,
"key": "a",
"line": undefined,
"name": "a",
"selfWeight": 0,
"totalWeight": 14,
},
Frame {
"col": undefined,
"file": undefined,
"key": "b",
"line": undefined,
"name": "b",
"selfWeight": 5,
"totalWeight": 14,
},
Frame {
"col": undefined,
"file": undefined,
"key": "c",
"line": undefined,
"name": "c",
"selfWeight": 5,
"totalWeight": 5,
},
Frame {
"col": undefined,
"file": undefined,
"key": "d",
"line": undefined,
"name": "d",
"selfWeight": 4,
"totalWeight": 4,
},
],
"name": "simple-utf16-le.txt",
"stacks": Array [
"a;b;c 2",
"a;b;d 4",
"a;b;c 3",
"a;b 5",
],
}
`;
exports[`importFromBGFlameGraph with UTF-16, Little Endian: indexToView 1`] = `0`;
exports[`importFromBGFlameGraph with UTF-16, Little Endian: profileGroup.name 1`] = `"simple-utf16-le.txt"`;
exports[`importFromBGFlameGraph: indexToView 1`] = `0`;
exports[`importFromBGFlameGraph: profileGroup.name 1`] = `"simple.txt"`;
File diff suppressed because it is too large Load Diff
+11 -11
View File
@@ -64,17 +64,17 @@ exports[`importFromFirefox ignore self-hosted 1`] = `
Object {
"frames": Array [
Frame {
"col": 15,
"file": "http://localhost:8000/simple.js",
"col": undefined,
"file": "http://localhost:8000/simple.js:1",
"key": "alpha (http://localhost:8000/simple.js:1:14)",
"line": 1,
"line": 14,
"name": "alpha",
"selfWeight": 0,
"totalWeight": 26.983816999942064,
},
Frame {
"col": 15,
"file": "http://localhost:8000/simple.js",
"col": undefined,
"file": "http://localhost:8000/simple.js:14",
"key": "delta (http://localhost:8000/simple.js:14:14)",
"line": 14,
"name": "delta",
@@ -82,19 +82,19 @@ Object {
"totalWeight": 11.946324001066387,
},
Frame {
"col": 15,
"file": "http://localhost:8000/simple.js",
"col": undefined,
"file": "http://localhost:8000/simple.js:20",
"key": "gamma (http://localhost:8000/simple.js:20:14)",
"line": 20,
"line": 14,
"name": "gamma",
"selfWeight": 26.983816999942064,
"totalWeight": 26.983816999942064,
},
Frame {
"col": 14,
"file": "http://localhost:8000/simple.js",
"col": undefined,
"file": "http://localhost:8000/simple.js:8",
"key": "beta (http://localhost:8000/simple.js:8:13)",
"line": 8,
"line": 13,
"name": "beta",
"selfWeight": 0,
"totalWeight": 15.037492998875678,
@@ -1,101 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`importFromSafari 1`] = `
Object {
"frames": Array [
Frame {
"col": 13,
"file": "__InjectedScript_InjectedScriptSource.js",
"key": "injectModule:__InjectedScript_InjectedScriptSource.js:109:13",
"line": 109,
"name": "injectModule",
"selfWeight": 0,
"totalWeight": 0.001,
},
Frame {
"col": 10,
"file": "__InjectedScript_CommandLineAPIModuleSource.js",
"key": ":__InjectedScript_CommandLineAPIModuleSource.js:2:10",
"line": 2,
"name": "(anonymous)",
"selfWeight": 0.001,
"totalWeight": 0.001,
},
Frame {
"col": 1,
"file": "file:///speedscope/sample/programs/javascript/simple.js",
"key": "(program):file:///speedscope/sample/programs/javascript/simple.js:1:1",
"line": 1,
"name": "(program)",
"selfWeight": 0,
"totalWeight": 0.03248933597933502,
},
Frame {
"col": 15,
"file": "file:///speedscope/sample/programs/javascript/simple.js",
"key": "alpha:file:///speedscope/sample/programs/javascript/simple.js:1:15",
"line": 1,
"name": "alpha",
"selfWeight": 0,
"totalWeight": 0.03248933597933502,
},
Frame {
"col": 15,
"file": "file:///speedscope/sample/programs/javascript/simple.js",
"key": "delta:file:///speedscope/sample/programs/javascript/simple.js:14:15",
"line": 14,
"name": "delta",
"selfWeight": 0.003094222474222382,
"totalWeight": 0.020112446082445484,
},
Frame {
"col": 15,
"file": "file:///speedscope/sample/programs/javascript/simple.js",
"key": "gamma:file:///speedscope/sample/programs/javascript/simple.js:20:15",
"line": 20,
"name": "gamma",
"selfWeight": 0.029395113505112636,
"totalWeight": 0.029395113505112636,
},
Frame {
"col": 14,
"file": "file:///speedscope/sample/programs/javascript/simple.js",
"key": "beta:file:///speedscope/sample/programs/javascript/simple.js:8:14",
"line": 8,
"name": "beta",
"selfWeight": 0,
"totalWeight": 0.012376889896889526,
},
Frame {
"col": 102,
"file": "",
"key": "firstOpenSearchURLString::4:102",
"line": 4,
"name": "firstOpenSearchURLString",
"selfWeight": 0.0005174240213818848,
"totalWeight": 0.0005174240213818848,
},
],
"name": "Grabación de Control temporal 1",
"stacks": Array [
"injectModule;(anonymous) 1.00ms",
" 39.93ms",
"(program);alpha;delta;gamma 10.83ms",
" 2.46ms",
"(program);alpha;delta 3.09ms",
"(program);alpha;beta;gamma 4.64ms",
"(program);alpha;delta;gamma 1.55ms",
"(program);alpha;beta;gamma 1.55ms",
"(program);alpha;delta;gamma 3.09ms",
"(program);alpha;beta;gamma 4.64ms",
"(program);alpha;delta;gamma 1.55ms",
"(program);alpha;beta;gamma 1.55ms",
" 253.50ms",
"firstOpenSearchURLString 517.42µs",
],
}
`;
exports[`importFromSafari: indexToView 1`] = `0`;
exports[`importFromSafari: profileGroup.name 1`] = `"Grabación de Control temporal 1"`;
@@ -35,64 +35,6 @@ exports[`importTraceEvents bad E events: indexToView 1`] = `0`;
exports[`importTraceEvents bad E events: profileGroup.name 1`] = `"too-many-end-events.json"`;
exports[`importTraceEvents event re-ordering 1`] = `
Object {
"frames": Array [
Frame {
"col": undefined,
"file": undefined,
"key": "A",
"line": undefined,
"name": "A",
"selfWeight": 2,
"totalWeight": 6,
},
Frame {
"col": undefined,
"file": undefined,
"key": "B",
"line": undefined,
"name": "B",
"selfWeight": 2,
"totalWeight": 4,
},
Frame {
"col": undefined,
"file": undefined,
"key": "C",
"line": undefined,
"name": "C",
"selfWeight": 2,
"totalWeight": 2,
},
Frame {
"col": undefined,
"file": undefined,
"key": "X",
"line": undefined,
"name": "X",
"selfWeight": 3,
"totalWeight": 3,
},
],
"name": "pid 0, tid 1",
"stacks": Array [
"A;B;C 1.00µs",
"A;B 1.00µs",
"A 1.00µs",
" 1.00µs",
"A 1.00µs",
"A;B 1.00µs",
"A;B;C 1.00µs",
"X 3.00µs",
],
}
`;
exports[`importTraceEvents event re-ordering: indexToView 1`] = `0`;
exports[`importTraceEvents event re-ordering: profileGroup.name 1`] = `"must-retain-original-order.json"`;
exports[`importTraceEvents multiprocess 1`] = `
Object {
"frames": Array [
-8
View File
@@ -7,11 +7,3 @@ test('importFromBGFlameGraph', async () => {
test('importFromBGFlameGraph with CRLF', async () => {
await checkProfileSnapshot('./sample/profiles/stackcollapse/simple-crlf.txt')
})
test('importFromBGFlameGraph with UTF-16, Little Endian', async () => {
await checkProfileSnapshot('./sample/profiles/stackcollapse/simple-utf16-le.txt')
})
test('importFromBGFlameGraph with UTF-16, Big Endian', async () => {
await checkProfileSnapshot('./sample/profiles/stackcollapse/simple-utf16-be.txt')
})
+11 -28
View File
@@ -170,17 +170,8 @@ function frameInfoForCallFrame(callFrame: CPUProfileCallFrame) {
return getOrInsert(callFrameToFrameInfo, callFrame, callFrame => {
const name = callFrame.functionName || '(anonymous)'
const file = callFrame.url
// In Chrome profiles, line numbers & column numbers are both 0-indexed.
//
// We're going to normalize these to be 1-based to avoid needing to normalize
// these at the presentation layer.
let line = callFrame.lineNumber
if (line != null) line++
let col = callFrame.columnNumber
if (col != null) col++
const line = callFrame.lineNumber
const col = callFrame.columnNumber
return {
key: `${name}:${file}:${line}:${col}`,
name,
@@ -233,10 +224,6 @@ export function importFromChromeCPUProfile(chromeProfile: CPUProfile): Profile {
// Ref: https://github.com/v8/v8/blob/44bd8fd7/src/inspector/js_protocol.json#L1485
let elapsed = chromeProfile.timeDeltas[0]
// Prevents negative time deltas from causing bad data. See
// https://github.com/jlfwong/speedscope/pull/305 for details.
let lastValidElapsed = elapsed
let lastNodeId = NaN
// The chrome CPU profile format doesn't collapse identical samples. We'll do that
@@ -245,26 +232,22 @@ export function importFromChromeCPUProfile(chromeProfile: CPUProfile): Profile {
const nodeId = chromeProfile.samples[i]
if (nodeId != lastNodeId) {
samples.push(nodeId)
if (elapsed < lastValidElapsed) {
sampleTimes.push(lastValidElapsed)
} else {
sampleTimes.push(elapsed)
lastValidElapsed = elapsed
}
sampleTimes.push(elapsed)
}
if (i === chromeProfile.samples.length - 1) {
if (!isNaN(lastNodeId)) {
samples.push(lastNodeId)
if (elapsed < lastValidElapsed) {
sampleTimes.push(lastValidElapsed)
} else {
sampleTimes.push(elapsed)
lastValidElapsed = elapsed
}
sampleTimes.push(elapsed)
}
} else {
const timeDelta = chromeProfile.timeDeltas[i + 1]
let timeDelta = chromeProfile.timeDeltas[i + 1]
if (timeDelta < 0) {
// This is super noisy, but can be helpful when debugging strange data
// console.warn('Substituting zero for unexpected time delta:', timeDelta, 'at index', i)
timeDelta = 0
}
elapsed += timeDelta
lastNodeId = nodeId
}
+1 -5
View File
@@ -176,7 +176,7 @@ export function importFromFirefox(firefoxProfile: FirefoxProfile): Profile {
const frameData = thread.frameTable.data[f]
const location = thread.stringTable[frameData[0]]
const match = /(.*)\s+\((.*?)(?::(\d+))?(?::(\d+))?\)$/.exec(location)
const match = /(.*)\s+\((.*?):?(\d+)?\)$/.exec(location)
if (!match) return null
@@ -193,11 +193,7 @@ export function importFromFirefox(firefoxProfile: FirefoxProfile): Profile {
key: location,
name: match[1]!,
file: match[2]!,
// In Firefox profiles, line numbers are 1-based, but columns are
// 0-based. Let's normalize both to be 1-based.
line: match[3] ? parseInt(match[3]) : undefined,
col: match[4] ? parseInt(match[4]) + 1 : undefined,
}))
})
.filter(f => f != null) as FrameInfo[]
-7
View File
@@ -15,7 +15,6 @@ import {importSpeedscopeProfiles} from '../lib/file-format'
import {importFromV8ProfLog} from './v8proflog'
import {importFromLinuxPerf} from './linux-tools-perf'
import {importFromHaskell} from './haskell'
import {importFromSafari} from './safari'
import {ProfileDataSource, TextProfileDataSource, MaybeCompressedDataReader} from './utils'
import {importAsPprofProfile} from './pprof'
import {decodeBase64} from '../lib/utils'
@@ -132,9 +131,6 @@ async function _importProfileGroup(dataSource: ProfileDataSource): Promise<Profi
} else if (fileName.endsWith('.heapprofile')) {
console.log('Importing as Chrome Heap Profile')
return toGroup(importFromChromeHeapProfile(JSON.parse(contents)))
} else if (fileName.endsWith('-recording.json')) {
console.log('Importing as Safari profile')
return toGroup(importFromSafari(JSON.parse(contents)))
}
// Second pass: Try to guess what file format it is based on structure
@@ -173,9 +169,6 @@ async function _importProfileGroup(dataSource: ProfileDataSource): Promise<Profi
} else if ('rts_arguments' in parsed && 'initial_capabilities' in parsed) {
console.log('Importing as Haskell GHC JSON Profile')
return importFromHaskell(parsed)
} else if ('recording' in parsed && 'sampleStackTraces' in parsed.recording) {
console.log('Importing as Safari profile')
return toGroup(importFromSafari(JSON.parse(contents)))
}
} else {
// Format is not JSON
+2 -5
View File
@@ -633,7 +633,7 @@ export function readInstrumentsKeyedArchive(buffer: ArrayBuffer): any {
////////////////////////////////////////////////////////////////////////////////
export function decodeUTF8(bytes: Uint8Array): string {
let text = String.fromCharCode.apply(String, Array.from(bytes))
let text = String.fromCharCode.apply(String, bytes)
if (text.slice(-1) === '\0') text = text.slice(0, -1) // Remove a single trailing null character if present
return decodeURIComponent(escape(text))
}
@@ -740,10 +740,7 @@ function paternMatchObjectiveC(
// Replace NSString with a string
case 'NSString':
case 'NSMutableString':
if (value['NS.string']) return value['NS.string']
if (value['NS.bytes']) return decodeUTF8(value['NS.bytes'])
console.warn(`Unexpected ${name} format: `, value)
return null
return decodeUTF8(value['NS.bytes'])
// Replace NSArray with an Array
case 'NSArray':
+1 -1
View File
@@ -1,6 +1,6 @@
import {checkProfileSnapshot} from '../lib/test-utils'
describe('importFromLinuxPerf', () => {
describe('importFromLinuxPerf', async () => {
test('simple.linux-perf.txt', async () => {
await checkProfileSnapshot('./sample/profiles/linux-perf/simple.linux-perf.txt')
})
-5
View File
@@ -1,5 +0,0 @@
import {checkProfileSnapshot} from '../lib/test-utils'
test('importFromSafari', async () => {
await checkProfileSnapshot('./sample/profiles/Safari/13.1/simple.html-recording.json')
})
-120
View File
@@ -1,120 +0,0 @@
import {Profile, FrameInfo, StackListProfileBuilder} from '../lib/profile'
import {TimeFormatter} from '../lib/value-formatters'
interface Record {
type: string
eventType?: string
startTime?: number
endTime?: number
// timeline-record-type-cpu
timestamp?: number
usage?: number
threads?: any[]
// timeline-record-type-script
details?: number | string | any
extraDetails?: null | any
// timeline-record-type-network
archiveStartTime?: number
entry?: any
// timeline-record-type-layout
quad?: number[]
}
interface ExprLocation {
line: number
column: number
}
interface StackFrame {
sourceID: string
name: string
line: number
column: number
url: string
expressionLocation?: ExprLocation
}
interface Sample {
timestamp: number
stackFrames: StackFrame[]
}
interface Recording {
displayName: string
startTime: number
endTime: number
discontinuities: any[]
instrumentTypes: string[]
records: Record[]
markers: any[]
memoryPressureEvents: any[]
sampleStackTraces: Sample[]
sampleDurations: number[]
}
interface Overview {
secondsPerPixel: number
scrollStartTime: number
selectionStartTime: number
selectionDuration: number
}
interface SafariProfile {
version: number
recording: Recording
overview: Overview
}
function makeStack(frames: StackFrame[]): FrameInfo[] {
return frames
.map(({name, url, line, column}) => ({
key: `${name}:${url}:${line}:${column}`,
file: url,
line,
col: column,
name: name || '(anonymous)',
}))
.reverse()
}
export function importFromSafari(contents: SafariProfile): Profile | null {
if (contents.version !== 1) {
console.warn(`Unknown Safari profile version ${contents.version}... Might be incompatible.`)
}
const {recording} = contents
const {sampleStackTraces, sampleDurations} = recording
const count = sampleStackTraces.length
if (count < 1) {
console.warn('Empty profile')
return null
}
const profileDuration =
sampleStackTraces[count - 1].timestamp - sampleStackTraces[0].timestamp + sampleDurations[0]
const profile = new StackListProfileBuilder(profileDuration)
let previousEndTime = Number.MAX_VALUE
sampleStackTraces.forEach((sample, i) => {
const endTime = sample.timestamp
const duration = sampleDurations[i]
const startTime = endTime - duration
const idleDurationBefore = startTime - previousEndTime
// FIXME: 2ms is a lot, but Safari's timestamps and durations don't line up very well and will create
// phantom idle time
if (idleDurationBefore > 0.002) {
profile.appendSampleWithWeight([], idleDurationBefore)
}
profile.appendSampleWithWeight(makeStack(sample.stackFrames), duration)
previousEndTime = endTime
})
profile.setValueFormatter(new TimeFormatter('seconds'))
profile.setName(recording.displayName)
return profile.build()
}
-4
View File
@@ -27,7 +27,3 @@ test('importTraceEvents partial json import whitespace padding', async () => {
test('importTraceEvents bad E events', async () => {
await checkProfileSnapshot('./sample/profiles/trace-event/too-many-end-events.json')
})
test('importTraceEvents event re-ordering', async () => {
await checkProfileSnapshot('./sample/profiles/trace-event/must-retain-original-order.json')
})
+17 -20
View File
@@ -157,30 +157,27 @@ function eventListToProfileGroup(events: TraceEvent[]): ProfileGroup {
durationEvents.sort((a, b) => {
if (a.ts < b.ts) return -1
if (a.ts > b.ts) return 1
if (a.pid < b.pid) return -1
if (a.pid > b.pid) return 1
if (a.tid < b.tid) return -1
if (a.tid > b.tid) return 1
// We have to be careful with events that have the same timestamp
// and the same pid/tid
const aKey = keyForEvent(a)
const bKey = keyForEvent(b)
if (aKey === bKey) {
// If the two elements have the same key, we need to process the begin
// event before the end event. This will be a zero-duration event.
if (a.ph === 'B' && b.ph === 'E') return -1
if (a.ph === 'E' && b.ph === 'B') return 1
} else {
// If the two elements have *different* keys, we want to process
// the end of an event before the beginning of the event to prevent
// out-of-order push/pops from the call-stack.
if (a.ph === 'B' && b.ph === 'E') return 1
if (a.ph === 'E' && b.ph === 'B') return -1
if (a.pid === b.pid && a.tid === b.tid) {
const aKey = keyForEvent(a)
const bKey = keyForEvent(b)
if (aKey === bKey) {
// If the two elements have the same key, we need to process the begin
// event before the end event. This will be a zero-duration event.
if (a.ph === 'B' && b.ph === 'E') return -1
if (a.ph === 'E' && b.ph === 'B') return 1
} else {
// If the two elements have *different* keys, we want to process
// the end of an event before the beginning of the event to prevent
// out-of-order push/pops from the callstack.
if (a.ph === 'B' && b.ph === 'E') return 1
if (a.ph === 'E' && b.ph === 'B') return -1
}
}
// In all other cases, retain the original sort order.
return 0
return -1
})
if (durationEvents.length > 0) {
+5 -20
View File
@@ -51,30 +51,15 @@ export class MaybeCompressedDataReader implements ProfileDataSource {
async readAsText(): Promise<string> {
const buffer = await this.readAsArrayBuffer()
// By default, we assume the file is utf-8 encoded.
let encoding = 'utf-8'
const array = new Uint8Array(buffer)
if (array.length > 2) {
if (array[0] === 0xff && array[1] === 0xfe) {
// UTF-16, Little Endian encoding
encoding = 'utf-16le'
} else if (array[0] === 0xfe && array[1] === 0xff) {
// UTF-16, Big Endian encoding
encoding = 'utf-16be'
}
}
let ret: string = ''
if (typeof TextDecoder !== 'undefined') {
const decoder = new TextDecoder(encoding)
const decoder = new TextDecoder()
return decoder.decode(buffer)
} else {
// JavaScript strings are UTF-16 encoded, but we're reading data from disk
// that we're going to blindly assume it's ASCII encoded. This codepath
// only exists for older browser support.
console.warn('This browser does not support TextDecoder. Decoding text as ASCII.')
let ret: string = ''
// JavaScript strings are UTF-16 encoded, but we're reading data
// from disk that we're going to asusme is UTF-8 encoded.
const array = new Uint8Array(buffer)
for (let i = 0; i < array.length; i++) {
ret += String.fromCharCode(array[i])
}
-57
View File
@@ -1,57 +0,0 @@
// Versions of node before 10 had an unstable sort. This isn't really an issue in browsers
// that speedscope supports, but for the purposes of supporting node 10, we'll polyfill
// a stable sort to make the tests pass.
//
// See:
// - https://v8.dev/features/stable-sort
// - https://v8.dev/blog/array-sort
// - https://github.com/jlfwong/speedscope/pull/254#issuecomment-575116995
//
// Once we stop supporting node 10, this can be removed.
//
// An alternative would be to change our sort implementation to be stable by definition
// rather than relying upon native sort being stable. I don't want to do that because
// we'd take a perf hit.
//
// Because we're not going to use this in our actual build, it's okay for this
// to be inefficient.
;(function () {
const nodeVersion = process.versions.node
const versionParts = nodeVersion.split('.')
const majorVersion = parseInt(versionParts[0], 10)
if (majorVersion > 10) {
// Don't need to do the patch for newer node versions
return
}
const defaultCompareFunction = (a, b) => {
const sa = '' + a
const sb = '' + b
if (sa < sb) return -1
if (sa > sb) return 1
return 0
}
const originalSort = Array.prototype.sort
Array.prototype.sort = function (compareFunction) {
const arrayWithIndices = this.map((x, i) => [x, i])
originalSort.call(arrayWithIndices, (a, b) => {
if (!compareFunction) {
compareFunction = defaultCompareFunction
}
const res = compareFunction(a[0], b[0])
if (res !== 0) return res
return a[1] < b[1] ? -1 : 1
})
this.splice(0, this.length, ...arrayWithIndices.map(x => x[0]))
return this
}
})()
;(function () {
// TextDecoder is a global API in browsers, but an imported API in node.
//
// Let's emulate it being a global API during tests.
global.TextDecoder = require('util').TextDecoder
})()
@@ -211,7 +211,3 @@ Object {
exports[`importSpeedscopeProfiles 0.6.0 multiple profiles: indexToView 1`] = `1`;
exports[`importSpeedscopeProfiles 0.6.0 multiple profiles: profileGroup.name 1`] = `"Two Samples"`;
exports[`importSpeedscopeProfiles invalid due to incomplete trace 1`] = `"Tried to complete profile construction with a non-empty stack"`;
exports[`importSpeedscopeProfiles invalid due to out of order events 1`] = `"Tried to leave frame \\"B\\" while frame \\"A\\" was at the top at 4"`;
@@ -1,70 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`source-map remapping of chrome-85-esbuild 1`] = `
Array [
"((anonymous) @ alpha.ts:5:5) <- ((anonymous) @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/esbuild/typescript-source-map-test.js:1:170)",
"(e @ beta.ts:3:8) <- (e @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/esbuild/typescript-source-map-test.js:1:75)",
"(get floop @ kludge.ts:13:7) <- (get floop @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/esbuild/typescript-source-map-test.js:1:276)",
"(l constructor @ kludge.ts:4:3) <- (l @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/esbuild/typescript-source-map-test.js:1:226)",
"(m @ delta.ts:3:22) <- (m @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/esbuild/typescript-source-map-test.js:1:119)",
"(r @ alpha.ts:4:8) <- (r @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/esbuild/typescript-source-map-test.js:1:158)",
"(gamma @ gamma.ts:1:14) <- (t @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/esbuild/typescript-source-map-test.js:1:15)",
"(zap @ kludge.ts:9:3) <- (zap @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/esbuild/typescript-source-map-test.js:1:260)",
]
`;
exports[`source-map remapping of chrome-85-parcel 1`] = `
Array [
"((anonymous) @ ../alpha.ts:5:5) <- ((anonymous) @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:8:152)",
"(e @ ../gamma.ts:1:22) <- (e @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:2:104)",
"(get @ ../kludge.ts:13:3) <- (get @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:10:284)",
"(o.zap @ ../kludge.ts:9:3) <- (o.zap @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:10:211)",
"(o constructor @ ../kludge.ts:4:3) <- (o @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:10:139)",
"(parcelRequire.CIJJ../alpha @ ../alpha.ts:5:5) <- (parcelRequire.CIJJ../alpha @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:9:55)",
"(parcelRequire.EJAe../gamma @ ../gamma.ts:1:8) <- (parcelRequire.EJAe../gamma @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:3:23)",
"(parcelRequire.NDR3../beta @ ../delta.ts:3:8) <- (parcelRequire.NDR3../beta @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:7:39)",
"(parcelRequire.xEzo../kludge @ ../kludge.ts:3:1) <- (parcelRequire.xEzo../kludge @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:11:39)",
"(beta @ ../beta.ts:3:17) <- (r @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:4:119)",
"(r @ ../delta.ts:3:22) <- (r @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:6:125)",
"(alpha @ ../alpha.ts:4:17) <- (t @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/parcel/typescript-source-map-test.js:8:140)",
]
`;
exports[`source-map remapping of chrome-85-webpack 1`] = `
Array [
"((anonymous) @ webpack://speedscope-sourcemap-test-project/alpha.ts:5:4) <- ((anonymous) @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:181)",
"(get @ webpack://speedscope-sourcemap-test-project/kludge.ts:13:3) <- (get @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:368)",
"(n.zap @ webpack://speedscope-sourcemap-test-project/kludge.ts:9:3) <- (n.zap @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:305)",
"(n constructor @ webpack://speedscope-sourcemap-test-project/kludge.ts:4:3) <- (n @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:243)",
"(n @ webpack://speedscope-sourcemap-test-project/gamma.ts:1:22) <- (n @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:34)",
"(beta @ webpack://speedscope-sourcemap-test-project/beta.ts:3:17) <- (o @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:88)",
"(r @ webpack://speedscope-sourcemap-test-project/delta.ts:3:22) <- (r @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:130)",
"(alpha @ webpack://speedscope-sourcemap-test-project/alpha.ts:4:17) <- (t @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:169)",
]
`;
exports[`source-map remapping of firefox-79-webpack 1`] = `
Array [
"(get @ webpack://speedscope-sourcemap-test-project/kludge.ts:13:3) <- (get @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:368)",
"(n constructor @ webpack://speedscope-sourcemap-test-project/kludge.ts:4:3) <- (n @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:243)",
"(n @ webpack://speedscope-sourcemap-test-project/gamma.ts:1:22) <- (n @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:34)",
"(n.prototype.zap @ webpack://speedscope-sourcemap-test-project/kludge.ts:9:3) <- (n.prototype.zap @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:305)",
"(beta @ webpack://speedscope-sourcemap-test-project/beta.ts:3:17) <- (o @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:88)",
"(r @ webpack://speedscope-sourcemap-test-project/delta.ts:3:22) <- (r @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:130)",
"(alpha @ webpack://speedscope-sourcemap-test-project/alpha.ts:4:17) <- (t @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:169)",
"(t/< @ webpack://speedscope-sourcemap-test-project/alpha.ts:5:4) <- (t/< @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:181)",
]
`;
exports[`source-map remapping of safari-13-webpack 1`] = `
Array [
"((anonymous) @ webpack://speedscope-sourcemap-test-project/alpha.ts:5:4) <- ((anonymous) @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:181)",
"(zap @ webpack://speedscope-sourcemap-test-project/kludge.ts:9:3) <- ((anonymous) @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:305)",
"(get @ webpack://speedscope-sourcemap-test-project/kludge.ts:13:3) <- (get @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:368)",
"(n constructor @ webpack://speedscope-sourcemap-test-project/kludge.ts:4:3) <- (n @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:243)",
"(n @ webpack://speedscope-sourcemap-test-project/gamma.ts:1:22) <- (n @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:34)",
"(beta @ webpack://speedscope-sourcemap-test-project/beta.ts:3:17) <- (o @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:88)",
"(r @ webpack://speedscope-sourcemap-test-project/delta.ts:3:22) <- (r @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:130)",
"(alpha @ webpack://speedscope-sourcemap-test-project/alpha.ts:4:17) <- (t @ file:///Users/jlfwong/code/speedscope/sample/programs/javascript/sourcemaps/dist/webpack/typescript-source-map-test.js:1:169)",
]
`;
-69
View File
@@ -1,69 +0,0 @@
// This file contains a collection of classes which make it easier to perform
// batch rendering of Canvas2D primitives. The advantage of this over just doing
// ctx.beginPath() ... ctx.rect(...) ... ctx.endPath() is that you can construct
// several different batch renderers are the same time, then decide on their
// paint order at the end.
//
// See FlamechartPanZoomView.renderOverlays for an example of how this is used.
export interface TextArgs {
text: string
x: number
y: number
}
export class BatchCanvasTextRenderer {
private argsBatch: TextArgs[] = []
text(args: TextArgs) {
this.argsBatch.push(args)
}
fill(ctx: CanvasRenderingContext2D, color: string) {
if (this.argsBatch.length === 0) return
ctx.fillStyle = color
for (let args of this.argsBatch) {
ctx.fillText(args.text, args.x, args.y)
}
this.argsBatch = []
}
}
export interface RectArgs {
x: number
y: number
w: number
h: number
}
export class BatchCanvasRectRenderer {
private argsBatch: RectArgs[] = []
rect(args: RectArgs) {
this.argsBatch.push(args)
}
private drawPath(ctx: CanvasRenderingContext2D) {
ctx.beginPath()
for (let args of this.argsBatch) {
ctx.rect(args.x, args.y, args.w, args.h)
}
ctx.closePath()
this.argsBatch = []
}
fill(ctx: CanvasRenderingContext2D, color: string) {
if (this.argsBatch.length === 0) return
ctx.fillStyle = color
this.drawPath(ctx)
ctx.fill()
}
stroke(ctx: CanvasRenderingContext2D, color: string, lineWidth: number) {
if (this.argsBatch.length === 0) return
ctx.strokeStyle = color
ctx.lineWidth = lineWidth
this.drawPath(ctx)
ctx.stroke()
}
}
+9 -9
View File
@@ -15,19 +15,19 @@ export class Color {
// https://en.wikipedia.org/wiki/HSL_and_HSV#From_luma/chroma/hue
const hPrime = H / 60
const X = C * (1 - Math.abs((hPrime % 2) - 1))
const X = C * (1 - Math.abs(hPrime % 2 - 1))
const [R1, G1, B1] =
hPrime < 1
? [C, X, 0]
: hPrime < 2
? [X, C, 0]
: hPrime < 3
? [0, C, X]
: hPrime < 4
? [0, X, C]
: hPrime < 5
? [X, 0, C]
: [C, 0, X]
? [X, C, 0]
: hPrime < 3
? [0, C, X]
: hPrime < 4
? [0, X, C]
: hPrime < 5
? [X, 0, C]
: [C, 0, X]
const m = L - (0.3 * R1 + 0.59 * G1 + 0.11 * B1)
+42 -60
View File
@@ -1,72 +1,54 @@
import {importEmscriptenSymbolMap} from './emscripten'
import {Frame} from './profile'
import {KeyedSet} from './utils'
test('importEmscriptenSymbolMap', () => {
function checkMap(input: string, expectedMapping: [string, string][]) {
const mapping = importEmscriptenSymbolMap(input)
if (mapping == null) {
fail('Mapping failed to parse')
return
}
const frames = new KeyedSet<Frame>()
for (let [key, value] of expectedMapping) {
const frame = Frame.getOrInsert(frames, {key, name: key})
expect(mapping(frame)?.name).toBe(value)
}
}
// Valid symbol map
checkMap(
[
/* prettier: ignore */
'a:A',
'b:B',
'c:C',
].join('\n'),
[
['a', 'A'],
['b', 'B'],
['c', 'C'],
],
)
expect(
importEmscriptenSymbolMap(
[
/* prettier: ignore */
'a:A',
'b:B',
'c:C',
].join('\n'),
),
).toEqual(new Map([['a', 'A'], ['b', 'B'], ['c', 'C']]))
// Valid symbol map with trailing newline
checkMap(
[
/* prettier: ignore */
'a:A',
'b:B',
'c:C',
'd:D-D',
'',
].join('\n'),
[
['a', 'A'],
['b', 'B'],
['c', 'C'],
['d', 'D-D'],
],
)
expect(
importEmscriptenSymbolMap(
[
/* prettier: ignore */
'a:A',
'b:B',
'c:C',
'd:D-D',
'',
].join('\n'),
),
).toEqual(new Map([['a', 'A'], ['b', 'B'], ['c', 'C'], ['d', 'D-D']]))
// Valid symbol map with non-alpha characters
checkMap('u6:__ZN8tinyxml210XMLCommentD0Ev\n', [['u6', '__ZN8tinyxml210XMLCommentD0Ev']])
expect(importEmscriptenSymbolMap('u6:__ZN8tinyxml210XMLCommentD0Ev\n')).toEqual(
new Map([['u6', '__ZN8tinyxml210XMLCommentD0Ev']]),
)
// WebAssembly symbol map
checkMap(
[
/* prettier: ignore */
'0:A',
'1:B',
'2:C',
'3:D-D',
'4:a\\20b',
'5:a\\2',
'6:a\\3z',
'7:a\\20b\\20c',
].join('\n'),
[
expect(
importEmscriptenSymbolMap(
[
/* prettier: ignore */
'0:A',
'1:B',
'2:C',
'3:D-D',
'4:a\\20b',
'5:a\\2',
'6:a\\3z',
'7:a\\20b\\20c',
].join('\n'),
),
).toEqual(
new Map([
['wasm-function[0]', 'A'],
['wasm-function[1]', 'B'],
['wasm-function[2]', 'C'],
@@ -75,7 +57,7 @@ test('importEmscriptenSymbolMap', () => {
['wasm-function[5]', 'a\\2'],
['wasm-function[6]', 'a\\3z'],
['wasm-function[7]', 'a b c'],
],
]),
)
// Invalid symbol map
+5 -12
View File
@@ -1,8 +1,7 @@
type EmscriptenSymbolMap = Map<string, string>
// Returns `input` with hex escapes expanded (e.g. `\20` becomes ` `.)
//
import {Frame, SymbolRemapper} from './profile'
// NOTE: This will fail to ignore escaped backslahes (e.g. `\\20`).
function unescapeHex(input: string): string {
return input.replace(/\\([a-fA-F0-9]{2})/g, (_match, group) => {
@@ -16,7 +15,7 @@ function unescapeHex(input: string): string {
// have the associated symbol map. To do this, first drop the profile into speedscope
// and then drop the symbol map. After the second drop, the symbols will be remapped to
// their original names.
export function importEmscriptenSymbolMap(contents: string): SymbolRemapper | null {
export function importEmscriptenSymbolMap(contents: string): EmscriptenSymbolMap | null {
const lines = contents.split('\n')
if (!lines.length) return null
@@ -24,7 +23,7 @@ export function importEmscriptenSymbolMap(contents: string): SymbolRemapper | nu
if (lines[lines.length - 1] === '') lines.pop()
if (!lines.length) return null
const map = new Map<string, string>()
const map: EmscriptenSymbolMap = new Map()
const intRegex = /^(\d+):(.+)$/
const idRegex = /^([\$\w]+):([\$\w-]+)$/
@@ -46,11 +45,5 @@ export function importEmscriptenSymbolMap(contents: string): SymbolRemapper | nu
return null
}
return (frame: Frame) => {
if (!map.has(frame.name)) {
return null
}
return {name: map.get(frame.name)}
}
return map
}
+2 -11
View File
@@ -1,6 +1,6 @@
import {checkProfileSnapshot, expectImportFailure} from './test-utils'
import {checkProfileSnapshot} from './test-utils'
describe('importSpeedscopeProfiles', () => {
describe('importSpeedscopeProfiles', async () => {
test('0.0.1 evented profile', async () => {
await checkProfileSnapshot('./sample/profiles/speedscope/0.0.1/simple.speedscope.json')
})
@@ -12,13 +12,4 @@ describe('importSpeedscopeProfiles', () => {
test('0.6.0 multiple profiles', async () => {
await checkProfileSnapshot('./sample/profiles/speedscope/0.6.0/two-sampled.speedscope.json')
})
test('invalid due to out of order events', async () => {
// See: https://github.com/jlfwong/speedscope/issues/272
await expectImportFailure('./sample/profiles/speedscope/invalid/out-of-order-events.json')
})
test('invalid due to incomplete trace', async () => {
await expectImportFailure('./sample/profiles/speedscope/invalid/incomplete-trace.json')
})
})
+1 -4
View File
@@ -138,10 +138,7 @@ function importSpeedscopeProfile(
for (let i = 0; i < samples.length; i++) {
const stack = samples[i]
const weight = weights[i]
profile.appendSampleWithWeight(
stack.map(n => frameInfos[n]),
weight,
)
profile.appendSampleWithWeight(stack.map(n => frameInfos[n]), weight)
}
return profile.build()
+1 -22
View File
@@ -1,7 +1,7 @@
import {Frame, CallTreeNode} from './profile'
import {lastOf} from './utils'
import {clamp, Rect, Vec2} from './math'
import {clamp} from './math'
export interface FlamechartFrame {
node: CallTreeNode
@@ -90,27 +90,6 @@ export class Flamechart {
return clamp(viewportWidth, minWidth, maxWidth)
}
// Given a desired config-space viewport rectangle, clamp the rectangle so
// that it fits within the given flamechart. This prevents the viewport from
// extending past the bounds of the flamechart or zooming in too far.
getClampedConfigSpaceViewportRect({
configSpaceViewportRect,
renderInverted,
}: {
configSpaceViewportRect: Rect
renderInverted?: boolean
}) {
const configSpaceSize = new Vec2(this.getTotalWeight(), this.getLayers().length)
const width = this.getClampedViewportWidth(configSpaceViewportRect.size.x)
const size = configSpaceViewportRect.size.withX(width)
const origin = Vec2.clamp(
configSpaceViewportRect.origin,
new Vec2(0, renderInverted ? 0 : -1),
Vec2.max(Vec2.zero, configSpaceSize.minus(size).plus(new Vec2(0, 1))),
)
return new Rect(origin, configSpaceViewportRect.size.withX(width))
}
constructor(private source: FlamechartDataSource) {
const stack: FlamechartFrame[] = []
const openFrame = (node: CallTreeNode, value: number) => {
-81
View File
@@ -1,81 +0,0 @@
import {fuzzyMatchStrings} from './fuzzy-find'
import {sortBy} from './utils'
function assertMatches(texts: string[], pattern: string, expectedResults: string[]) {
const results: {score: number; highlighted: string}[] = []
for (let text of texts) {
const match = fuzzyMatchStrings(text, pattern)
if (match == null) {
continue
}
let highlighted = ''
let last = 0
for (let range of match.matchedRanges) {
highlighted += `${text.slice(last, range[0])}[${text.slice(range[0], range[1])}]`
last = range[1]
}
highlighted += text.slice(last)
results.push({score: match.score, highlighted})
}
// Sort scores in descending order
sortBy(results, r => -r.score)
expect(results.map(r => r.highlighted)).toEqual(expectedResults)
}
function assertMatch(text: string, pattern: string, expected: string) {
assertMatches([text], pattern, [expected])
}
function assertNoMatch(text: string, pattern: string) {
assertMatches([text], pattern, [])
}
describe('fuzzyMatchStrings', () => {
test('no match', () => {
assertNoMatch('a', 'b')
assertNoMatch('aa', 'ab')
assertNoMatch('a', 'aa')
assertNoMatch('ca', 'ac')
})
test('full text match', () => {
assertMatch('hello', 'hello', '[hello]')
assertMatch('multiple words', 'multiple words', '[multiple words]')
})
test('case sensitivity', () => {
assertMatch('HELLO', 'hello', '[HELLO]')
assertMatch('Hello', 'hello', '[Hello]')
assertNoMatch('hello', 'Hello')
assertNoMatch('hello', 'HELLO')
})
test('multiple occurrences', () => {
assertMatch('hello hello', 'hello', '[hello] hello')
assertMatch('hellohello', 'hello', '[hello]hello')
})
test('prefer earlier matches', () => {
assertMatches(['cab', 'ab'], 'ab', ['[ab]', 'c[ab]'])
})
test('prefer shorter matches', () => {
assertMatches(['abbc', 'abc', 'abbbc'], 'ac', ['[a]b[c]', '[a]bb[c]', '[a]bbb[c]'])
})
test('prefer word boundaries', () => {
assertMatches(['abc', 'a c'], 'ac', ['[a] [c]', '[a]b[c]'])
})
test('prefer camelCase matches', () => {
assertMatches(['downtown', 'OutNode'], 'n', ['Out[N]ode', 'dow[n]town'])
})
test('prefer number prefix matches', () => {
assertMatches(['211', 'a123'], '1', ['a[1]23', '2[1]1'])
})
})
-246
View File
@@ -1,246 +0,0 @@
/**
* This file contains an implementation of fuzzy string matching.
*/
export interface FuzzyMatch {
// List of [start, end] indices in the haystack string that match the needle string
matchedRanges: [number, number][]
// The score of the match for relative ranking. Higher scores indicate
// "better" matches.
score: number
}
export function fuzzyMatchStrings(text: string, pattern: string): FuzzyMatch | null {
return fzfFuzzyMatchV1(text, pattern)
}
// The implementation here is based on FuzzyMatchV1, as described here:
// https://github.com/junegunn/fzf/blob/f81feb1e69e5cb75797d50817752ddfe4933cd68/src/algo/algo.go#L8-L15
//
// This is a hand-port to better understand what the code is doing and for added
// clarity.
//
// Capitalized letters only match capitalized letters, but lower-case letters
// match both.
//
// Note: fzf includes a normalization table for homoglyphs. I'm going to ignore that too
// https://github.com/junegunn/fzf/blob/master/src/algo/normalize.go
const charCodeLowerA = 'a'.charCodeAt(0)
const charCodeLowerZ = 'z'.charCodeAt(0)
const charCodeUpperA = 'A'.charCodeAt(0)
const charCodeUpperZ = 'Z'.charCodeAt(0)
const charCodeDigit0 = '0'.charCodeAt(0)
const charCodeDigit9 = '9'.charCodeAt(0)
enum fzfCharClass {
charNonWord,
charLower,
charUpper,
charNumber,
}
function fzfCharClassOf(char: string): fzfCharClass {
const code = char.charCodeAt(0)
if (charCodeLowerA <= code && code <= charCodeLowerZ) {
return fzfCharClass.charLower
} else if (charCodeUpperA <= code && code <= charCodeUpperZ) {
return fzfCharClass.charUpper
} else if (charCodeDigit0 <= code && code <= charCodeDigit9) {
return fzfCharClass.charNumber
}
return fzfCharClass.charNonWord
}
function charsMatch(textChar: string, patternChar: string): boolean {
if (textChar === patternChar) return true
const patternCharCode = patternChar.charCodeAt(0)
if (charCodeLowerA <= patternCharCode && patternCharCode <= charCodeLowerZ) {
return textChar.charCodeAt(0) === patternCharCode - charCodeLowerA + charCodeUpperA
}
return false
}
function fzfFuzzyMatchV1(text: string, pattern: string): FuzzyMatch | null {
if (pattern.length == 0) {
return {matchedRanges: [], score: 0}
}
// I removed the fzfAsciiFuzzyIndex code because it's not actually clear to
// me that it's a very helpful optimization.
let pidx = 0
let sidx = -1
let eidx = -1
let lenRunes = text.length
let lenPattern = pattern.length
// Forward pass: scan over the text pattern, identifying the earliest start
// and the latest end to consider.
for (let index = 0; index < lenRunes; index++) {
let char = text[index]
let pchar = pattern[pidx]
if (charsMatch(char, pchar)) {
if (sidx < 0) {
sidx = index
}
pidx++
if (pidx == lenPattern) {
// We found the last character in the pattern! eidx is exclusive, so
// we'll set it to the current index + 1.
eidx = index + 1
break
}
}
}
if (eidx == -1) {
// We couldn't find all the characters in the pattern. No match.
return null
}
// Assuming we found all the characters in the pattern, perform the backwards
// pass.
pidx--
for (let index = eidx - 1; index >= sidx; index--) {
const char = text[index]
const pchar = pattern[pidx]
if (charsMatch(char, pchar)) {
pidx--
if (pidx < 0) {
// We found the first character of the pattern, scanning
// backwards. This *may* have narrowed the match further.
// For example, for the following inputs:
//
// text = "xxx a b c abc xxx"
// pattern = "abc"
//
// For the forward pass, you get:
//
// "xxx a b c abc xxx"
// start^ ^end
//
// But after the backward pass, we can narrow this to:
//
// "xxx a b c abc xxx"
// start^ ^end
sidx = index
return fzfCalculateScore(text, pattern, sidx, eidx)
}
}
}
// This should be unreachable.
throw new Error('Implementation error. This must be a bug in fzfFuzzyMatchV1')
}
const fzfScoreMatch = 16
const fzfScoreGapStart = -3
const fzfScoreGapExtension = -1
const fzfBonusBoundary = fzfScoreMatch / 2
const fzfBonusNonWord = fzfScoreMatch / 2
const fzfBonusCamel123 = fzfBonusBoundary + fzfScoreGapExtension
const fzfBonusConsecutive = -(fzfScoreGapStart + fzfScoreGapExtension)
const fzfBonusFirstCharMultiplier = 2
function bonusFor(prevClass: fzfCharClass, curClass: fzfCharClass): number {
if (prevClass === fzfCharClass.charNonWord && curClass !== fzfCharClass.charNonWord) {
// Prefer matching at word boundaries
//
// This should prefer "a c" over "abc" for a pattern of "ac".
return fzfBonusBoundary
}
if (
(prevClass === fzfCharClass.charLower && curClass == fzfCharClass.charUpper) ||
(prevClass !== fzfCharClass.charNumber && curClass == fzfCharClass.charNumber)
) {
// Prefer matching at the transition point between lower & upper for camelCase,
// and from transition from letter to number for identifiers like letter123.
//
// This should prefer "OutNode" over "phone" for a pattern of "n",
// and "abc123" over "x211" for a pattern of "1".
return fzfBonusCamel123
}
if (curClass === fzfCharClass.charNonWord) {
return fzfBonusNonWord
}
return 0
}
function fzfCalculateScore(text: string, pattern: string, sidx: number, eidx: number): FuzzyMatch {
let pidx = 0
let score = 0
let inGap = false
let consecutive = 0
let firstBonus = 0
let pos: number[] = new Array(pattern.length)
let prevClass = fzfCharClass.charNonWord
if (sidx > 0) {
prevClass = fzfCharClassOf(text[sidx - 1])
}
for (let idx = sidx; idx < eidx; idx++) {
let char = text[idx]
let curClass = fzfCharClassOf(char)
if (charsMatch(char, pattern[pidx])) {
pos[pidx] = idx
score += fzfScoreMatch
let bonus = bonusFor(prevClass, curClass)
if (consecutive == 0) {
firstBonus = bonus
} else {
// Break consecutive chunk
if (bonus === fzfBonusBoundary) {
firstBonus = bonus
}
bonus = Math.max(bonus, firstBonus, fzfBonusConsecutive)
}
if (pidx === 0) {
score += bonus * fzfBonusFirstCharMultiplier
} else {
score += bonus
}
inGap = false
consecutive++
pidx++
} else {
if (inGap) {
// Penalize gaps (this bonus is negative)
score += fzfScoreGapExtension
} else {
// Penalize the beginning of gaps more harshly
score += fzfScoreGapStart
}
inGap = true
consecutive = 0
firstBonus = 0
}
prevClass = curClass
}
if (pidx !== pattern.length) {
throw new Error(
'fzfCalculateScore should only be called when pattern is found between sidx and eidx',
)
}
let matchedRanges: [number, number][] = [[pos[0], pos[0] + 1]]
for (let i = 1; i < pos.length; i++) {
const curPos = pos[i]
const curRange = matchedRanges[matchedRanges.length - 1]
if (curRange[1] === curPos) {
curRange[1] = curPos + 1
} else {
matchedRanges.push([curPos, curPos + 1])
}
}
return {
score,
matchedRanges,
}
}
-86
View File
@@ -1,86 +0,0 @@
import * as fs from 'fs'
import * as path from 'path'
import {importProfilesFromArrayBuffer} from '../import'
import {importJavaScriptSourceMapSymbolRemapper} from './js-source-map'
import {Frame} from './profile'
async function checkSourceMapApplication(pathToProfile: string, pathToSourceMap: string) {
const buffer = fs.readFileSync(pathToProfile)
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)
const profileGroup = await importProfilesFromArrayBuffer(
path.basename(pathToProfile),
arrayBuffer,
)
if (!profileGroup) {
fail('Failed to extract profile')
return
}
const sourceMapFileName = path.basename(pathToSourceMap)
const remapper = await importJavaScriptSourceMapSymbolRemapper(
fs.readFileSync(pathToSourceMap, 'utf-8'),
sourceMapFileName,
)
if (!remapper) {
fail('Failed to extract sourcemap')
return
}
const key: (f: {name?: string; file?: string; line?: number; col?: number}) => string = f => {
return `${f.name} @ ${f.file}:${f.line}:${f.col}`
}
const frames: Frame[] = []
profileGroup.profiles[profileGroup.indexToView].forEachFrame(f => {
frames.push(f)
})
frames.sort((a, b) => (a.key < b.key ? -1 : 1))
const remappedFrames: string[] = []
frames.forEach(f => {
const remapped = remapper(f)
if (!remapped) return
remappedFrames.push(`(${key({...f, ...remapped})}) <- (${key(f)})`)
})
expect(remappedFrames).toMatchSnapshot()
}
test('source-map remapping of chrome-85-webpack', async () => {
await checkSourceMapApplication(
'./sample/profiles/source-maps/chrome-85-webpack.json',
'./sample/profiles/source-maps/webpack/typescript-source-map-test.js.map',
)
})
test('source-map remapping of firefox-79-webpack', async () => {
await checkSourceMapApplication(
'./sample/profiles/source-maps/firefox-79-webpack.json',
'./sample/profiles/source-maps/webpack/typescript-source-map-test.js.map',
)
})
test('source-map remapping of safari-13-webpack', async () => {
await checkSourceMapApplication(
'./sample/profiles/source-maps/safari-13-webpack.json',
'./sample/profiles/source-maps/webpack/typescript-source-map-test.js.map',
)
})
test('source-map remapping of chrome-85-esbuild', async () => {
await checkSourceMapApplication(
'./sample/profiles/source-maps/chrome-85-esbuild.json',
'./sample/profiles/source-maps/esbuild/typescript-source-map-test.js.map',
)
})
test('source-map remapping of chrome-85-parcel', async () => {
await checkSourceMapApplication(
'./sample/profiles/source-maps/chrome-85-parcel.json',
'./sample/profiles/source-maps/parcel/typescript-source-map-test.js.map',
)
})
-227
View File
@@ -1,227 +0,0 @@
// This file contains code to allow profiles to be remapped by JavaScript source maps.
//
// As of writing, this is using an out-of-date version of source-map, because the
// source-map library migrated to using web-assembly. This requires loading the
// web-assembly ball. The easiest way to do this is to load it from a third-party
// URL, but I want speedscope to work standalone offline. This means that the remaining
// options require some way of having a local URL that corresponds the .wasm file.
//
// Also as of writing, speedscope is bundled with Parcel v1. Trying to import
// a .wasm file in Parcel v1 tries to load the wasm module itself, which is not
// what I'm trying to do -- I want SourceMapConsumer.initialize to be the thing
// booting the WebAssembly, not Parcel itself.
//
// One way of getting around this problem is to modify the build system to
// copy the .wasm file from node_modules/source-map/lib/mappings.wasm. I could do
// this, but it's a bit of a pain.
//
// Another would be to use something like
// import("url:../node_modules/source-map/lib/mappings.wasm"), and then pass the
// resulting URL to SourceMapConsumer.initialize. This is also kind of a pain,
// because I can only do that if I upgrade to Parcel v2. Ultimately, I'd like to
// use esbuild rather than parcel at all, so for now I'm just punting on this by
// using an old-version of source-map which doesn't depend on wasm.
// This is rarely used, so let's load it async to avoid bloating the initial
// bundle.
import type {MappingItem, RawSourceMap, SourceMapConsumer} from 'source-map'
const sourceMapModule = import('source-map')
import {Frame, SymbolRemapper} from './profile'
import {findIndexBisect} from './utils'
const DEBUG = false
export async function importJavaScriptSourceMapSymbolRemapper(
contentsString: string,
sourceMapFileName: string,
): Promise<SymbolRemapper | null> {
const sourceMap = await sourceMapModule
let consumer: SourceMapConsumer | null = null
let contents: RawSourceMap | null = null
try {
contents = JSON.parse(contentsString)
consumer = new sourceMap.SourceMapConsumer(contents!)
} catch (e) {
return null
}
const mappingItems: MappingItem[] = []
consumer.eachMapping(
function (m: MappingItem) {
// The sourcemap library uses 1-based line numbers, and 0-based column
// numbers. speedscope uses 1-based line-numbers, and 1-based column
// numbers for its in-memory representation, so we'll normalize that
// here too.
mappingItems.push({
...m,
generatedColumn: m.generatedColumn + 1,
originalColumn: m.originalColumn + 1,
})
},
{},
// We're going to binary search through these later, so make sure they're
// sorted by their order in the generated file.
sourceMap.SourceMapConsumer.GENERATED_ORDER,
)
const sourceMapFileNameWithoutExt = sourceMapFileName.replace(/\.[^/]*$/, '')
return (frame: Frame) => {
let fileMatches = false
if (contents?.file && contents?.file === frame.file) {
fileMatches = true
} else if (
('/' + frame.file?.replace(/\.[^/]*$/, '')).endsWith('/' + sourceMapFileNameWithoutExt)
) {
fileMatches = true
}
if (!fileMatches) {
// The source-map doesn't apply to the file this frame is defined in.
return null
}
if (frame.line == null || frame.col == null) {
// If we don't have a line & column number for the frame, we can't
// remap it.
return null
}
// If we got here, then we hopefully have an remapping.
//
// Ideally, we'd look up a symbol whose generatedLine & generatedColumn
// match what we have in our profile, but unfortunately browsers don't do
// this.
//
// Browsers set the column number for a function to the index of the
// opening paren for the argument list, rather than the beginning of the
// index of the name.
//
// function alpha() { ... }
// ^
//
// const beta = function() { ... }
// ^
//
// const gamma = () => { ... }
// ^
//
// Since we don't have the source code being profiled, we unfortunately
// can't normalize this to set the column to the first character of the
// actual name.
//
// To work around this limitation, we'll search backwards from the first
// mapping whose generatedLine & generatedColumn are beyond the location
// in the profile.
let mappingIndex = findIndexBisect(mappingItems, m => {
if (m.generatedLine > frame.line!) return true
if (m.generatedLine < frame.line!) return false
if (m.generatedColumn >= frame.col!) return true
return false
})
if (mappingIndex === -1) {
// There are no symbols following the given profile frame symbol, so try
// to apply the very last mapping.
mappingIndex = mappingItems.length - 1
} else if (mappingIndex === 0) {
// If the very first index in mappingItems is beyond the location in the
// profile, it means the name we're looking for doesn't have a
// corresponding entry in the source-map (this can happen if the
// source-map isn't the right source-map)
return null
} else {
mappingIndex--
}
const sourceMapItem = mappingItems[mappingIndex]
const remappedFrameInfo: {name?: string; file?: string; line?: number; col?: number} = {}
if (sourceMapItem.name != null) {
remappedFrameInfo.name = sourceMapItem.name
} else if (sourceMapItem.source != null) {
// HACK: If the item name isn't specified, but the source is present, then
// we're going to try to guess what the name is by using the originalLine
// and originalColumn.
// The second argument here is "returnNullOnMissing". Without this, it
// throws instead of returning null.
const content = consumer?.sourceContentFor(sourceMapItem.source, true)
if (content) {
const lines = content.split('\n')
const line = lines[sourceMapItem.originalLine - 1]
if (line) {
// It's possible this source map entry will contain stuff other than
// the name, so let's only consider word-ish characters that are part
// of the prefix.
const identifierMatch = /\w+/.exec(line.substr(sourceMapItem.originalColumn - 1))
if (identifierMatch) {
remappedFrameInfo.name = identifierMatch[0]
}
}
}
}
switch (remappedFrameInfo.name) {
case 'constructor': {
// If the name was remapped to "constructor", then let's use the
// original name, since "constructor" isn't very helpful.
//
// TODO(jlfwong): Search backwards for the class keyword and see if we
// can guess the right name.
remappedFrameInfo.name = frame.name + ' constructor'
break
}
case 'function': {
// If the name is just "function", it probably means we either messed up
// the remapping, or that we matched an anonymous function. In either
// case, this isn't helpful, so put this back.
remappedFrameInfo.name = frame.name
break
}
case 'const':
case 'export': {
// If we got this, we probably just did a bad job leveraging the hack
// looking through the source code. Let's fall-back to whatever the
// original name was.
remappedFrameInfo.name = frame.name
break
}
}
if (remappedFrameInfo.name && frame.name.includes(remappedFrameInfo.name)) {
// If the remapped name is a substring of the original name, the original
// name probably contains more useful information. In that case, just use
// the original name instead.
//
// This can happen, for example, when remapping method names. If a
// call stack says the symbol name is "n.zap" and we remapped it to a
// function just called "zap", we might as well use the original name
// instead.
remappedFrameInfo.name = frame.name
}
if (sourceMapItem.source != null) {
remappedFrameInfo.file = sourceMapItem.source
remappedFrameInfo.line = sourceMapItem.originalLine
remappedFrameInfo.col = sourceMapItem.originalColumn
}
if (DEBUG) {
console.groupCollapsed(`Remapping "${frame.name}" -> "${remappedFrameInfo.name}"`)
console.log('before', {...frame})
console.log('item @ index', sourceMapItem)
console.log('item @ index + 1', mappingItems[mappingIndex + 1])
console.log('after', remappedFrameInfo)
console.groupEnd()
}
return remappedFrameInfo
}
}
+45 -25
View File
@@ -13,10 +13,9 @@ test('clamp', () => {
// Change this to jsc.integer to debug failures more easily
let numericType = jsc.number
const arbitraryVec2 = jsc.record({x: jsc.integer, y: numericType}).smap(
v => new Vec2(v.x, v.y),
v => v,
)
const arbitraryVec2 = jsc
.record({x: jsc.integer, y: numericType})
.smap(v => new Vec2(v.x, v.y), v => v)
const positiveVec2 = jsc.suchthat(arbitraryVec2, v => v.x > 0 && v.y > 0)
@@ -29,25 +28,23 @@ const arbitraryTransform = jsc
m11: numericType,
m12: numericType,
})
.smap(
t => new AffineTransform(t.m00, t.m01, t.m02, t.m10, t.m11, t.m12),
t => t,
)
.smap(t => new AffineTransform(t.m00, t.m01, t.m02, t.m10, t.m11, t.m12), t => t)
const invertibleTransform = jsc.suchthat(arbitraryTransform, t => t.det() != 0)
const simpleTransform = jsc.suchthat(
jsc.record({scale: arbitraryVec2, translation: arbitraryVec2}).smap(
t => AffineTransform.withScale(t.scale).withTranslation(t.translation),
t => ({scale: t.getScale(), translation: t.getTranslation()}),
),
jsc
.record({scale: arbitraryVec2, translation: arbitraryVec2})
.smap(
t => AffineTransform.withScale(t.scale).withTranslation(t.translation),
t => ({scale: t.getScale(), translation: t.getTranslation()}),
),
t => t.det() != 0,
)
const arbitraryRect = jsc.record({origin: arbitraryVec2, size: positiveVec2}).smap(
r => new Rect(r.origin, r.size),
r => r,
)
const arbitraryRect = jsc
.record({origin: arbitraryVec2, size: positiveVec2})
.smap(r => new Rect(r.origin, r.size), r => r)
describe('Vec2', () => {
test('constructor', () => {
@@ -266,35 +263,51 @@ describe('AffineTransform', () => {
expect(new AffineTransform(0, 0, 0, 0, 0, 0).inverted()).toBe(null)
jsc.assertForall(invertibleTransform, t => {
return t.inverted()!.inverted()!.approxEquals(t)
return t
.inverted()!
.inverted()!
.approxEquals(t)
})
})
test('translation', () => {
jsc.assertForall(arbitraryTransform, arbitraryVec2, (t, v1) => {
return t.withTranslation(v1).getTranslation().equals(v1)
return t
.withTranslation(v1)
.getTranslation()
.equals(v1)
})
jsc.assertForall(arbitraryTransform, arbitraryVec2, (t, v1) => {
const initialTranslation = t.getTranslation()
return t.translatedBy(v1).getTranslation().approxEquals(initialTranslation.plus(v1))
return t
.translatedBy(v1)
.getTranslation()
.approxEquals(initialTranslation.plus(v1))
})
})
test('scale', () => {
jsc.assertForall(arbitraryTransform, arbitraryVec2, (t, v1) => {
return t.withScale(v1).getScale().equals(v1)
return t
.withScale(v1)
.getScale()
.equals(v1)
})
})
test('transformVector', () => {
// Vector transformation are translation-invariant
jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => {
return AffineTransform.withTranslation(v1).transformVector(v2).approxEquals(v2)
return AffineTransform.withTranslation(v1)
.transformVector(v2)
.approxEquals(v2)
})
jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => {
return AffineTransform.withScale(v1).transformVector(v2).approxEquals(v2.timesPointwise(v1))
return AffineTransform.withScale(v1)
.transformVector(v2)
.approxEquals(v2.timesPointwise(v1))
})
})
@@ -306,11 +319,15 @@ describe('AffineTransform', () => {
test('transformPosition', () => {
jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => {
return AffineTransform.withTranslation(v1).transformPosition(v2).approxEquals(v2.plus(v1))
return AffineTransform.withTranslation(v1)
.transformPosition(v2)
.approxEquals(v2.plus(v1))
})
jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => {
return AffineTransform.withScale(v1).transformPosition(v2).approxEquals(v2.timesPointwise(v1))
return AffineTransform.withScale(v1)
.transformPosition(v2)
.approxEquals(v2.timesPointwise(v1))
})
})
@@ -342,7 +359,10 @@ describe('AffineTransform', () => {
test('times', () => {
jsc.assertForall(invertibleTransform, invertibleTransform, (t1, t2) => {
return t1.times(t2).times(t2.inverted()!).approxEquals(t1)
return t1
.times(t2)
.times(t2.inverted()!)
.approxEquals(t1)
})
})
})
-74
View File
@@ -1,74 +0,0 @@
/**
* As of Preact 10.x, they no longer have an officially supported preact-redux library.
* It's possible to use react-redux with some hacks, but these hacks cause npm run pack
* to error out because of (intentionally) unmet peer dependencies.
*
* I could stack more hacks to fix this problem, but I'd rather just drop the dependency
* and remove the need to do any dependency hacking by writing the very small part of
* react-redux that I actually need myself.
*/
import {h} from 'preact'
import * as redux from 'redux'
import {createContext, ComponentChildren} from 'preact'
import {Dispatch, Action} from './typed-redux'
import {useState, useContext, useCallback, useLayoutEffect} from 'preact/hooks'
const PreactRedux = createContext<redux.Store<any> | null>(null)
interface ProviderProps {
store: redux.Store<any>
children?: ComponentChildren
}
export function Provider(props: ProviderProps) {
return <PreactRedux.Provider value={props.store} children={props.children} />
}
function useStore<T>(): redux.Store<T> {
const store = useContext(PreactRedux)
if (store == null) {
throw new Error('Called useStore when no store exists in context')
}
return store
}
export function useDispatch(): Dispatch {
const store = useStore()
return store.dispatch
}
export function useActionCreator<T, U>(
creator_: (payload: T) => Action<U>,
cacheArgs: any[],
): (t: T) => void {
const dispatch = useDispatch()
/* eslint-disable react-hooks/exhaustive-deps */
const creator = useCallback(creator_, cacheArgs)
return useCallback((t: T) => dispatch(creator(t)), [dispatch, creator])
}
export function useSelector<T, U>(selector_: (t: T) => U, cacheArgs: any[]): U {
const store = useStore<T>()
/* eslint-disable react-hooks/exhaustive-deps */
const selector = useCallback(selector_, cacheArgs)
const getValueFromStore = useCallback(() => selector(store.getState()), [store, selector])
const [value, setValue] = useState(getValueFromStore)
useLayoutEffect(() => {
// We need to setValue here because it's possible something has changed the
// value in the store between the useSelector call and layout. In most cases
// this should no-op.
setValue(getValueFromStore())
return store.subscribe(() => {
setValue(getValueFromStore())
})
}, [store, getValueFromStore])
return value
}
-90
View File
@@ -1,90 +0,0 @@
import {Profile, Frame, CallTreeNode} from './profile'
import {FuzzyMatch, fuzzyMatchStrings} from './fuzzy-find'
import {Flamechart, FlamechartFrame} from './flamechart'
import {Rect, Vec2} from './math'
export enum FlamechartType {
CHRONO_FLAME_CHART,
LEFT_HEAVY_FLAME_GRAPH,
}
// A utility class for storing cached search results to avoid recomputation when
// the search results & profile did not change.
export class ProfileSearchResults {
constructor(readonly profile: Profile, readonly searchQuery: string) {}
private matches: Map<Frame, FuzzyMatch> | null = null
getMatchForFrame(frame: Frame): FuzzyMatch | null {
if (!this.matches) {
this.matches = new Map()
this.profile.forEachFrame(frame => {
const match = fuzzyMatchStrings(frame.name, this.searchQuery)
if (match == null) return
this.matches!.set(frame, match)
})
}
return this.matches.get(frame) || null
}
}
export interface FlamechartSearchMatch {
configSpaceBounds: Rect
node: CallTreeNode
}
interface CachedFlamechartResult {
matches: FlamechartSearchMatch[]
indexForNode: Map<CallTreeNode, number>
}
export class FlamechartSearchResults {
constructor(readonly flamechart: Flamechart, readonly profileResults: ProfileSearchResults) {}
private matches: CachedFlamechartResult | null = null
private getResults(): CachedFlamechartResult {
if (this.matches == null) {
const matches: FlamechartSearchMatch[] = []
const indexForNode = new Map<CallTreeNode, number>()
const visit = (frame: FlamechartFrame, depth: number) => {
const {node} = frame
if (this.profileResults.getMatchForFrame(node.frame)) {
const configSpaceBounds = new Rect(
new Vec2(frame.start, depth),
new Vec2(frame.end - frame.start, 1),
)
indexForNode.set(node, matches.length)
matches.push({configSpaceBounds, node})
}
frame.children.forEach(child => {
visit(child, depth + 1)
})
}
const layers = this.flamechart.getLayers()
if (layers.length > 0) {
layers[0].forEach(frame => visit(frame, 0))
}
this.matches = {matches, indexForNode}
}
return this.matches
}
count(): number {
return this.getResults().matches.length
}
indexOf(node: CallTreeNode): number | null {
const result = this.getResults().indexForNode.get(node)
return result === undefined ? null : result
}
at(index: number): FlamechartSearchMatch {
const matches = this.getResults().matches
if (index < 0 || index >= matches.length) {
throw new Error(`Index ${index} out of bounds in list of ${matches.length} matches.`)
}
return matches[index]
}
}
+46 -49
View File
@@ -26,22 +26,19 @@ function toStackList(profile: Profile, grouped: boolean): string[] {
const curStack: (number | string)[] = []
let lastValue = 0
function maybeEmit(value: number) {
function openFrame(node: CallTreeNode, value: number) {
if (lastValue != value) {
stackList.push(
curStack.map(k => `${k}`).join(';') + ` ${profile.formatValue(value - lastValue)}`,
)
stackList.push(curStack.map(k => `${k}`).join(';'))
lastValue = value
}
}
function openFrame(node: CallTreeNode, value: number) {
maybeEmit(value)
curStack.push(node.frame.name)
curStack.push(node.frame.key)
}
function closeFrame(node: CallTreeNode, value: number) {
maybeEmit(value)
if (lastValue != value) {
stackList.push(curStack.map(k => `${k}`).join(';'))
lastValue = value
}
curStack.pop()
}
@@ -85,49 +82,49 @@ function verifyProfile(profile: Profile) {
expect(toStackList(profile, false)).toEqual([
// prettier-ignore
'a 1',
'a;b 2',
'a;b;d 1',
'a;b;c 1',
' 1',
'a 1',
'a;b 1',
'a;b;b 1',
'a;b;e 1',
'a 1',
'a',
'a;b',
'a;b;d',
'a;b;c',
'',
'a',
'a;b',
'a;b;b',
'a;b;e',
'a',
])
expect(toStackList(profile, true)).toEqual([
// prettier-ignore
'a;b;d 1',
'a;b;c 1',
'a;b;b 1',
'a;b;e 1',
'a;b 3',
'a 3',
'a;b;e',
'a;b;b',
'a;b;c',
'a;b;d',
'a;b',
'a',
])
const flattened = profile.getProfileWithRecursionFlattened()
expect(toStackList(flattened, false)).toEqual([
// prettier-ignore
'a 1',
'a;b 2',
'a;b;d 1',
'a;b;c 1',
' 1',
'a 1',
'a;b 2',
'a;b;e 1',
'a 1',
'a',
'a;b',
'a;b;d',
'a;b;c',
'',
'a',
'a;b',
'a;b;e',
'a',
])
expect(toStackList(flattened, true)).toEqual([
// prettier-ignore
'a;b;d 1',
'a;b;c 1',
'a;b;e 1',
'a;b 4',
'a 3',
'a;b;e',
'a;b;c',
'a;b;d',
'a;b',
'a',
])
}
@@ -262,9 +259,9 @@ test('getInvertedProfileForCallersOf', () => {
expect(toStackList(inverted, false)).toEqual([
// prettier-ignore
'b 1',
'b;a 3',
'b;d 1',
'b',
'b;a',
'b;d',
])
})
@@ -290,10 +287,10 @@ test('getProfileForCalleesOf', () => {
expect(toStackList(inverted, false)).toEqual([
// prettier-ignore
'b 2',
'b;c 1',
'b;d 1',
'b 1',
'b',
'b;c',
'b;d',
'b',
])
})
@@ -316,8 +313,8 @@ test('getProfileWithRecursionFlattened', () => {
expect(toStackList(inverted, false)).toEqual([
// prettier-ignore
'a 1',
'a;b 3',
'a',
'a;b',
])
const framesInProfile = new Set<string | number>()
+21 -63
View File
@@ -3,6 +3,9 @@ import {ValueFormatter, RawValueFormatter} from './value-formatters'
import {FileFormat} from './file-format-spec'
const demangleCppModule = import('./demangle-cpp')
// Force eager loading of the module
demangleCppModule.then(() => {})
export interface FrameInfo {
key: string | number
@@ -14,17 +17,13 @@ export interface FrameInfo {
// call stack frame.
file?: string
// Line in the given file where this frame occurs, 1-based.
// Line in the given file where this frame occurs
line?: number
// Column in the file, 1-based.
// Column in the file
col?: number
}
export type SymbolRemapper = (
frame: Frame,
) => {name?: string; file?: string; line?: number; col?: number} | null
export class HasWeights {
private selfWeight = 0
private totalWeight = 0
@@ -117,13 +116,6 @@ export class Profile {
protected frames = new KeyedSet<Frame>()
// Profiles store two call-trees.
//
// The "append order" call tree is the one in which nodes are ordered in
// whatever order they were appended to their parent.
//
// The "grouped" call tree is one in which each node has at most one child per
// frame. Nodes are ordered in decreasing order of weight
protected appendOrderCalltreeRoot = new CallTreeNode(Frame.root, null)
protected groupedCalltreeRoot = new CallTreeNode(Frame.root, null)
@@ -145,12 +137,6 @@ export class Profile {
this.totalWeight = totalWeight
}
shallowClone(): Profile {
const profile = new Profile(this.totalWeight)
Object.assign(profile, this)
return profile
}
formatValue(v: number) {
return this.valueFormatter.format(v)
}
@@ -183,17 +169,6 @@ export class Profile {
return this.totalNonIdleWeight
}
// This is private because it should only be called in the ProfileBuilder
// classes. Once a Profile instance has been constructed, it should be treated
// as immutable.
protected sortGroupedCallTree() {
function visit(node: CallTreeNode) {
node.children.sort((a, b) => -(a.getTotalWeight() - b.getTotalWeight()))
node.children.forEach(visit)
}
visit(this.groupedCalltreeRoot)
}
forEachCallGrouped(
openFrame: (node: CallTreeNode, value: number) => void,
closeFrame: (node: CallTreeNode, value: number) => void,
@@ -205,7 +180,10 @@ export class Profile {
let childTime = 0
node.children.forEach(function (child) {
const children = [...node.children]
children.sort((a, b) => (a.getTotalWeight() > b.getTotalWeight() ? -1 : 1))
children.forEach(function(child) {
visit(child, start + childTime)
childTime += child.getTotalWeight()
})
@@ -272,6 +250,12 @@ export class Profile {
this.frames.forEach(fn)
}
forEachSample(fn: (sample: CallTreeNode, weight: number) => void) {
for (let i = 0; i < this.samples.length; i++) {
fn(this.samples[i], this.weights[i])
}
}
getProfileWithRecursionFlattened(): Profile {
const builder = new CallTreeProfileBuilder()
@@ -415,25 +399,9 @@ export class Profile {
}
}
remapSymbols(callback: SymbolRemapper) {
remapNames(callback: (name: string) => string) {
for (let frame of this.frames) {
const remapped = callback(frame)
if (remapped == null) {
continue
}
const {name, file, line, col} = remapped
if (name != null) {
frame.name = name
}
if (file != null) {
frame.file = file
}
if (line != null) {
frame.line = line
}
if (col != null) {
frame.col = col
}
frame.name = callback(frame.name)
}
}
}
@@ -539,11 +507,7 @@ export class StackListProfileBuilder extends Profile {
this.setValueFormatter(new RawValueFormatter())
}
}
this.totalWeight = Math.max(
this.totalWeight,
this.weights.reduce((a, b) => a + b, 0),
)
this.sortGroupedCallTree()
this.totalWeight = Math.max(this.totalWeight, this.weights.reduce((a, b) => a + b, 0))
return this
}
}
@@ -593,7 +557,9 @@ export class CallTreeProfileBuilder extends Profile {
this.weights.push(value - this.lastValue)
} else if (delta < 0) {
throw new Error(
`Samples must be provided in increasing order of cumulative value. Last sample was ${this.lastValue}, this sample was ${value}`,
`Samples must be provided in increasing order of cumulative value. Last sample was ${
this.lastValue
}, this sample was ${value}`,
)
}
}
@@ -636,13 +602,6 @@ export class CallTreeProfileBuilder extends Profile {
throw new Error(`Trying to leave a ${frame.key} before any have been entered`)
}
leavingStackTop.freeze()
if (leavingStackTop.frame.key !== frame.key) {
throw new Error(
`Tried to leave frame "${frame.name}" while frame "${leavingStackTop.frame.name}" was at the top at ${value}`,
)
}
const delta = value - this.lastValue
if (delta > 0) {
this.samples.push(leavingStackTop)
@@ -684,7 +643,6 @@ export class CallTreeProfileBuilder extends Profile {
if (this.appendOrderStack.length > 1 || this.groupedOrderStack.length > 1) {
throw new Error('Tried to complete profile construction with a non-empty stack')
}
this.sortGroupedCallTree()
return this
}
}
+1 -1
View File
@@ -53,7 +53,7 @@ export class StatsPanel {
this.msPanel.update(time - this.beginTime, 200)
if (time >= this.prevTime + 1000) {
this.fpsPanel.update((this.frames * 1000) / (time - this.prevTime), 100)
this.fpsPanel.update(this.frames * 1000 / (time - this.prevTime), 100)
this.prevTime = time
this.frames = 0
}
-11
View File
@@ -97,14 +97,3 @@ export async function checkProfileSnapshot(filepath: string) {
const reexported = exportProfileGroup(reimportedGroup)
expect(exported).toEqual(reexported)
}
export async function expectImportFailure(filepath: string) {
const buffer = fs.readFileSync(filepath)
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)
try {
await importProfilesFromArrayBuffer(path.basename(filepath), arrayBuffer)
fail('Expected import to fail but it succeeded')
} catch (error) {
expect(error.message).toMatchSnapshot()
}
}
-116
View File
@@ -1,116 +0,0 @@
import {buildTrimmedText, ELLIPSIS, remapRangesToTrimmedText} from './text-utils'
import {fuzzyMatchStrings} from './fuzzy-find'
function assertTrimmed(text: string, length: number, expectedTrimmed: string) {
expect(buildTrimmedText(text, length).trimmedString).toEqual(
expectedTrimmed.replace('...', ELLIPSIS),
)
}
test('buildTrimmedText', () => {
assertTrimmed('hello world', 1, '...')
assertTrimmed('hello world', 2, 'h...')
assertTrimmed('hello world', 3, 'h...d')
assertTrimmed('hello world', 4, 'he...d')
assertTrimmed('hello world', 10, 'hello...orld')
assertTrimmed('hello world', 11, 'hello world')
assertTrimmed('hello world', 100, 'hello world')
})
function highlightText(text: string, highlightedRanges: [number, number][]): string {
let last = 0
let highlighted = ''
for (let range of highlightedRanges) {
highlighted += `${text.slice(last, range[0])}[${text.slice(range[0], range[1])}]`
last = range[1]
}
highlighted += text.slice(last)
return highlighted
}
function assertTrimmedHighlight({
text,
pattern,
expectedHighlighted,
length,
expectedHighlightedTrimmed,
}: {
text: string
pattern: string
expectedHighlighted: string
length: number
expectedHighlightedTrimmed: string
}) {
const match = fuzzyMatchStrings(text, pattern)
const trimmed = buildTrimmedText(text, length)
if (!match) {
fail()
return
}
const matchedRangesForTrimmedText = remapRangesToTrimmedText(trimmed, match.matchedRanges)
const highlighted = highlightText(text, match.matchedRanges)
const highlightedTrimmed = highlightText(trimmed.trimmedString, matchedRangesForTrimmedText)
expect(highlighted).toEqual(expectedHighlighted)
expect(highlightedTrimmed).toEqual(expectedHighlightedTrimmed.replace('...', ELLIPSIS))
}
test('remapRangesToTrimmedText', () => {
assertTrimmedHighlight({
text: 'hello world',
pattern: 'he',
length: 4,
expectedHighlighted: '[he]llo world',
expectedHighlightedTrimmed: `[he]...d`,
})
assertTrimmedHighlight({
text: 'hello world',
pattern: 'o w',
length: 4,
expectedHighlighted: 'hell[o w]orld',
expectedHighlightedTrimmed: `he[...]d`,
})
assertTrimmedHighlight({
text: 'hello world',
pattern: 'ow',
length: 4,
expectedHighlighted: 'hell[o] [w]orld',
expectedHighlightedTrimmed: `he[...]d`,
})
assertTrimmedHighlight({
text: 'hello world',
pattern: 'hello',
length: 4,
expectedHighlighted: '[hello] world',
expectedHighlightedTrimmed: `[he...]d`,
})
assertTrimmedHighlight({
text: 'hello world',
pattern: 'hello world',
length: 4,
expectedHighlighted: '[hello world]',
expectedHighlightedTrimmed: `[he...d]`,
})
assertTrimmedHighlight({
text: 'hello world',
pattern: 'helloworld',
length: 4,
expectedHighlighted: '[hello] [world]',
expectedHighlightedTrimmed: `[he...][d]`,
})
assertTrimmedHighlight({
text: 'hello world',
pattern: 'world',
length: 4,
expectedHighlighted: 'hello [world]',
expectedHighlightedTrimmed: `he[...d]`,
})
})
+9 -175
View File
@@ -1,4 +1,4 @@
import {findValueBisect} from './utils'
import {binarySearch} from './utils'
export const ELLIPSIS = '\u2026'
@@ -18,188 +18,22 @@ export function cachedMeasureTextWidth(ctx: CanvasRenderingContext2D, text: stri
return measureTextCache.get(text)!
}
interface TrimmedTextResult {
trimmedString: string
trimmedLength: number
prefixLength: number
suffixLength: number
originalLength: number
originalString: string
}
// Trim text, placing an ellipsis in the middle, with a slight bias towards
// keeping text from the beginning rather than the end
export function buildTrimmedText(text: string, length: number): TrimmedTextResult {
if (text.length <= length) {
return {
trimmedString: text,
trimmedLength: text.length,
prefixLength: text.length,
suffixLength: 0,
originalString: text,
originalLength: text.length,
}
}
let prefixLength = Math.floor(length / 2)
const suffixLength = length - prefixLength - 1
function buildTrimmedText(text: string, length: number) {
const prefixLength = Math.floor(length / 2)
const prefix = text.substr(0, prefixLength)
const suffix = text.substr(text.length - suffixLength, suffixLength)
const trimmedString = prefix + ELLIPSIS + suffix
return {
trimmedString,
trimmedLength: trimmedString.length,
prefixLength: prefix.length,
suffixLength: suffix.length,
originalString: text,
originalLength: text.length,
}
const suffix = text.substr(text.length - prefixLength, prefixLength)
return prefix + ELLIPSIS + suffix
}
// Trim text to fit within the given number of pixels on the canvas
export function trimTextMid(
ctx: CanvasRenderingContext2D,
text: string,
maxWidth: number,
): TrimmedTextResult {
if (cachedMeasureTextWidth(ctx, text) <= maxWidth) {
return buildTrimmedText(text, text.length)
}
const [lo] = findValueBisect(
export function trimTextMid(ctx: CanvasRenderingContext2D, text: string, maxWidth: number) {
if (cachedMeasureTextWidth(ctx, text) <= maxWidth) return text
const [lo] = binarySearch(
0,
text.length,
n => {
return cachedMeasureTextWidth(ctx, buildTrimmedText(text, n).trimmedString)
return cachedMeasureTextWidth(ctx, buildTrimmedText(text, n))
},
maxWidth,
)
return buildTrimmedText(text, lo)
}
enum IndexTypeInTrimmed {
IN_PREFIX,
IN_SUFFIX,
ELIDED,
}
function getIndexTypeInTrimmed(result: TrimmedTextResult, index: number): IndexTypeInTrimmed {
if (index < result.prefixLength) {
return IndexTypeInTrimmed.IN_PREFIX
} else if (index < result.originalLength - result.suffixLength) {
return IndexTypeInTrimmed.ELIDED
} else {
return IndexTypeInTrimmed.IN_SUFFIX
}
}
export function remapRangesToTrimmedText(
trimmedText: TrimmedTextResult,
ranges: [number, number][],
): [number, number][] {
// We intentionally don't just re-run fuzzy matching on the trimmed
// text, beacuse if the search query is "helloWorld", the frame name
// is "application::helloWorld", and that gets trimmed down to
// "appl...oWorld", we still want "oWorld" to be highlighted, even
// though the string "appl...oWorld" is not matched by the query
// "helloWorld".
//
// There's a weird case to consider here: what if the trimmedText is
// also matched by the query, but results in a different match than
// the original query? Consider, e.g. the search string of "ab". The
// string "hello ab shabby" will be matched at the first "ab", but
// may be trimmed to "hello...shabby". In this case, should we
// highlight the "ab" hidden by the ellipsis, or the "ab" in
// "shabby"? The code below highlights the ellipsis so that the
// matched characters don't change as you zoom in and out.
const rangesToHighlightInTrimmedText: [number, number][] = []
const lengthLoss = trimmedText.originalLength - trimmedText.trimmedLength
let highlightedEllipsis = false
for (let [origStart, origEnd] of ranges) {
let startPosType = getIndexTypeInTrimmed(trimmedText, origStart)
let endPosType = getIndexTypeInTrimmed(trimmedText, origEnd - 1)
switch (startPosType) {
case IndexTypeInTrimmed.IN_PREFIX: {
switch (endPosType) {
case IndexTypeInTrimmed.IN_PREFIX: {
// The entire range fits in the prefix. Add it unmodified.
rangesToHighlightInTrimmedText.push([origStart, origEnd])
break
}
case IndexTypeInTrimmed.ELIDED: {
// The range starts in the prefix, but ends in the elided
// section. Add just the prefix + one char for the ellipsis.
rangesToHighlightInTrimmedText.push([
origStart,
origStart + trimmedText.prefixLength + 1,
])
highlightedEllipsis = true
break
}
case IndexTypeInTrimmed.IN_SUFFIX: {
// The range crosses from the prefix to the suffix.
// Highlight everything including the ellipsis.
rangesToHighlightInTrimmedText.push([origStart, origEnd - lengthLoss])
break
}
}
break
}
case IndexTypeInTrimmed.ELIDED: {
switch (endPosType) {
case IndexTypeInTrimmed.IN_PREFIX: {
// This should be impossible
throw new Error('Unexpected highlight range starts in elided and ends in prefix')
}
case IndexTypeInTrimmed.ELIDED: {
// The match starts & ends within the elided section.
if (!highlightedEllipsis) {
rangesToHighlightInTrimmedText.push([
trimmedText.prefixLength,
trimmedText.prefixLength + 1,
])
highlightedEllipsis = true
}
break
}
case IndexTypeInTrimmed.IN_SUFFIX: {
// The match starts in elided, but ends in suffix.
if (highlightedEllipsis) {
rangesToHighlightInTrimmedText.push([
trimmedText.trimmedLength - trimmedText.suffixLength,
origEnd - lengthLoss,
])
} else {
rangesToHighlightInTrimmedText.push([trimmedText.prefixLength, origEnd - lengthLoss])
highlightedEllipsis = true
}
break
}
}
break
}
case IndexTypeInTrimmed.IN_SUFFIX: {
switch (endPosType) {
case IndexTypeInTrimmed.IN_PREFIX: {
// This should be impossible
throw new Error('Unexpected highlight range starts in suffix and ends in prefix')
}
case IndexTypeInTrimmed.ELIDED: {
// This should be impossible
throw new Error('Unexpected highlight range starts in suffix and ends in elided')
break
}
case IndexTypeInTrimmed.IN_SUFFIX: {
// Match starts & ends in suffix
rangesToHighlightInTrimmedText.push([origStart - lengthLoss, origEnd - lengthLoss])
break
}
}
break
}
}
}
return rangesToHighlightInTrimmedText
}
+27 -1
View File
@@ -1,5 +1,6 @@
import {connect} from 'preact-redux'
import * as redux from 'redux'
import {Component} from 'preact'
import {ComponentConstructor, Component} from 'preact'
export interface Action<TPayload> extends redux.Action<string> {
payload: TPayload
@@ -52,6 +53,31 @@ export function setter<T>(
export type Dispatch = redux.Dispatch<Action<any>>
// We make this into a single function invocation instead of the connect(map, map)(Component)
// syntax to make better use of type inference.
//
// NOTE: To avoid this returning objects which do not compare shallow equal, it's the
// responsibility of the caller to ensure that the props returned by map compare shallow
// equal. This most importantly mean memoizing functions which wrap dispatch to avoid
// all callback props from being regenerated on every call.
export function createContainer<OwnProps, State, ComponentProps, ComponentType>(
component: {
new (props: ComponentProps): ComponentType
},
map: (state: State, dispatch: Dispatch, ownProps: OwnProps) => ComponentProps,
): ComponentConstructor<OwnProps, {}> {
const mapStateToProps = (state: State) => state
const mapDispatchToProps = (dispatch: Dispatch) => ({dispatch})
const mergeProps = (
stateProps: State,
dispatchProps: {dispatch: Dispatch},
ownProps: OwnProps,
) => {
return map(stateProps, dispatchProps.dispatch, ownProps)
}
return connect(mapStateToProps, mapDispatchToProps, mergeProps)(component)
}
export type VoidState = {
__dummyField: void
}
+3 -40
View File
@@ -9,12 +9,11 @@ import {
zeroPad,
formatPercent,
KeyedSet,
findValueBisect,
binarySearch,
memoizeByReference,
memoizeByShallowEquality,
objectsHaveShallowEquality,
decodeBase64,
findIndexBisect,
} from './utils'
import * as jsc from 'jsverify'
@@ -110,49 +109,13 @@ test('formatPercent', () => {
expect(formatPercent(100)).toBe('100%')
})
test('findValueBisect', () => {
const [lo, hi] = findValueBisect(0, 10, n => Math.log(n), 1, 0.0001)
test('binarySearch', () => {
const [lo, hi] = binarySearch(0, 10, n => Math.log(n), 1, 0.0001)
expect(lo).toBeCloseTo(Math.E, 4)
expect(lo).toBeLessThan(Math.E)
expect(hi).toBeGreaterThan(Math.E)
})
test('findIndexBisect', () => {
const check = (haystack: number[], needle: number) => {
const condition = (v: number) => v > needle
expect(findIndexBisect(haystack, condition)).toEqual(haystack.findIndex(condition))
}
check([], 0)
check([0], 0)
check([0], -1)
check([0], 1)
check([0, 1], 0)
check([0, 1], 1)
check([0, 1], 2)
check([0, 1, 2], 2)
check([0, 1, 2], 2)
check([0, 1, 2], 2)
check([0, 1, 2], 2)
check([3, 5, 5, 7], 1)
check([3, 5, 5, 7], 2)
check([3, 5, 5, 7], 5)
check([3, 5, 5, 7], 7)
check([3, 5, 5, 7], 11)
jsc.assertForall(jsc.array(jsc.int8), jsc.int8, (haystack: number[], needle: number) => {
haystack.sort((a, b) => a - b)
const fn = (v: number) => v > needle
expect(findIndexBisect(haystack, fn)).toEqual(haystack.findIndex(fn))
return true
})
})
test('memoizeByReference', () => {
let hitCount = 0
const identity = memoizeByReference((arg: number) => {
+14 -49
View File
@@ -4,9 +4,7 @@ export function lastOf<T>(ts: T[]): T | null {
export function sortBy<T>(ts: T[], key: (t: T) => number | string): void {
function comparator(a: T, b: T) {
const keyA = key(a)
const keyB = key(b)
return keyA < keyB ? -1 : keyA > keyB ? 1 : 0
return key(a) < key(b) ? -1 : 1
}
ts.sort(comparator)
}
@@ -105,7 +103,7 @@ export function triangle(x: number) {
return 2.0 * Math.abs(fract(x) - 0.5) - 1.0
}
export function findValueBisect(
export function binarySearch(
lo: number,
hi: number,
f: (val: number) => number,
@@ -122,39 +120,6 @@ export function findValueBisect(
}
}
// Similar to Array.prototype.findIndex, except uses a binary search.
//
// This assumes that the condition transitions exactly once from false to true
// in the list, e.g. the following is a valid input:
//
// ls = [a, b, c, d]
// ls.map(f) = [false, false, true, true]
//
// The following is an invalid input:
//
// ls = [a, b, c, d]
// ls.map(f) = [false, true, false, true]
export function findIndexBisect<T>(ls: T[], f: (val: T) => boolean): number {
if (ls.length === 0) return -1
let lo = 0
let hi = ls.length - 1
while (hi !== lo) {
const mid = Math.floor((lo + hi) / 2)
if (f(ls[mid])) {
// The desired index is <= mid
hi = mid
} else {
// The desired index is > mid
lo = mid + 1
}
}
return f(ls[hi]) ? hi : -1
}
export function noop(...args: any[]) {}
export function objectsHaveShallowEquality<T extends object>(a: T, b: T): boolean {
@@ -213,17 +178,15 @@ export function lazyStatic<T>(cb: () => T): () => T {
}
}
const base64lookupTable = lazyStatic(
(): Map<string, number> => {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
const ret = new Map<string, number>()
for (let i = 0; i < alphabet.length; i++) {
ret.set(alphabet.charAt(i), i)
}
ret.set('=', -1)
return ret
},
)
const base64lookupTable = lazyStatic((): Map<string, number> => {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
const ret = new Map<string, number>()
for (let i = 0; i < alphabet.length; i++) {
ret.set(alphabet.charAt(i), i)
}
ret.set('=', -1)
return ret
})
// NOTE: There are probably simpler solutions to this problem, but I have this written already, so
// until we run into problems with this, let's just use this.
@@ -247,7 +210,9 @@ export function decodeBase64(encoded: string): Uint8Array {
if (encoded.length % 4 !== 0) {
throw new Error(
`Invalid length for base64 encoded string. Expected length % 4 = 0, got length = ${encoded.length}`,
`Invalid length for base64 encoded string. Expected length % 4 = 0, got length = ${
encoded.length
}`,
)
}
+3 -3
View File
@@ -1,7 +1,7 @@
import {h, render} from 'preact'
import {createAppStore} from './store'
import {createApplicationStore} from './store'
import {Provider} from 'preact-redux'
import {ApplicationContainer} from './views/application-container'
import {Provider} from './lib/preact-redux'
console.log(`speedscope v${require('../package.json').version}`)
@@ -15,7 +15,7 @@ if (module.hot) {
}
const lastStore: any = (window as any)['store']
const store = lastStore ? createAppStore(lastStore.getState()) : createAppStore()
const store = createApplicationStore(lastStore ? lastStore.getState() : {})
;(window as any)['store'] = store
render(
+20 -3
View File
@@ -8,23 +8,40 @@ import {HashParams} from '../lib/hash-params'
import {actionCreatorWithIndex} from './profiles-state'
export namespace actions {
// Set the top-level profile group from which other data will be derived
export const setProfileGroup = actionCreator<ProfileGroup>('setProfileGroup')
// Set the index into the profile group to view
export const setProfileIndexToView = actionCreator<number>('setProfileIndexToView')
export const setGLCanvas = actionCreator<HTMLCanvasElement | null>('setGLCanvas')
// Set which top-level view should be displayed
export const setViewMode = actionCreator<ViewMode>('setViewMode')
// Set whether or not recursion should be flattened when viewing flamegraphs
export const setFlattenRecursion = actionCreator<boolean>('setFlattenRecursion')
export const setSearchQuery = actionCreator<string>('setSearchQuery')
export const setSearchIsActive = actionCreator<boolean>('setSearchIsActive')
// Set whether a file drag is currently active. Used to indicate that the
// application is a valid drop target.
export const setDragActive = actionCreator<boolean>('setDragActive')
// Set whether the application is currently in a loading state. Used to
// display a loading progress bar.
export const setLoading = actionCreator<boolean>('setLoading')
// Set whether the application is in an errored state.
export const setError = actionCreator<boolean>('setError')
// Set whether parameters defined by the URL encoded k=v pairs after the # in the URL
export const setHashParams = actionCreator<HashParams>('setHashParams')
export namespace sandwichView {
// Set the table sorting method used for the sandwich view.
export const setTableSortMethod = actionCreator<SortMethod>('sandwichView.setTableSortMethod')
export const setSelectedFrame = actionCreatorWithIndex<Frame | null>(
'sandwichView.setSelectedFrame',
'sandwichView.setSelectedFarmr',
)
}
+23 -18
View File
@@ -40,27 +40,32 @@ export const getRowAtlas = memoizeByReference((canvasContext: CanvasContext) =>
)
})
export const getProfileWithRecursionFlattened = memoizeByReference((profile: Profile) =>
profile.getProfileWithRecursionFlattened(),
)
export const getProfileToView = memoizeByShallowEquality(
({profile, flattenRecursion}: {profile: Profile; flattenRecursion: boolean}): Profile => {
return flattenRecursion ? profile.getProfileWithRecursionFlattened() : profile
},
)
export const getFrameToColorBucket = memoizeByReference(
(profile: Profile): Map<string | number, number> => {
const frames: Frame[] = []
profile.forEachFrame(f => frames.push(f))
function key(f: Frame) {
return (f.file || '') + f.name
}
function compare(a: Frame, b: Frame) {
return key(a) > key(b) ? 1 : -1
}
frames.sort(compare)
const frameToColorBucket = new Map<string | number, number>()
for (let i = 0; i < frames.length; i++) {
frameToColorBucket.set(frames[i].key, Math.floor((255 * i) / frames.length))
}
export const getFrameToColorBucket = memoizeByReference((profile: Profile): Map<
string | number,
number
> => {
const frames: Frame[] = []
profile.forEachFrame(f => frames.push(f))
function key(f: Frame) {
return (f.file || '') + f.name
}
function compare(a: Frame, b: Frame) {
return key(a) > key(b) ? 1 : -1
}
frames.sort(compare)
const frameToColorBucket = new Map<string | number, number>()
for (let i = 0; i < frames.length; i++) {
frameToColorBucket.set(frames[i].key, Math.floor(255 * i / frames.length))
}
return frameToColorBucket
},
)
return frameToColorBucket
})
+6 -67
View File
@@ -10,11 +10,6 @@ import {setter, Reducer} from '../lib/typed-redux'
import {HashParams, getHashParams} from '../lib/hash-params'
import {ProfileGroupState, profileGroup} from './profiles-state'
import {SortMethod, SortField, SortDirection} from '../views/profile-table-view'
import {useSelector} from '../lib/preact-redux'
import {Profile} from '../lib/profile'
import {FlamechartViewState} from './flamechart-view-state'
import {SandwichViewState} from './sandwich-view-state'
import {getProfileToView} from './getters'
export const enum ViewMode {
CHRONO_FLAME_CHART,
@@ -23,43 +18,20 @@ export const enum ViewMode {
}
export interface ApplicationState {
// The top-level profile group from which most other data will be derived
profileGroup: ProfileGroupState
// Parameters defined by the URL encoded k=v pairs after the # in the URL
hashParams: HashParams
glCanvas: HTMLCanvasElement | null
// Which top-level view should be displayed
viewMode: ViewMode
// True if recursion should be flattened when viewing flamegraphs
flattenRecursion: boolean
// The query used in top-level views
//
// An empty string indicates that the search is open by no filter is applied.
// searchIsActive is stored separately, because we may choose to persist the
// query even when the search input is closed.
searchQuery: string
searchIsActive: boolean
// True when a file drag is currently active. Used to indicate that the
// application is a valid drop target.
viewMode: ViewMode
dragActive: boolean
// True when the application is currently in a loading state. Used to
// display a loading progress bar.
loading: boolean
// True when the application is an error state, e.g. because the profile
// imported was invalid.
error: boolean
// The table sorting method using for the sandwich view, specifying the column
// to sort by, and the direction to sort that clumn.
tableSortMethod: SortMethod
profileGroup: ProfileGroupState
}
const protocol = window.location.protocol
@@ -69,7 +41,9 @@ const protocol = window.location.protocol
// however, XHR will be unavailable to fetching files in adjacent directories.
export const canUseXHR = protocol === 'http:' || protocol === 'https:'
export function createAppStore(initialState?: ApplicationState): redux.Store<ApplicationState> {
export function createApplicationStore(
initialState: Partial<ApplicationState>,
): redux.Store<ApplicationState> {
const hashParams = getHashParams()
const loading = canUseXHR && hashParams.profileURL != null
@@ -83,9 +57,6 @@ export function createAppStore(initialState?: ApplicationState): redux.Store<App
viewMode: setter<ViewMode>(actions.setViewMode, ViewMode.CHRONO_FLAME_CHART),
searchQuery: setter<string>(actions.setSearchQuery, ''),
searchIsActive: setter<boolean>(actions.setSearchIsActive, false),
glCanvas: setter<HTMLCanvasElement | null>(actions.setGLCanvas, null),
dragActive: setter<boolean>(actions.setDragActive, false),
@@ -100,35 +71,3 @@ export function createAppStore(initialState?: ApplicationState): redux.Store<App
return redux.createStore(reducer, initialState)
}
export function useAppSelector<T>(selector: (t: ApplicationState) => T, cacheArgs: any[]): T {
/* eslint-disable react-hooks/exhaustive-deps */
return useSelector(selector, cacheArgs)
}
export interface ActiveProfileState {
profile: Profile
index: number
chronoViewState: FlamechartViewState
leftHeavyViewState: FlamechartViewState
sandwichViewState: SandwichViewState
}
export function useActiveProfileState(): ActiveProfileState | null {
return useAppSelector(state => {
const {profileGroup} = state
if (!profileGroup) return null
if (profileGroup.indexToView >= profileGroup.profiles.length) return null
const index = profileGroup.indexToView
const profileState = profileGroup.profiles[index]
return {
...profileGroup.profiles[profileGroup.indexToView],
profile: getProfileToView({
profile: profileState.profile,
flattenRecursion: state.flattenRecursion,
}),
index: profileGroup.indexToView,
}
}, [])
}
-3
View File
@@ -12,10 +12,7 @@ import {objectsHaveShallowEquality} from '../lib/utils'
export type ProfileGroupState = {
name: string
// The index within the list of profiles currently being viewed
indexToView: number
profiles: ProfileState[]
} | null
+2 -2
View File
@@ -1,11 +1,11 @@
import * as fs from 'fs'
import {Store, AnyAction} from 'redux'
import {ApplicationState, createAppStore} from '.'
import {ApplicationState, createApplicationStore} from '.'
import {importSpeedscopeProfiles} from '../lib/file-format'
export function storeTest(name: string, cb: (store: Store<ApplicationState, AnyAction>) => void) {
const store = createAppStore()
const store = createApplicationStore({})
test(name, () => {
cb(store)
})
+12
View File
@@ -0,0 +1,12 @@
declare module 'preact-redux' {
import {VNode, Component} from 'preact'
import {Store} from 'redux'
// We just export the bare minimum here because we're going
// to implement an API for readability convenience elsewhere
export function connect(...args: any[]): any
export class Provider extends Component<{store: Store<any>}, {}> {
render(): VNode
}
}
+59 -41
View File
@@ -1,45 +1,63 @@
import {h} from 'preact'
import {Application} from './application'
import {getCanvasContext} from '../store/getters'
import {createContainer, Dispatch, bindActionCreator, ActionCreator} from '../lib/typed-redux'
import {Application, ActiveProfileState} from './application'
import {ApplicationState} from '../store'
import {getProfileToView, getCanvasContext} from '../store/getters'
import {actions} from '../store/actions'
import {useActionCreator} from '../lib/preact-redux'
import {memo} from 'preact/compat'
import {useAppSelector, useActiveProfileState} from '../store'
import {ProfileSearchContextProvider} from './search-view'
import {Graphics} from '../gl/graphics'
const {
setLoading,
setError,
setProfileGroup,
setDragActive,
setViewMode,
setGLCanvas,
setFlattenRecursion,
setProfileIndexToView,
} = actions
export const ApplicationContainer = createContainer(
Application,
(state: ApplicationState, dispatch: Dispatch) => {
const {flattenRecursion, profileGroup} = state
export const ApplicationContainer = memo(() => {
const appState = useAppSelector(state => state, [])
const canvasContext = useAppSelector(
state => (state.glCanvas ? getCanvasContext(state.glCanvas) : null),
[],
)
let activeProfileState: ActiveProfileState | null = null
if (profileGroup) {
if (profileGroup.profiles.length > profileGroup.indexToView) {
const index = profileGroup.indexToView
const profileState = profileGroup.profiles[index]
activeProfileState = {
...profileGroup.profiles[profileGroup.indexToView],
profile: getProfileToView({profile: profileState.profile, flattenRecursion}),
index: profileGroup.indexToView,
}
}
}
return (
<ProfileSearchContextProvider>
<Application
activeProfileState={useActiveProfileState()}
canvasContext={canvasContext}
setGLCanvas={useActionCreator(setGLCanvas, [])}
setLoading={useActionCreator(setLoading, [])}
setError={useActionCreator(setError, [])}
setProfileGroup={useActionCreator(setProfileGroup, [])}
setDragActive={useActionCreator(setDragActive, [])}
setViewMode={useActionCreator(setViewMode, [])}
setFlattenRecursion={useActionCreator(setFlattenRecursion, [])}
setProfileIndexToView={useActionCreator(setProfileIndexToView, [])}
{...appState}
/>
</ProfileSearchContextProvider>
)
})
function wrapActionCreator<T>(actionCreator: ActionCreator<T>): (t: T) => void {
return bindActionCreator(dispatch, actionCreator)
}
// TODO(jlfwong): Cache this and resizeCanvas below to prevent re-renders
// due to changing props.
const setters = {
setGLCanvas: wrapActionCreator(actions.setGLCanvas),
setLoading: wrapActionCreator(actions.setLoading),
setError: wrapActionCreator(actions.setError),
setProfileGroup: wrapActionCreator(actions.setProfileGroup),
setDragActive: wrapActionCreator(actions.setDragActive),
setViewMode: wrapActionCreator(actions.setViewMode),
setFlattenRecursion: wrapActionCreator(actions.setFlattenRecursion),
setProfileIndexToView: wrapActionCreator(actions.setProfileIndexToView),
}
return {
activeProfileState,
dispatch,
canvasContext: state.glCanvas ? getCanvasContext(state.glCanvas) : null,
resizeCanvas: (
widthInPixels: number,
heightInPixels: number,
widthInAppUnits: number,
heightInAppUnits: number,
) => {
if (state.glCanvas) {
const gl = getCanvasContext(state.glCanvas).gl
gl.resize(widthInPixels, heightInPixels, widthInAppUnits, heightInAppUnits)
gl.clear(new Graphics.Color(1, 1, 1, 1))
}
},
...setters,
...state,
}
},
)
+256 -53
View File
@@ -1,29 +1,23 @@
import {h} from 'preact'
import {h, Component} from 'preact'
import {StyleSheet, css} from 'aphrodite'
import {FileSystemDirectoryEntry} from '../import/file-system-entry'
import {ProfileGroup, SymbolRemapper} from '../lib/profile'
import {FontFamily, FontSize, Colors, Duration} from './style'
import {importEmscriptenSymbolMap as importEmscriptenSymbolRemapper} from '../lib/emscripten'
import {Profile, ProfileGroup} from '../lib/profile'
import {FontFamily, FontSize, Colors, Sizes, Duration} from './style'
import {importEmscriptenSymbolMap} from '../lib/emscripten'
import {SandwichViewContainer} from './sandwich-view'
import {saveToFile} from '../lib/file-format'
import {ApplicationState, ViewMode, canUseXHR, ActiveProfileState} from '../store'
import {ApplicationState, ViewMode, canUseXHR} from '../store'
import {StatelessComponent} from '../lib/typed-redux'
import {LeftHeavyFlamechartView, ChronoFlamechartView} from './flamechart-view-container'
import {SandwichViewState} from '../store/sandwich-view-state'
import {FlamechartViewState} from '../store/flamechart-view-state'
import {CanvasContext} from '../gl/canvas-context'
import {Graphics} from '../gl/graphics'
import {Toolbar} from './toolbar'
import {importJavaScriptSourceMapSymbolRemapper} from '../lib/js-source-map'
const importModule = import('../import')
// Force eager loading of a few code-split modules.
//
// We put them all in one place so we can directly control the relative priority
// of these.
// Force eager loading of the module
importModule.then(() => {})
import('../lib/demangle-cpp').then(() => {})
import('source-map').then(() => {})
async function importProfilesFromText(
fileName: string,
@@ -56,14 +50,155 @@ async function importFromFileSystemDirectoryEntry(entry: FileSystemDirectoryEntr
declare function require(x: string): any
const exampleProfileURL = require('../../sample/profiles/stackcollapse/perf-vertx-stacks-01-collapsed-all.txt')
interface ToolbarProps extends ApplicationProps {
browseForFile(): void
saveFile(): void
}
export class Toolbar extends StatelessComponent<ToolbarProps> {
setTimeOrder = () => {
this.props.setViewMode(ViewMode.CHRONO_FLAME_CHART)
}
setLeftHeavyOrder = () => {
this.props.setViewMode(ViewMode.LEFT_HEAVY_FLAME_GRAPH)
}
setSandwichView = () => {
this.props.setViewMode(ViewMode.SANDWICH_VIEW)
}
renderLeftContent() {
if (!this.props.activeProfileState) return null
return (
<div className={css(style.toolbarLeft)}>
<div
className={css(
style.toolbarTab,
this.props.viewMode === ViewMode.CHRONO_FLAME_CHART && style.toolbarTabActive,
)}
onClick={this.setTimeOrder}
>
<span className={css(style.emoji)}>🕰</span>Time Order
</div>
<div
className={css(
style.toolbarTab,
this.props.viewMode === ViewMode.LEFT_HEAVY_FLAME_GRAPH && style.toolbarTabActive,
)}
onClick={this.setLeftHeavyOrder}
>
<span className={css(style.emoji)}></span>Left Heavy
</div>
<div
className={css(
style.toolbarTab,
this.props.viewMode === ViewMode.SANDWICH_VIEW && style.toolbarTabActive,
)}
onClick={this.setSandwichView}
>
<span className={css(style.emoji)}>🥪</span>Sandwich
</div>
</div>
)
}
renderCenterContent() {
const {activeProfileState, profileGroup} = this.props
if (activeProfileState && profileGroup) {
const {index} = activeProfileState
if (profileGroup.profiles.length === 1) {
return activeProfileState.profile.getName()
} else {
function makeNavButton(content: string, disabled: boolean, onClick: () => void) {
return (
<button
disabled={disabled}
onClick={onClick}
className={css(
style.emoji,
style.toolbarProfileNavButton,
disabled && style.toolbarProfileNavButtonDisabled,
)}
>
{content}
</button>
)
}
const prevButton = makeNavButton('⬅️', index === 0, () =>
this.props.setProfileIndexToView(index - 1),
)
const nextButton = makeNavButton('➡️', index >= profileGroup.profiles.length - 1, () =>
this.props.setProfileIndexToView(index + 1),
)
return (
<div className={css(style.toolbarCenter)}>
{prevButton}
{activeProfileState.profile.getName()}{' '}
<span className={css(style.toolbarProfileIndex)}>
({activeProfileState.index + 1}/{profileGroup.profiles.length})
</span>
{nextButton}
</div>
)
}
}
return '🔬speedscope'
}
renderRightContent() {
const importFile = (
<div className={css(style.toolbarTab)} onClick={this.props.browseForFile}>
<span className={css(style.emoji)}></span>Import
</div>
)
const help = (
<div className={css(style.toolbarTab)}>
<a
href="https://github.com/jlfwong/speedscope#usage"
className={css(style.noLinkStyle)}
target="_blank"
>
<span className={css(style.emoji)}></span>Help
</a>
</div>
)
return (
<div className={css(style.toolbarRight)}>
{this.props.activeProfileState && (
<div className={css(style.toolbarTab)} onClick={this.props.saveFile}>
<span className={css(style.emoji)}></span>Export
</div>
)}
{importFile}
{help}
</div>
)
}
render() {
return (
<div className={css(style.toolbar)}>
{this.renderLeftContent()}
{this.renderCenterContent()}
{this.renderRightContent()}
</div>
)
}
}
interface GLCanvasProps {
canvasContext: CanvasContext | null
setGLCanvas: (canvas: HTMLCanvasElement | null) => void
}
export class GLCanvas extends StatelessComponent<GLCanvasProps> {
export class GLCanvas extends Component<GLCanvasProps, void> {
private canvas: HTMLCanvasElement | null = null
private ref = (canvas: Element | null) => {
private ref = (canvas?: Element) => {
if (canvas instanceof HTMLCanvasElement) {
this.canvas = canvas
} else {
@@ -74,7 +209,7 @@ export class GLCanvas extends StatelessComponent<GLCanvasProps> {
}
private container: HTMLElement | null = null
private containerRef = (container: Element | null) => {
private containerRef = (container?: Element) => {
if (container instanceof HTMLElement) {
this.container = container
} else {
@@ -136,6 +271,14 @@ export class GLCanvas extends StatelessComponent<GLCanvasProps> {
}
}
export interface ActiveProfileState {
profile: Profile
index: number
chronoViewState: FlamechartViewState
leftHeavyViewState: FlamechartViewState
sandwichViewState: SandwichViewState
}
export type ApplicationProps = ApplicationState & {
setGLCanvas: (canvas: HTMLCanvasElement | null) => void
setLoading: (loading: boolean) => void
@@ -180,8 +323,8 @@ export class Application extends StatelessComponent<ApplicationProps> {
if (this.props.hashParams.title) {
profileGroup = {
...profileGroup,
name: this.props.hashParams.title,
...profileGroup,
}
}
document.title = `${profileGroup.name} - speedscope`
@@ -230,36 +373,15 @@ export class Application extends StatelessComponent<ApplicationProps> {
reader.readAsText(file)
const fileContents = await fileContentsPromise
let symbolRemapper: SymbolRemapper | null = null
const emscriptenSymbolRemapper = importEmscriptenSymbolRemapper(fileContents)
if (emscriptenSymbolRemapper) {
const map = importEmscriptenSymbolMap(fileContents)
if (map) {
const {profile, index} = this.props.activeProfileState
console.log('Importing as emscripten symbol map')
symbolRemapper = emscriptenSymbolRemapper
}
const jsSourceMapRemapper = await importJavaScriptSourceMapSymbolRemapper(
fileContents,
file.name,
)
if (!symbolRemapper && jsSourceMapRemapper) {
console.log('Importing as JavaScript source map')
symbolRemapper = jsSourceMapRemapper
}
if (symbolRemapper != null) {
profile.remapNames(name => map.get(name) || name)
return {
name: this.props.profileGroup.name || 'profile',
indexToView: this.props.profileGroup.indexToView,
profiles: this.props.profileGroup.profiles.map(profileState => {
// We do a shallow clone here to invalidate certain caches keyed
// on a reference to the profile group under the assumption that
// profiles are immutable. Symbol remapping is (at time of
// writing) the only exception to that immutability.
const p = profileState.profile.shallowClone()
p.remapSymbols(symbolRemapper!)
return p
}),
indexToView: index,
profiles: [profile],
}
}
}
@@ -280,8 +402,6 @@ export class Application extends StatelessComponent<ApplicationProps> {
this.props.setDragActive(false)
ev.preventDefault()
if (!ev.dataTransfer) return
const firstItem = ev.dataTransfer.items[0]
if ('webkitGetAsEntry' in firstItem) {
const webkitEntry: FileSystemDirectoryEntry = firstItem.webkitGetAsEntry()
@@ -370,9 +490,7 @@ export class Application extends StatelessComponent<ApplicationProps> {
ev.preventDefault()
ev.stopPropagation()
const clipboardData = (ev as ClipboardEvent).clipboardData
if (!clipboardData) return
const pasted = clipboardData.getData('text')
const pasted = (ev as ClipboardEvent).clipboardData.getData('text')
this.loadProfile(async () => {
return await importProfilesFromText('From Clipboard', pasted)
})
@@ -493,8 +611,7 @@ export class Application extends StatelessComponent<ApplicationProps> {
href="https://github.com/jlfwong/speedscope/issues"
>
report any issues on GitHub
</a>
.
</a>.
</p>
</div>
</div>
@@ -556,7 +673,7 @@ export class Application extends StatelessComponent<ApplicationProps> {
<Toolbar
saveFile={this.saveFile}
browseForFile={this.browseForFile}
{...(this.props as ApplicationProps)}
{...this.props as ApplicationProps}
/>
<div className={css(style.contentContainer)}>{this.renderContent()}</div>
{this.props.dragActive && <div className={css(style.dragTarget)} />}
@@ -668,4 +785,90 @@ const style = StyleSheet.create({
cursor: 'pointer',
textDecoration: 'none',
},
toolbar: {
height: Sizes.TOOLBAR_HEIGHT,
flexShrink: 0,
background: Colors.BLACK,
color: Colors.WHITE,
textAlign: 'center',
fontFamily: FontFamily.MONOSPACE,
fontSize: FontSize.TITLE,
lineHeight: `${Sizes.TOOLBAR_TAB_HEIGHT}px`,
userSelect: 'none',
},
toolbarLeft: {
position: 'absolute',
height: Sizes.TOOLBAR_HEIGHT,
overflow: 'hidden',
top: 0,
left: 0,
marginRight: 2,
textAlign: 'left',
},
toolbarCenter: {
paddingTop: 1,
height: Sizes.TOOLBAR_HEIGHT,
},
toolbarRight: {
height: Sizes.TOOLBAR_HEIGHT,
overflow: 'hidden',
position: 'absolute',
top: 0,
right: 0,
marginRight: 2,
textAlign: 'right',
},
toolbarProfileIndex: {
color: Colors.LIGHT_GRAY,
},
toolbarProfileNavButton: {
opacity: 0.8,
fontSize: FontSize.TITLE,
lineHeight: `${Sizes.TOOLBAR_TAB_HEIGHT}px`,
':hover': {
opacity: 1.0,
},
background: 'none',
border: 'none',
padding: 0,
marginLeft: '0.3em',
marginRight: '0.3em',
transition: `all ${Duration.HOVER_CHANGE} ease-in`,
},
toolbarProfileNavButtonDisabled: {
opacity: 0.5,
':hover': {
opacity: 0.5,
},
},
toolbarTab: {
background: Colors.DARK_GRAY,
marginTop: Sizes.SEPARATOR_HEIGHT,
height: Sizes.TOOLBAR_TAB_HEIGHT,
lineHeight: `${Sizes.TOOLBAR_TAB_HEIGHT}px`,
paddingLeft: 2,
paddingRight: 8,
display: 'inline-block',
marginLeft: 2,
transition: `all ${Duration.HOVER_CHANGE} ease-in`,
':hover': {
background: Colors.GRAY,
},
},
toolbarTabActive: {
background: Colors.BRIGHT_BLUE,
':hover': {
background: Colors.BRIGHT_BLUE,
},
},
noLinkStyle: {
textDecoration: 'none',
color: 'inherit',
},
emoji: {
display: 'inline-block',
verticalAlign: 'middle',
paddingTop: '0px',
marginRight: '0.3em',
},
})
+84
View File
@@ -0,0 +1,84 @@
import {memoizeByShallowEquality} from '../lib/utils'
import {Profile, Frame} from '../lib/profile'
import {Flamechart} from '../lib/flamechart'
import {
createMemoizedFlamechartRenderer,
FlamechartViewContainerProps,
createFlamechartSetters,
} from './flamechart-view-container'
import {createContainer, Dispatch} from '../lib/typed-redux'
import {ApplicationState} from '../store'
import {
getCanvasContext,
createGetColorBucketForFrame,
createGetCSSColorForFrame,
getFrameToColorBucket,
} from '../store/getters'
import {FlamechartID} from '../store/flamechart-view-state'
import {FlamechartWrapper} from './flamechart-wrapper'
const getCalleeProfile = memoizeByShallowEquality<
{
profile: Profile
frame: Frame
flattenRecursion: boolean
},
Profile
>(({profile, frame, flattenRecursion}) => {
let p = profile.getProfileForCalleesOf(frame)
return flattenRecursion ? p.getProfileWithRecursionFlattened() : p
})
const getCalleeFlamegraph = memoizeByShallowEquality<
{
calleeProfile: Profile
getColorBucketForFrame: (frame: Frame) => number
},
Flamechart
>(({calleeProfile, getColorBucketForFrame}) => {
return new Flamechart({
getTotalWeight: calleeProfile.getTotalNonIdleWeight.bind(calleeProfile),
forEachCall: calleeProfile.forEachCallGrouped.bind(calleeProfile),
formatValue: calleeProfile.formatValue.bind(calleeProfile),
getColorBucketForFrame,
})
})
const getCalleeFlamegraphRenderer = createMemoizedFlamechartRenderer()
export const CalleeFlamegraphView = createContainer(
FlamechartWrapper,
(state: ApplicationState, dispatch: Dispatch, ownProps: FlamechartViewContainerProps) => {
const {activeProfileState} = ownProps
const {index, profile, sandwichViewState} = activeProfileState
const {flattenRecursion, glCanvas} = state
if (!profile) throw new Error('profile missing')
if (!glCanvas) throw new Error('glCanvas missing')
const {callerCallee} = sandwichViewState
if (!callerCallee) throw new Error('callerCallee missing')
const {selectedFrame} = callerCallee
const frameToColorBucket = getFrameToColorBucket(profile)
const getColorBucketForFrame = createGetColorBucketForFrame(frameToColorBucket)
const getCSSColorForFrame = createGetCSSColorForFrame(frameToColorBucket)
const canvasContext = getCanvasContext(glCanvas)
const flamechart = getCalleeFlamegraph({
calleeProfile: getCalleeProfile({profile, frame: selectedFrame, flattenRecursion}),
getColorBucketForFrame,
})
const flamechartRenderer = getCalleeFlamegraphRenderer({canvasContext, flamechart})
return {
renderInverted: false,
flamechart,
flamechartRenderer,
canvasContext,
getCSSColorForFrame,
...createFlamechartSetters(dispatch, FlamechartID.SANDWICH_CALLEES, index),
// This overrides the setSelectedNode specified in createFlamechartSettesr
setSelectedNode: () => {},
...callerCallee.calleeFlamegraph,
}
},
)
-86
View File
@@ -1,86 +0,0 @@
import {memoizeByShallowEquality, noop} from '../lib/utils'
import {Profile, Frame} from '../lib/profile'
import {Flamechart} from '../lib/flamechart'
import {
createMemoizedFlamechartRenderer,
FlamechartViewContainerProps,
useFlamechartSetters,
} from './flamechart-view-container'
import {
getCanvasContext,
createGetColorBucketForFrame,
createGetCSSColorForFrame,
getFrameToColorBucket,
} from '../store/getters'
import {FlamechartID} from '../store/flamechart-view-state'
import {FlamechartWrapper} from './flamechart-wrapper'
import {useAppSelector} from '../store'
import {h} from 'preact'
import {memo} from 'preact/compat'
const getCalleeProfile = memoizeByShallowEquality<
{
profile: Profile
frame: Frame
flattenRecursion: boolean
},
Profile
>(({profile, frame, flattenRecursion}) => {
let p = profile.getProfileForCalleesOf(frame)
return flattenRecursion ? p.getProfileWithRecursionFlattened() : p
})
const getCalleeFlamegraph = memoizeByShallowEquality<
{
calleeProfile: Profile
getColorBucketForFrame: (frame: Frame) => number
},
Flamechart
>(({calleeProfile, getColorBucketForFrame}) => {
return new Flamechart({
getTotalWeight: calleeProfile.getTotalNonIdleWeight.bind(calleeProfile),
forEachCall: calleeProfile.forEachCallGrouped.bind(calleeProfile),
formatValue: calleeProfile.formatValue.bind(calleeProfile),
getColorBucketForFrame,
})
})
const getCalleeFlamegraphRenderer = createMemoizedFlamechartRenderer()
export const CalleeFlamegraphView = memo((ownProps: FlamechartViewContainerProps) => {
const {activeProfileState} = ownProps
const {index, profile, sandwichViewState} = activeProfileState
const flattenRecursion = useAppSelector(state => state.flattenRecursion, [])
const glCanvas = useAppSelector(state => state.glCanvas, [])
if (!profile) throw new Error('profile missing')
if (!glCanvas) throw new Error('glCanvas missing')
const {callerCallee} = sandwichViewState
if (!callerCallee) throw new Error('callerCallee missing')
const {selectedFrame} = callerCallee
const frameToColorBucket = getFrameToColorBucket(profile)
const getColorBucketForFrame = createGetColorBucketForFrame(frameToColorBucket)
const getCSSColorForFrame = createGetCSSColorForFrame(frameToColorBucket)
const canvasContext = getCanvasContext(glCanvas)
const flamechart = getCalleeFlamegraph({
calleeProfile: getCalleeProfile({profile, frame: selectedFrame, flattenRecursion}),
getColorBucketForFrame,
})
const flamechartRenderer = getCalleeFlamegraphRenderer({canvasContext, flamechart})
return (
<FlamechartWrapper
renderInverted={false}
flamechart={flamechart}
flamechartRenderer={flamechartRenderer}
canvasContext={canvasContext}
getCSSColorForFrame={getCSSColorForFrame}
{...useFlamechartSetters(FlamechartID.SANDWICH_CALLEES, index)}
{...callerCallee.calleeFlamegraph}
// This overrides the setSelectedNode specified in useFlamechartSettesr
setSelectedNode={noop}
/>
)
})
+5 -3
View File
@@ -1,4 +1,4 @@
import {h} from 'preact'
import {h, Component} from 'preact'
import {StyleSheet, css} from 'aphrodite'
import {Colors, FontSize} from './style'
@@ -6,8 +6,10 @@ interface ColorChitProps {
color: string
}
export function ColorChit(props: ColorChitProps) {
return <span className={css(style.stackChit)} style={{backgroundColor: props.color}} />
export class ColorChit extends Component<ColorChitProps, {}> {
render() {
return <span className={css(style.stackChit)} style={{backgroundColor: this.props.color}} />
}
}
const style = StyleSheet.create({
+6 -6
View File
@@ -1,5 +1,5 @@
import {StyleDeclarationValue, css} from 'aphrodite'
import {h, Component, JSX} from 'preact'
import {h, Component} from 'preact'
import {style} from './flamechart-style'
import {formatPercent} from '../lib/utils'
import {Frame, CallTreeNode} from '../lib/profile'
@@ -19,8 +19,8 @@ class StatisticsTable extends Component<StatisticsTableProps, {}> {
render() {
const total = this.props.formatter(this.props.selectedTotal)
const self = this.props.formatter(this.props.selectedSelf)
const totalPerc = (100.0 * this.props.selectedTotal) / this.props.grandTotal
const selfPerc = (100.0 * this.props.selectedSelf) / this.props.grandTotal
const totalPerc = 100.0 * this.props.selectedTotal / this.props.grandTotal
const selfPerc = 100.0 * this.props.selectedSelf / this.props.grandTotal
return (
<div className={css(style.statsTable)}>
@@ -62,15 +62,15 @@ class StackTraceView extends Component<StackTraceViewProps, {}> {
row.push(<ColorChit color={this.props.getFrameColor(frame)} />)
if (rows.length) {
row.push(<span className={css(style.stackFileLine)}>&gt; </span>)
row.push(<span className={css(style.stackFileLine)}>> </span>)
}
row.push(frame.name)
if (frame.file) {
let pos = frame.file
if (frame.line != null) {
if (frame.line) {
pos += `:${frame.line}`
if (frame.col != null) {
if (frame.col) {
pos += `:${frame.col}`
}
}

Some files were not shown because too many files have changed in this diff Show More