@paulirish/trace_engine 0.0.14 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +27 -0
  2. package/PAUL.readme.md +5 -0
  3. package/README.md +156 -0
  4. package/analyze-trace.mjs +184 -0
  5. package/core/platform/array-utilities.d.ts +66 -0
  6. package/core/platform/array-utilities.js +199 -0
  7. package/core/platform/array-utilities.js.map +1 -0
  8. package/core/platform/date-utilities.d.ts +2 -0
  9. package/core/platform/date-utilities.js +14 -0
  10. package/core/platform/date-utilities.js.map +1 -0
  11. package/core/platform/dcheck-tsconfig.json +8 -0
  12. package/core/platform/dcheck.d.ts +4 -0
  13. package/core/platform/dcheck.js +5 -0
  14. package/core/platform/dom-utilities.d.ts +8 -0
  15. package/core/platform/dom-utilities.js +109 -0
  16. package/core/platform/dom-utilities.js.map +1 -0
  17. package/core/platform/keyboard-utilities.d.ts +17 -0
  18. package/core/platform/keyboard-utilities.js +22 -0
  19. package/core/platform/keyboard-utilities.js.map +1 -0
  20. package/core/platform/map-utilities.d.ts +18 -0
  21. package/core/platform/map-utilities.js +76 -0
  22. package/core/platform/map-utilities.js.map +1 -0
  23. package/core/platform/number-utilities.d.ts +15 -0
  24. package/core/platform/number-utilities.js +82 -0
  25. package/core/platform/number-utilities.js.map +1 -0
  26. package/core/platform/promise-utilities.d.ts +10 -0
  27. package/core/platform/promise-utilities.js +18 -0
  28. package/core/platform/promise-utilities.js.map +1 -0
  29. package/core/platform/set-utilities.d.ts +2 -0
  30. package/core/platform/set-utilities.js +23 -0
  31. package/core/platform/set-utilities.js.map +1 -0
  32. package/core/platform/string-utilities.d.ts +71 -0
  33. package/core/platform/string-utilities.js +513 -0
  34. package/core/platform/string-utilities.js.map +1 -0
  35. package/core/platform/typescript-utilities.d.ts +56 -0
  36. package/core/platform/typescript-utilities.js +25 -0
  37. package/core/platform/typescript-utilities.js.map +1 -0
  38. package/models/trace/EntriesFilter.d.ts +6 -0
  39. package/models/trace/EntriesFilter.js +17 -0
  40. package/models/trace/EntriesFilter.js.map +1 -1
  41. package/package.json +8 -6
  42. package/test/invalid-animation-events.json.gz +0 -0
  43. package/test/test-trace-engine.mjs +52 -0
  44. /package/core/platform/{Brand.d.ts → brand.d.ts} +0 -0
  45. /package/core/platform/{Brand.js → brand.js} +0 -0
  46. /package/core/platform/{Brand.js.map → brand.js.map} +0 -0
package/LICENSE ADDED
@@ -0,0 +1,27 @@
1
+ // Copyright 2014 The Chromium Authors. All rights reserved.
2
+ //
3
+ // Redistribution and use in source and binary forms, with or without
4
+ // modification, are permitted provided that the following conditions are
5
+ // met:
6
+ //
7
+ // * Redistributions of source code must retain the above copyright
8
+ // notice, this list of conditions and the following disclaimer.
9
+ // * Redistributions in binary form must reproduce the above
10
+ // copyright notice, this list of conditions and the following disclaimer
11
+ // in the documentation and/or other materials provided with the
12
+ // distribution.
13
+ // * Neither the name of Google Inc. nor the names of its
14
+ // contributors may be used to endorse or promote products derived from
15
+ // this software without specific prior written permission.
16
+ //
17
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/PAUL.readme.md ADDED
@@ -0,0 +1,5 @@
1
+ # see readme for cmds
2
+
3
+ # some types thing that might work
4
+
5
+ node out/Typed/../../third_party/typescript/../../node_modules/typescript/bin/tsc -p out/Typed/gen/front_end/models/trace/trace-tsconfig.json # this then has js/map/d.ts. should be able to use for typs
package/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # Trace Model (NOT FOR PUBLIC CONSUMPTION)
2
+
3
+ This folder contains the new trace engine that was first implemented for the Performance Insights panel and is now being repurposed as the primary trace engine that we use within DevTools.
4
+
5
+ ## API quickstart
6
+
7
+ ```js
8
+ import * as TraceModel from '@paulirish/trace_engine';
9
+
10
+ polyfillDOMRect();
11
+ const processor = TraceModel.Processor.TraceProcessor.createWithAllHandlers();
12
+
13
+ await processor.parse(traceEvents);
14
+ console.log(processor.data)
15
+ ```
16
+
17
+ **Note:** in reality to run in Node, you'll need to polyfill `window.DOMRect`. 😜
18
+
19
+ See the included `analyze-trace.mjs` a runnable invocation.
20
+
21
+ ## Maintainer cheatsheet
22
+
23
+ See also http://go/btlax
24
+
25
+ #### Build, run, extract
26
+
27
+ ```sh
28
+ # Build devtools and prep a package
29
+ scripts/trace/build-trace-engine-lib.sh
30
+
31
+ # run
32
+ node scripts/trace/analyze-trace.mjs test/unittests/fixtures/traces/web-dev.json.gz
33
+
34
+ # test
35
+ node scripts/trace/test/test-trace-engine.mjs
36
+
37
+ # copy built files to $HOME/code/trace_engine
38
+ scripts/trace/copy-build-trace-engine-for-publish.sh
39
+ ```
40
+
41
+ #### Test and publish
42
+
43
+ ```sh
44
+ # switch to standalone
45
+ cd $HOME/code/trace_engine
46
+
47
+ # test
48
+ node test/test-trace-engine.mjs
49
+
50
+ # bump and publish
51
+ npm version v0.0.XXX # Manually determine next version
52
+ npm publish --access public --dry-run
53
+ npm publish --access public
54
+ ```
55
+
56
+ ## High level architecture
57
+
58
+ ```
59
+ ┌──────────────┐
60
+ │ Model#parse ├───┐
61
+ └──────────────┘ │
62
+
63
+ ┌──────────▼──────────┐
64
+ │async processor#parse│
65
+ └──────────┬──────────┘
66
+
67
+ ┌──────────▼────────────┐
68
+ │for handler of handlers│
69
+ └───┬────────────────┬──┘
70
+ │ │
71
+ ┌────────────────▼────┐ ┌─────▼────────────────┐
72
+ │NetworkRequestHandler│ │...many more handlers │
73
+ │ │ │ │
74
+ │ reset() │ │ │
75
+ │ initialize() │ │ │
76
+ │ │ │ │
77
+ │ handleEvent() │ │ │
78
+ │ │ │ │
79
+ │ finalize() │ │ │
80
+ │ │ │ │
81
+ │ data() │ │ │ │
82
+ └─────────────────────┘ │ └──────────────────────┘
83
+
84
+
85
+ ┌──────────────────▼─────────────────┐
86
+ │const data = model.traceParsedData()│
87
+ └────────────────────────────────────┘
88
+ ```
89
+
90
+ `Model#parse` is the entrypoint into the engine and is the public interface that consumers use to initiate tracing and to fetch data back.
91
+
92
+ All the processing is done by the `Processor`. The processor contains a series of *Handlers*, each of which is responsible for parsing events of a particular category.
93
+
94
+ The trace processor loops over every event in the trace and calls each handler in turn (done this way so we only loop over the trace file once, rather than doing it once-per-handler). A Handler is a file that exposes a set of methods, most importantly `handleEvent()` and `data()`. The `handleEvent` function will be called for each event in the trace, and it is up to an individual handler to do something with that event if it needs to. The `data` method should return the final data that has been parsed and generated by the handler.
95
+
96
+ Once processing is done (read on for more details on how to track this), you can use the `traceParsedData()` method to fetch the result of parsing a given trace.
97
+
98
+ ## Enabled handlers and creating a model
99
+
100
+ At the time of writing (06 June 2023) we are midway through a migration of the Performanc Panel's trace engine from the SDK.TracingModel to the new TraceEngine. Consequently, not all of the TraceEngine's handlers are currently active, because we don't want to run expensive handlers whose data we do not yet use in the UI.
101
+
102
+ Therefore, to create a model instance, we use `Model.createWithRequiredHandlersForMigration()`, which initializes a model configured correctly with the right handlers.
103
+
104
+ Once the migration is done, we can swap to `Model.createWithAllHandlers()` and remove the code that enables a subset of the handlers to run.
105
+
106
+ If you want to strictly control the set of handlers that are run (for example, if you only want to run one particular handler), you can initialize the model yourself and pass in the set of handlers:
107
+
108
+ ```ts
109
+ const model = new Model({
110
+ NetworkRequestHandler: Handlers.ModelHandlers.NetworkRequestHandler,
111
+ })
112
+ ```
113
+
114
+ ## Parsing a trace and getting data back
115
+
116
+ Once you have an instance of the model, you can call the `parse` method to take a set of raw events and parse them. Once parsed, you then have to call the `traceParsedData` method, providing an index of the trace you want to have the data for. This is because any model can store a number of traces. Each trace is given an index, which starts at 0 and increments by one as a new trace is parsed.
117
+
118
+ If you are managing multiple traces, you should store them in some form of indexed data structure so you can easily know which index to use to fetch any data from the model. You may delete a trace with `deleteTraceByIndex`, which will then update the indexes of all other traces too.
119
+
120
+ If you need to check how many traces you have, you can call `model.size()`. The latest trace's index is therefore always `model.size() - 1`.
121
+
122
+ ## Waiting for updates from the model
123
+
124
+ When you call `parse` you have two options. You can `await` it, which will wait until the trace is fully parsed:
125
+
126
+ ```ts
127
+ await this.model.parse();
128
+ ```
129
+
130
+ But it's likely preferable to instead use events, to avoid blocking the UI whilst parsing is in progress. You can listen to the `ModelUpdateEvent` for updates:
131
+
132
+ ```ts
133
+ this.model.addEventListener(Model.ModelUpdateEvent.eventName, event => {
134
+ const {data} = event as Model.ModelUpdateEvent;
135
+
136
+ if (data.data === 'done') {
137
+ // trace is complete
138
+ const newestData = this.model.traceParsedData(this.model.size() - 1);
139
+ } else {
140
+ // data.data will be an object: { index: X, total: Y}, which represents how many events (X) have been processed out of a total (Y).
141
+ // This can be used to show a progress bar, for example.
142
+ }
143
+ })
144
+ ```
145
+
146
+ ## The structure of the final data object
147
+
148
+ The object returned from `traceParsedData()` is an object of key-value pairs where each key is the name of a handler, and the value is the data that was parsed and returned from that handler.
149
+
150
+ ```ts
151
+ {
152
+ NetworkRequestHandler: ReturnType<typeof NetworkRequestHandler['data']>,
153
+ LayoutShiftHandler: ReturnType<typeof LayoutShiftHandler['data']>,
154
+ // and so on for each enabled Handler
155
+ }
156
+ ```
@@ -0,0 +1,184 @@
1
+ // Copyright 2023 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ // Run this first:
6
+ // front_end/models/trace/build-trace-engine-lib.sh
7
+
8
+ /* eslint-disable rulesdir/es_modules_import */
9
+ import fs from 'node:fs';
10
+ import zlib from 'node:zlib';
11
+
12
+ /** @typedef {import('../front_end/models/trace/trace.ts')} TraceEngine */
13
+
14
+ // For types... see Connor's manual hack here:
15
+ // https://github.com/GoogleChrome/lighthouse/pull/15703/files#diff-ec7e073cf0e6135d4f2af9bc04fe6100ec0df80ad1686bee2da53871be5f1a7b
16
+ // and https://github.com/GoogleChrome/lighthouse/pull/15703/files#diff-6dab4507247217209f5ab0f6c343ca2b00af1300878abba81fb74d51cdfbedf9
17
+
18
+ /** @type {TraceEngine} */
19
+ import * as TraceEngine from './models/trace/trace.js';
20
+
21
+ polyfillDOMRect();
22
+
23
+ /**
24
+ * @param {string} filename
25
+ * @returns {Promise<TraceEngine.TraceModel>}
26
+ */
27
+ export async function analyzeTrace(filename) {
28
+ const traceEvents = loadTraceEventsFromFile(filename);
29
+ const model = TraceEngine.TraceModel.Model.createWithAllHandlers(TraceEngine.Types.Configuration.DEFAULT); // aka `fullTraceEngine`
30
+ await model.parse(traceEvents);
31
+ return model.traceParsedData();
32
+ }
33
+
34
+ // If run as CLI, parse the argv trace (or a fallback)
35
+ if (import.meta.url.endsWith(process?.argv[1])) {
36
+ cli();
37
+ }
38
+
39
+ async function cli() {
40
+ const filename = process.argv.at(2);
41
+ const TraceEngine = await analyzeTrace(filename);
42
+ console.log(TraceEngine);
43
+ }
44
+
45
+
46
+ /**
47
+ * @param {string=} filename
48
+ * @returns TraceEvent[]
49
+ */
50
+ function loadTraceEventsFromFile(filename) {
51
+ const fileBuf = fs.readFileSync(filename);
52
+ let data;
53
+ if (isGzip(fileBuf)) {
54
+ data = zlib.gunzipSync(fileBuf);
55
+ } else {
56
+ data = fileBuf.toString('utf8');
57
+ }
58
+ const json = JSON.parse(data);
59
+ const traceEvents = json.traceEvents ?? json;
60
+ console.assert(Array.isArray(traceEvents));
61
+ return traceEvents;
62
+ }
63
+
64
+ /**
65
+ * Read the first 3 bytes looking for the gzip signature in the file header
66
+ * https://www.rfc-editor.org/rfc/rfc1952#page-6
67
+ * @param {ArrayBuffer} ab
68
+ * @returns boolean
69
+ */
70
+ function isGzip(ab) {
71
+ const buf = new Uint8Array(ab);
72
+ if (!buf || buf.length < 3) {
73
+ return false;
74
+ }
75
+ return buf[0] === 0x1F && buf[1] === 0x8B && buf[2] === 0x08;
76
+ }
77
+
78
+ function polyfillDOMRect() {
79
+
80
+ // devtools assumes clientside :(
81
+
82
+ // Everything else in here is the DOMRect polyfill
83
+ // https://raw.githubusercontent.com/JakeChampion/polyfill-library/master/polyfills/DOMRect/polyfill.js
84
+
85
+ (function (global) {
86
+ function number(v) {
87
+ return v === undefined ? 0 : Number(v);
88
+ }
89
+
90
+ function different(u, v) {
91
+ return u !== v && !(isNaN(u) && isNaN(v));
92
+ }
93
+
94
+ function DOMRect(xArg, yArg, wArg, hArg) {
95
+ let x, y, width, height, left, right, top, bottom;
96
+
97
+ x = number(xArg);
98
+ y = number(yArg);
99
+ width = number(wArg);
100
+ height = number(hArg);
101
+
102
+ Object.defineProperties(this, {
103
+ x: {
104
+ get: function () { return x; },
105
+ set: function (newX) {
106
+ if (different(x, newX)) {
107
+ x = newX;
108
+ left = right = undefined;
109
+ }
110
+ },
111
+ enumerable: true
112
+ },
113
+ y: {
114
+ get: function () { return y; },
115
+ set: function (newY) {
116
+ if (different(y, newY)) {
117
+ y = newY;
118
+ top = bottom = undefined;
119
+ }
120
+ },
121
+ enumerable: true
122
+ },
123
+ width: {
124
+ get: function () { return width; },
125
+ set: function (newWidth) {
126
+ if (different(width, newWidth)) {
127
+ width = newWidth;
128
+ left = right = undefined;
129
+ }
130
+ },
131
+ enumerable: true
132
+ },
133
+ height: {
134
+ get: function () { return height; },
135
+ set: function (newHeight) {
136
+ if (different(height, newHeight)) {
137
+ height = newHeight;
138
+ top = bottom = undefined;
139
+ }
140
+ },
141
+ enumerable: true
142
+ },
143
+ left: {
144
+ get: function () {
145
+ if (left === undefined) {
146
+ left = x + Math.min(0, width);
147
+ }
148
+ return left;
149
+ },
150
+ enumerable: true
151
+ },
152
+ right: {
153
+ get: function () {
154
+ if (right === undefined) {
155
+ right = x + Math.max(0, width);
156
+ }
157
+ return right;
158
+ },
159
+ enumerable: true
160
+ },
161
+ top: {
162
+ get: function () {
163
+ if (top === undefined) {
164
+ top = y + Math.min(0, height);
165
+ }
166
+ return top;
167
+ },
168
+ enumerable: true
169
+ },
170
+ bottom: {
171
+ get: function () {
172
+ if (bottom === undefined) {
173
+ bottom = y + Math.max(0, height);
174
+ }
175
+ return bottom;
176
+ },
177
+ enumerable: true
178
+ }
179
+ });
180
+ }
181
+
182
+ globalThis.DOMRect = DOMRect;
183
+ })(globalThis);
184
+ }
@@ -0,0 +1,66 @@
1
+ export declare const removeElement: <T>(array: T[], element: T, firstOnly?: boolean) => boolean;
2
+ type NumberComparator = (a: number, b: number) => number;
3
+ export declare function sortRange(array: number[], comparator: NumberComparator, leftBound: number, rightBound: number, sortWindowLeft: number, sortWindowRight: number): number[];
4
+ export declare const binaryIndexOf: <T, S>(array: T[], value: S, comparator: (a: S, b: T) => number) => number;
5
+ export declare const intersectOrdered: <T>(array1: T[], array2: T[], comparator: (a: T, b: T) => number) => T[];
6
+ export declare const mergeOrdered: <T>(array1: T[], array2: T[], comparator: (a: T, b: T) => number) => T[];
7
+ export declare const DEFAULT_COMPARATOR: (a: string | number, b: string | number) => -1 | 0 | 1;
8
+ /**
9
+ * Returns the index of the element closest to the needle that is equal to or
10
+ * greater than it. Assumes that the provided array is sorted.
11
+ *
12
+ * If no element is found, the right bound is returned.
13
+ *
14
+ * Uses the provided comparator function to determine if two items are equal or
15
+ * if one is greater than the other. If you are working with strings or
16
+ * numbers, you can use ArrayUtilities.DEFAULT_COMPARATOR. Otherwise, you
17
+ * should define one that takes the needle element and an element from the
18
+ * array and returns a positive or negative number to indicate which is greater
19
+ * than the other.
20
+ *
21
+ * When specified, |left| (inclusive) and |right| (exclusive) indices
22
+ * define the search window.
23
+ */
24
+ export declare function lowerBound<T>(array: Uint32Array | Int32Array, needle: T, comparator: (needle: T, b: number) => number, left?: number, right?: number): number;
25
+ export declare function lowerBound<S, T>(array: S[], needle: T, comparator: (needle: T, b: S) => number, left?: number, right?: number): number;
26
+ export declare function lowerBound<S, T>(array: readonly S[], needle: T, comparator: (needle: T, b: S) => number, left?: number, right?: number): number;
27
+ /**
28
+ * Returns the index of the element closest to the needle that is greater than
29
+ * it. Assumes that the provided array is sorted.
30
+ *
31
+ * If no element is found, the right bound is returned.
32
+ *
33
+ * Uses the provided comparator function to determine if two items are equal or
34
+ * if one is greater than the other. If you are working with strings or
35
+ * numbers, you can use ArrayUtilities.DEFAULT_COMPARATOR. Otherwise, you
36
+ * should define one that takes the needle element and an element from the
37
+ * array and returns a positive or negative number to indicate which is greater
38
+ * than the other.
39
+ *
40
+ * When specified, |left| (inclusive) and |right| (exclusive) indices
41
+ * define the search window.
42
+ */
43
+ export declare function upperBound<T>(array: Uint32Array, needle: T, comparator: (needle: T, b: number) => number, left?: number, right?: number): number;
44
+ export declare function upperBound<S, T>(array: S[], needle: T, comparator: (needle: T, b: S) => number, left?: number, right?: number): number;
45
+ /**
46
+ * Obtains the first item in the array that satisfies the predicate function.
47
+ * So, for example, if the array was arr = [2, 4, 6, 8, 10], and you are looking for
48
+ * the first item arr[i] such that arr[i] > 5 you would be returned 2, because
49
+ * array[2] is 6, the first item in the array that satisfies the
50
+ * predicate function.
51
+ *
52
+ * Please note: this presupposes that the array is already ordered.
53
+ */
54
+ export declare function nearestIndexFromBeginning<T>(arr: T[], predicate: (arrayItem: T) => boolean): number | null;
55
+ /**
56
+ * Obtains the last item in the array that satisfies the predicate function.
57
+ * So, for example, if the array was arr = [2, 4, 6, 8, 10], and you are looking for
58
+ * the last item arr[i] such that arr[i] < 5 you would be returned 1, because
59
+ * arr[1] is 4, the last item in the array that satisfies the
60
+ * predicate function.
61
+ *
62
+ * Please note: this presupposes that the array is already ordered.
63
+ */
64
+ export declare function nearestIndexFromEnd<T>(arr: readonly T[], predicate: (arrayItem: T) => boolean): number | null;
65
+ export declare function arrayDoesNotContainNullOrUndefined<T>(arr: (T | null | undefined)[]): arr is T[];
66
+ export {};
@@ -0,0 +1,199 @@
1
+ // Copyright (c) 2020 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+ export const removeElement = (array, element, firstOnly) => {
5
+ let index = array.indexOf(element);
6
+ if (index === -1) {
7
+ return false;
8
+ }
9
+ if (firstOnly) {
10
+ array.splice(index, 1);
11
+ return true;
12
+ }
13
+ for (let i = index + 1, n = array.length; i < n; ++i) {
14
+ if (array[i] !== element) {
15
+ array[index++] = array[i];
16
+ }
17
+ }
18
+ array.length = index;
19
+ return true;
20
+ };
21
+ function swap(array, i1, i2) {
22
+ const temp = array[i1];
23
+ array[i1] = array[i2];
24
+ array[i2] = temp;
25
+ }
26
+ function partition(array, comparator, left, right, pivotIndex) {
27
+ const pivotValue = array[pivotIndex];
28
+ swap(array, right, pivotIndex);
29
+ let storeIndex = left;
30
+ for (let i = left; i < right; ++i) {
31
+ if (comparator(array[i], pivotValue) < 0) {
32
+ swap(array, storeIndex, i);
33
+ ++storeIndex;
34
+ }
35
+ }
36
+ swap(array, right, storeIndex);
37
+ return storeIndex;
38
+ }
39
+ function quickSortRange(array, comparator, left, right, sortWindowLeft, sortWindowRight) {
40
+ if (right <= left) {
41
+ return;
42
+ }
43
+ const pivotIndex = Math.floor(Math.random() * (right - left)) + left;
44
+ const pivotNewIndex = partition(array, comparator, left, right, pivotIndex);
45
+ if (sortWindowLeft < pivotNewIndex) {
46
+ quickSortRange(array, comparator, left, pivotNewIndex - 1, sortWindowLeft, sortWindowRight);
47
+ }
48
+ if (pivotNewIndex < sortWindowRight) {
49
+ quickSortRange(array, comparator, pivotNewIndex + 1, right, sortWindowLeft, sortWindowRight);
50
+ }
51
+ }
52
+ export function sortRange(array, comparator, leftBound, rightBound, sortWindowLeft, sortWindowRight) {
53
+ if (leftBound === 0 && rightBound === (array.length - 1) && sortWindowLeft === 0 && sortWindowRight >= rightBound) {
54
+ array.sort(comparator);
55
+ }
56
+ else {
57
+ quickSortRange(array, comparator, leftBound, rightBound, sortWindowLeft, sortWindowRight);
58
+ }
59
+ return array;
60
+ }
61
+ export const binaryIndexOf = (array, value, comparator) => {
62
+ const index = lowerBound(array, value, comparator);
63
+ return index < array.length && comparator(value, array[index]) === 0 ? index : -1;
64
+ };
65
+ function mergeOrIntersect(array1, array2, comparator, mergeNotIntersect) {
66
+ const result = [];
67
+ let i = 0;
68
+ let j = 0;
69
+ while (i < array1.length && j < array2.length) {
70
+ const compareValue = comparator(array1[i], array2[j]);
71
+ if (mergeNotIntersect || !compareValue) {
72
+ result.push(compareValue <= 0 ? array1[i] : array2[j]);
73
+ }
74
+ if (compareValue <= 0) {
75
+ i++;
76
+ }
77
+ if (compareValue >= 0) {
78
+ j++;
79
+ }
80
+ }
81
+ if (mergeNotIntersect) {
82
+ while (i < array1.length) {
83
+ result.push(array1[i++]);
84
+ }
85
+ while (j < array2.length) {
86
+ result.push(array2[j++]);
87
+ }
88
+ }
89
+ return result;
90
+ }
91
+ export const intersectOrdered = (array1, array2, comparator) => {
92
+ return mergeOrIntersect(array1, array2, comparator, false);
93
+ };
94
+ export const mergeOrdered = (array1, array2, comparator) => {
95
+ return mergeOrIntersect(array1, array2, comparator, true);
96
+ };
97
+ export const DEFAULT_COMPARATOR = (a, b) => {
98
+ return a < b ? -1 : (a > b ? 1 : 0);
99
+ };
100
+ export function lowerBound(array, needle, comparator, left, right) {
101
+ let l = left || 0;
102
+ let r = right !== undefined ? right : array.length;
103
+ while (l < r) {
104
+ const m = (l + r) >> 1;
105
+ if (comparator(needle, array[m]) > 0) {
106
+ l = m + 1;
107
+ }
108
+ else {
109
+ r = m;
110
+ }
111
+ }
112
+ return r;
113
+ }
114
+ export function upperBound(array, needle, comparator, left, right) {
115
+ let l = left || 0;
116
+ let r = right !== undefined ? right : array.length;
117
+ while (l < r) {
118
+ const m = (l + r) >> 1;
119
+ if (comparator(needle, array[m]) >= 0) {
120
+ l = m + 1;
121
+ }
122
+ else {
123
+ r = m;
124
+ }
125
+ }
126
+ return r;
127
+ }
128
+ /**
129
+ * Obtains the first or last item in the array that satisfies the predicate function.
130
+ * So, for example, if the array were arr = [2, 4, 6, 8, 10], and you are looking for
131
+ * the last item arr[i] such that arr[i] < 5 you would be returned 1, because
132
+ * array[1] is 4, the last item in the array that satisfies the
133
+ * predicate function.
134
+ *
135
+ * If instead you were looking for the first item in the same array that satisfies
136
+ * arr[i] > 5 you would be returned 2 because array[2] = 6.
137
+ *
138
+ * Please note: this presupposes that the array is already ordered.
139
+ */
140
+ function nearestIndex(arr, predicate, searchStart) {
141
+ const searchFromEnd = searchStart === "END" /* NearestSearchStart.END */;
142
+ if (arr.length === 0) {
143
+ return null;
144
+ }
145
+ let left = 0;
146
+ let right = arr.length - 1;
147
+ let pivot = 0;
148
+ let matchesPredicate = false;
149
+ let moveToTheRight = false;
150
+ let middle = 0;
151
+ do {
152
+ middle = left + (right - left) / 2;
153
+ pivot = searchFromEnd ? Math.ceil(middle) : Math.floor(middle);
154
+ matchesPredicate = predicate(arr[pivot]);
155
+ moveToTheRight = matchesPredicate === searchFromEnd;
156
+ if (moveToTheRight) {
157
+ left = Math.min(right, pivot + (left === pivot ? 1 : 0));
158
+ }
159
+ else {
160
+ right = Math.max(left, pivot + (right === pivot ? -1 : 0));
161
+ }
162
+ } while (right !== left);
163
+ // Special-case: the indexed item doesn't pass the predicate. This
164
+ // occurs when none of the items in the array are a match for the
165
+ // predicate.
166
+ if (!predicate(arr[left])) {
167
+ return null;
168
+ }
169
+ return left;
170
+ }
171
+ /**
172
+ * Obtains the first item in the array that satisfies the predicate function.
173
+ * So, for example, if the array was arr = [2, 4, 6, 8, 10], and you are looking for
174
+ * the first item arr[i] such that arr[i] > 5 you would be returned 2, because
175
+ * array[2] is 6, the first item in the array that satisfies the
176
+ * predicate function.
177
+ *
178
+ * Please note: this presupposes that the array is already ordered.
179
+ */
180
+ export function nearestIndexFromBeginning(arr, predicate) {
181
+ return nearestIndex(arr, predicate, "BEGINNING" /* NearestSearchStart.BEGINNING */);
182
+ }
183
+ /**
184
+ * Obtains the last item in the array that satisfies the predicate function.
185
+ * So, for example, if the array was arr = [2, 4, 6, 8, 10], and you are looking for
186
+ * the last item arr[i] such that arr[i] < 5 you would be returned 1, because
187
+ * arr[1] is 4, the last item in the array that satisfies the
188
+ * predicate function.
189
+ *
190
+ * Please note: this presupposes that the array is already ordered.
191
+ */
192
+ export function nearestIndexFromEnd(arr, predicate) {
193
+ return nearestIndex(arr, predicate, "END" /* NearestSearchStart.END */);
194
+ }
195
+ // Type guard for ensuring that `arr` does not contain null or undefined
196
+ export function arrayDoesNotContainNullOrUndefined(arr) {
197
+ return !arr.includes(null) && !arr.includes(undefined);
198
+ }
199
+ //# sourceMappingURL=array-utilities.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"array-utilities.js","sourceRoot":"","sources":["../../../../../../front_end/core/platform/array-utilities.ts"],"names":[],"mappings":"AAAA,gEAAgE;AAChE,yEAAyE;AACzE,6BAA6B;AAE7B,MAAM,CAAC,MAAM,aAAa,GAAG,CAAI,KAAU,EAAE,OAAU,EAAE,SAAmB,EAAW,EAAE;IACvF,IAAI,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IACnC,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;QAChB,OAAO,KAAK,CAAC;KACd;IACD,IAAI,SAAS,EAAE;QACb,KAAK,C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-style license that can be\n// found in the LICENSE file.\n\nexport const removeElement = <T>(array: T[], element: T, firstOnly?: boolean): boolean => {\n let index = array.indexOf(element);\n if (index === -1) {\n return false;\n }\n if (firstOnly) {\n array.splice(index, 1);\n return true;\n }\n for (let i = index + 1, n = array.length; i < n; ++i) {\n if (array[i] !== element) {\n array[index++] = array[i];\n }\n }\n array.length = index;\n return true;\n};\n\ntype NumberComparator = (a: number, b: number) => number;\n\nfunction swap(array: number[], i1: number, i2: number): void {\n const temp = array[i1];\n array[i1] = array[i2];\n array[i2] = temp;\n}\n\nfunction partition(\n array: number[], comparator: NumberComparator, left: number, right: number, pivotIndex: number): number {\n const pivotValue = array[pivotIndex];\n swap(array, right, pivotIndex);\n let storeIndex = left;\n for (let i = left; i < right; ++i) {\n if (comparator(array[i], pivotValue) < 0) {\n swap(array, storeIndex, i);\n ++storeIndex;\n }\n }\n swap(array, right, storeIndex);\n return storeIndex;\n}\n\nfunction quickSortRange(\n array: number[], comparator: NumberComparator, left: number, right: number, sortWindowLeft: number,\n sortWindowRight: number): void {\n if (right <= left) {\n return;\n }\n const pivotIndex = Math.floor(Math.random() * (right - left)) + left;\n const pivotNewIndex = partition(array, comparator, left, right, pivotIndex);\n if (sortWindowLeft < pivotNewIndex) {\n quickSortRange(array, comparator, left, pivotNewIndex - 1, sortWindowLeft, sortWindowRight);\n }\n if (pivotNewIndex < sortWindowRight) {\n quickSortRange(array, comparator, pivotNewIndex + 1, right, sortWindowLeft, sortWindowRight);\n }\n}\n\nexport function sortRange(\n array: number[], comparator: NumberComparator, leftBound: number, rightBound: number, sortWindowLeft: number,\n sortWindowRight: number): number[] {\n if (leftBound === 0 && rightBound === (array.length - 1) && sortWindowLeft === 0 && sortWindowRight >= rightBound) {\n array.sort(comparator);\n } else {\n quickSortRange(array, comparator, leftBound, rightBound, sortWindowLeft, sortWindowRight);\n }\n return array;\n}\nexport const binaryIndexOf = <T, S>(array: T[], value: S, comparator: (a: S, b: T) => number): number => {\n const index = lowerBound(array, value, comparator);\n return index < array.length && comparator(value, array[index]) === 0 ? index : -1;\n};\n\nfunction mergeOrIntersect<T>(\n array1: T[], array2: T[], comparator: (a: T, b: T) => number, mergeNotIntersect: boolean): T[] {\n const result = [];\n let i = 0;\n let j = 0;\n while (i < array1.length && j < array2.length) {\n const compareValue = comparator(array1[i], array2[j]);\n if (mergeNotIntersect || !compareValue) {\n result.push(compareValue <= 0 ? array1[i] : array2[j]);\n }\n if (compareValue <= 0) {\n i++;\n }\n if (compareValue >= 0) {\n j++;\n }\n }\n if (mergeNotIntersect) {\n while (i < array1.length) {\n result.push(array1[i++]);\n }\n while (j < array2.length) {\n result.push(array2[j++]);\n }\n }\n return result;\n}\n\nexport const intersectOrdered = <T>(array1: T[], array2: T[], comparator: (a: T, b: T) => number): T[] => {\n return mergeOrIntersect(array1, array2, comparator, false);\n};\n\nexport const mergeOrdered = <T>(array1: T[], array2: T[], comparator: (a: T, b: T) => number): T[] => {\n return mergeOrIntersect(array1, array2, comparator, true);\n};\n\nexport const DEFAULT_COMPARATOR = (a: string|number, b: string|number): -1|0|1 => {\n return a < b ? -1 : (a > b ? 1 : 0);\n};\n\n/**\n * Returns the index of the element closest to the needle that is equal to or\n * greater than it. Assumes that the provided array is sorted.\n *\n * If no element is found, the right bound is returned.\n *\n * Uses the provided comparator function to determine if two items are equal or\n * if one is greater than the other. If you are working with strings or\n * numbers, you can use ArrayUtilities.DEFAULT_COMPARATOR. Otherwise, you\n * should define one that takes the needle element and an element from the\n * array and returns a positive or negative number to indicate which is greater\n * than the other.\n *\n * When specified, |left| (inclusive) and |right| (exclusive) indices\n * define the search window.\n */\nexport function lowerBound<T>(\n array: Uint32Array|Int32Array, needle: T, comparator: (needle: T, b: number) => number, left?: number,\n right?: number): number;\nexport function lowerBound<S, T>(\n array: S[], needle: T, comparator: (needle: T, b: S) => number, left?: number, right?: number): number;\nexport function lowerBound<S, T>(\n array: readonly S[], needle: T, comparator: (needle: T, b: S) => number, left?: number, right?: number): number;\nexport function lowerBound<S, T, A extends S[]>(\n array: A, needle: T, comparator: (needle: T, b: S) => number, left?: number, right?: number): number {\n let l = left || 0;\n let r = right !== undefined ? right : array.length;\n while (l < r) {\n const m = (l + r) >> 1;\n if (comparator(needle, array[m]) > 0) {\n l = m + 1;\n } else {\n r = m;\n }\n }\n return r;\n}\n\n/**\n * Returns the index of the element closest to the needle that is greater than\n * it. Assumes that the provided array is sorted.\n *\n * If no element is found, the right bound is returned.\n *\n * Uses the provided comparator function to determine if two items are equal or\n * if one is greater than the other. If you are working with strings or\n * numbers, you can use ArrayUtilities.DEFAULT_COMPARATOR. Otherwise, you\n * should define one that takes the needle element and an element from the\n * array and returns a positive or negative number to indicate which is greater\n * than the other.\n *\n * When specified, |left| (inclusive) and |right| (exclusive) indices\n * define the search window.\n */\nexport function upperBound<T>(\n array: Uint32Array, needle: T, comparator: (needle: T, b: number) => number, left?: number, right?: number): number;\nexport function upperBound<S, T>(\n array: S[], needle: T, comparator: (needle: T, b: S) => number, left?: number, right?: number): number;\nexport function upperBound<S, T, A extends S[]>(\n array: A, needle: T, comparator: (needle: T, b: S) => number, left?: number, right?: number): number {\n let l = left || 0;\n let r = right !== undefined ? right : array.length;\n while (l < r) {\n const m = (l + r) >> 1;\n if (comparator(needle, array[m]) >= 0) {\n l = m + 1;\n } else {\n r = m;\n }\n }\n return r;\n}\n\nconst enum NearestSearchStart {\n BEGINNING = 'BEGINNING',\n END = 'END',\n}\n/**\n * Obtains the first or last item in the array that satisfies the predicate function.\n * So, for example, if the array were arr = [2, 4, 6, 8, 10], and you are looking for\n * the last item arr[i] such that arr[i] < 5 you would be returned 1, because\n * array[1] is 4, the last item in the array that satisfies the\n * predicate function.\n *\n * If instead you were looking for the first item in the same array that satisfies\n * arr[i] > 5 you would be returned 2 because array[2] = 6.\n *\n * Please note: this presupposes that the array is already ordered.\n */\nfunction nearestIndex<T>(\n arr: readonly T[], predicate: (arrayItem: T) => boolean, searchStart: NearestSearchStart): number|null {\n const searchFromEnd = searchStart === NearestSearchStart.END;\n if (arr.length === 0) {\n return null;\n }\n\n let left = 0;\n let right = arr.length - 1;\n let pivot = 0;\n let matchesPredicate = false;\n let moveToTheRight = false;\n let middle = 0;\n do {\n middle = left + (right - left) / 2;\n pivot = searchFromEnd ? Math.ceil(middle) : Math.floor(middle);\n matchesPredicate = predicate(arr[pivot]);\n moveToTheRight = matchesPredicate === searchFromEnd;\n if (moveToTheRight) {\n left = Math.min(right, pivot + (left === pivot ? 1 : 0));\n } else {\n right = Math.max(left, pivot + (right === pivot ? -1 : 0));\n }\n } while (right !== left);\n\n // Special-case: the indexed item doesn't pass the predicate. This\n // occurs when none of the items in the array are a match for the\n // predicate.\n if (!predicate(arr[left])) {\n return null;\n }\n return left;\n}\n\n/**\n * Obtains the first item in the array that satisfies the predicate function.\n * So, for example, if the array was arr = [2, 4, 6, 8, 10], and you are looking for\n * the first item arr[i] such that arr[i] > 5 you would be returned 2, because\n * array[2] is 6, the first item in the array that satisfies the\n * predicate function.\n *\n * Please note: this presupposes that the array is already ordered.\n */\nexport function nearestIndexFromBeginning<T>(arr: T[], predicate: (arrayItem: T) => boolean): number|null {\n return nearestIndex(arr, predicate, NearestSearchStart.BEGINNING);\n}\n\n/**\n * Obtains the last item in the array that satisfies the predicate function.\n * So, for example, if the array was arr = [2, 4, 6, 8, 10], and you are looking for\n * the last item arr[i] such that arr[i] < 5 you would be returned 1, because\n * arr[1] is 4, the last item in the array that satisfies the\n * predicate function.\n *\n * Please note: this presupposes that the array is already ordered.\n */\n\nexport function nearestIndexFromEnd<T>(arr: readonly T[], predicate: (arrayItem: T) => boolean): number|null {\n return nearestIndex(arr, predicate, NearestSearchStart.END);\n}\n\n// Type guard for ensuring that `arr` does not contain null or undefined\nexport function arrayDoesNotContainNullOrUndefined<T>(arr: (T|null|undefined)[]): arr is T[] {\n return !arr.includes(null) && !arr.includes(undefined);\n}\n"]}