@newrelic/browser-agent 1.321.0-rc.7 → 1.321.0-rc.9
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.
- package/dist/cjs/common/constants/env.cdn.js +1 -1
- package/dist/cjs/common/constants/env.npm.js +1 -1
- package/dist/cjs/common/util/console.js +1 -0
- package/dist/cjs/common/v2/manifest.js +142 -0
- package/dist/cjs/common/v2/script-tracker-types.js +27 -0
- package/dist/cjs/common/v2/script-tracker.js +223 -25
- package/dist/cjs/common/v2/utils.js +47 -1
- package/dist/cjs/features/generic_events/aggregate/index.js +28 -1
- package/dist/cjs/loaders/api/register-api-types.js +13 -4
- package/dist/cjs/loaders/api/register.js +18 -0
- package/dist/esm/common/constants/env.cdn.js +1 -1
- package/dist/esm/common/constants/env.npm.js +1 -1
- package/dist/esm/common/util/console.js +1 -0
- package/dist/esm/common/v2/manifest.js +136 -0
- package/dist/esm/common/v2/script-tracker-types.js +24 -0
- package/dist/esm/common/v2/script-tracker.js +222 -26
- package/dist/esm/common/v2/utils.js +46 -1
- package/dist/esm/features/generic_events/aggregate/index.js +29 -2
- package/dist/esm/loaders/api/register-api-types.js +14 -4
- package/dist/esm/loaders/api/register.js +18 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/common/config/init-types.d.ts +1 -1
- package/dist/types/common/util/console.d.ts +1 -0
- package/dist/types/common/util/console.d.ts.map +1 -1
- package/dist/types/common/v2/manifest.d.ts +66 -0
- package/dist/types/common/v2/manifest.d.ts.map +1 -0
- package/dist/types/common/v2/script-tracker-types.d.ts +25 -0
- package/dist/types/common/v2/script-tracker-types.d.ts.map +1 -0
- package/dist/types/common/v2/script-tracker.d.ts +25 -4
- package/dist/types/common/v2/script-tracker.d.ts.map +1 -1
- package/dist/types/common/v2/utils.d.ts +12 -0
- package/dist/types/common/v2/utils.d.ts.map +1 -1
- package/dist/types/features/generic_events/aggregate/index.d.ts.map +1 -1
- package/dist/types/loaders/api/register-api-types.d.ts +31 -4
- package/dist/types/loaders/api/register-api-types.d.ts.map +1 -1
- package/dist/types/loaders/api/register.d.ts +1 -0
- package/dist/types/loaders/api/register.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/common/util/console.js +1 -0
- package/src/common/v2/manifest.js +126 -0
- package/src/common/v2/script-tracker-types.js +24 -0
- package/src/common/v2/script-tracker.js +218 -26
- package/src/common/v2/utils.js +42 -1
- package/src/features/generic_events/aggregate/index.js +22 -2
- package/src/loaders/api/register-api-types.js +14 -4
- package/src/loaders/api/register.js +16 -1
|
@@ -21,6 +21,9 @@ exports.default = void 0;
|
|
|
21
21
|
* @property {(value: string | null, resetSession?: boolean) => void} setUserId - Add an enduser.id attribute to all outgoing API data for the registered entity. Note: a registered entity will not be able to initiate a session reset. It must be done from the main agent.
|
|
22
22
|
* @property {RegisterAPIMetadata} metadata - The metadata object containing the custom attributes and target information for the registered entity.
|
|
23
23
|
*/
|
|
24
|
+
/**
|
|
25
|
+
* @typedef {import('../../common/v2/manifest').AssetFile} AssetFile
|
|
26
|
+
*/
|
|
24
27
|
/**
|
|
25
28
|
* @typedef {Object} RegisterAPIConstructor
|
|
26
29
|
* @property {string} id - The unique id for the registered entity. This will be assigned to any synthesized entities.
|
|
@@ -28,6 +31,8 @@ exports.default = void 0;
|
|
|
28
31
|
* @property {{[key: string]: any}} [tags] - The tags for the registered entity as key-value pairs. This will be assigned to any synthesized entities. Tags are converted to source.* attributes (e.g., {environment: 'production'} becomes source.environment: 'production').
|
|
29
32
|
* @property {RegisterAPITarget} [parent] - The parent target for the registered entity. If none was supplied, it will assume the entity guid from the main agent.
|
|
30
33
|
* @property {string} [parentId] - The parentId for the registered entity. If none was supplied, it will assume the entity guid from the main agent.
|
|
34
|
+
* @property {{assets?: Array<AssetFile>}} [manifest] - An optional manifest describing the MFE's known assets (scripts, stylesheets, images, fonts, etc.) as `AssetFile` entries, used to improve the accuracy of event attribution (errors, logs, ajax, websockets), attribute `BrowserPerformance` resource events (any asset type, not just scripts) and, depending on `timingMethod`, MicroFrontEndTiming values. Each `AssetFile`'s script-capability is inferred from a `.js` suffix on a string `matcher` (a RegExp `matcher` is never inferred as a script), unless overridden via `type: 'script'` or explicitly disabled via `type: 'asset'`. An `AssetFile` with an invalid `matcher` or an unrecognized `type` is discarded/ignored (with a console warning) rather than applied. If omitted, the agent falls back to its existing behavior of only evaluating the script that called `register()` (resource attribution still applies to that script).
|
|
35
|
+
* @property {'entry'|'scripts'|'all'} [timingMethod] - Controls which manifest assets are used to calculate MicroFrontEndTiming values: 'entry' (the default) leaves timing based entirely on the script that called `register()`, unaffected by the manifest; 'scripts' widens the timing window across all script assets; 'all' widens it across every asset.
|
|
31
36
|
*/
|
|
32
37
|
/**
|
|
33
38
|
* @typedef {Object} RegisterAPIMetadata
|
|
@@ -41,17 +46,21 @@ exports.default = void 0;
|
|
|
41
46
|
* @property {string} name - The name returned for the registered entity.
|
|
42
47
|
* @property {{[key: string]: any}} [tags] - The tags for the registered entity as key-value pairs.
|
|
43
48
|
* @property {string} [parentId] - The parentId for the registered entity. If none was supplied, it will assume the entity guid from the main agent.
|
|
49
|
+
* @property {import('../../common/v2/manifest').ParsedManifest} [manifest] - The parsed manifest for the registered entity, if one was supplied.
|
|
50
|
+
* @property {'entry'|'scripts'|'all'} [timingMethod] - The timing method supplied for the registered entity, if any.
|
|
44
51
|
*/
|
|
45
52
|
/**
|
|
46
53
|
* @typedef {Object} RegisterAPITimings
|
|
47
54
|
* @property {number} registeredAt - The timestamp when the registered entity was created.
|
|
48
55
|
* @property {number} [reportedAt] - The timestamp when the registered entity was deregistered.
|
|
49
|
-
* @property {number} fetchStart - The timestamp when the registered entity began fetching (performance.start).
|
|
50
|
-
* @property {number} fetchEnd - The timestamp when the registered entity finished fetching (performance.end).
|
|
51
|
-
* @property {number} scriptStart - The timestamp when script initialization began (max of dom.start or performance.end, or performance.end if no dom.start).
|
|
52
|
-
* @property {number} scriptEnd - The timestamp when script loading completed (dom.end or registeredAt if no dom.end).
|
|
56
|
+
* @property {number} fetchStart - The timestamp when the registered entity began fetching (performance.start). When a manifest with timingMethod 'scripts'|'all' is supplied, this widens to the earliest fetchStart across all matched manifest assets.
|
|
57
|
+
* @property {number} fetchEnd - The timestamp when the registered entity finished fetching (performance.end). When a manifest with timingMethod 'scripts'|'all' is supplied, this widens to the latest fetchEnd across all matched manifest assets.
|
|
58
|
+
* @property {number} scriptStart - The timestamp when script initialization began (max of dom.start or performance.end, or performance.end if no dom.start). When a manifest with timingMethod 'scripts'|'all' is supplied, this widens to the earliest scriptStart across all matched manifest script assets (non-script assets are excluded).
|
|
59
|
+
* @property {number} scriptEnd - The timestamp when script loading completed (dom.end or registeredAt if no dom.end). When a manifest with timingMethod 'scripts'|'all' is supplied, this widens to the latest scriptEnd across all matched manifest script assets (non-script assets are excluded).
|
|
53
60
|
* @property {Object} [asset] - The asset path (if found) for the registered entity.
|
|
54
61
|
* @property {string} type - The type of timing associated with the registered entity, 'script' or 'link' if found with the performance resource API, 'fetch' for dynamic imports, 'inline' if found to be associated with the root document URL, or 'unknown' if no associated resource could be found.
|
|
62
|
+
* @property {number} totalWeight - The sum of `transferSize` (bytes) across every asset detected for the registered entity -- the entry script, plus, when a manifest is supplied, every matched manifest asset (script or non-script). Unlike fetchStart/fetchEnd/scriptStart/scriptEnd above, this is never gated behind `timingMethod` -- manifest assets contribute their bytes even at the 'entry' default/unset. Cross-origin assets without a Timing-Allow-Origin header report 0 bytes per the Resource Timing spec.
|
|
63
|
+
* @property {boolean} [renderBlocking] - True if any detected asset (entry script or matched manifest asset) has a `renderBlockingStatus` of 'blocking'; false if none were 'blocking' but at least one reported 'non-blocking'; left `undefined` if no detected asset reported the attribute at all (e.g. unsupported browser). A single 'blocking' asset always wins over any number of 'non-blocking' ones, regardless of resolution order.
|
|
55
64
|
*/
|
|
56
65
|
/**
|
|
57
66
|
* @typedef {Object} RegisterAPIVitals
|
|
@@ -23,12 +23,15 @@ var _pageVisibility = require("../../common/window/page-visibility");
|
|
|
23
23
|
var _scriptTracker = require("../../common/v2/script-tracker");
|
|
24
24
|
var _mfeVitals = require("../../common/v2/mfe-vitals");
|
|
25
25
|
var _uniqueId = require("../../common/ids/unique-id");
|
|
26
|
+
var _manifest = require("../../common/v2/manifest");
|
|
26
27
|
var _cleanUrl = require("../../common/url/clean-url");
|
|
27
28
|
/**
|
|
28
29
|
* Copyright 2020-2026 New Relic, Inc. All rights reserved.
|
|
29
30
|
* SPDX-License-Identifier: Apache-2.0
|
|
30
31
|
*/
|
|
31
32
|
|
|
33
|
+
const TIMING_METHODS = ['entry', 'scripts', 'all'];
|
|
34
|
+
|
|
32
35
|
/**
|
|
33
36
|
* @typedef {import('./register-api-types').RegisterAPI} RegisterAPI
|
|
34
37
|
*/
|
|
@@ -50,6 +53,7 @@ const warnings = exports.warnings = {
|
|
|
50
53
|
disabled: (0, _invoke.single)(() => (0, _console.warn)(55)),
|
|
51
54
|
invalidTarget: (0, _invoke.single)(target => (0, _console.warn)(48, target)),
|
|
52
55
|
deregistered: (0, _invoke.single)(() => (0, _console.warn)(68)),
|
|
56
|
+
invalidTimingMethod: (0, _invoke.single)(value => (0, _console.warn)(80, value)),
|
|
53
57
|
duplicateName: (0, _invoke.single)(target => (0, _console.warn)(81, target)),
|
|
54
58
|
duplicateId: (0, _invoke.single)(target => (0, _console.warn)(82, target))
|
|
55
59
|
};
|
|
@@ -87,9 +91,17 @@ function register(agentRef, target) {
|
|
|
87
91
|
// getter because this is asynchronously set
|
|
88
92
|
type: _constants.V2_TYPES.BA
|
|
89
93
|
};
|
|
94
|
+
target.manifest = (0, _manifest.parseManifest)(target.manifest);
|
|
95
|
+
if (target.timingMethod !== undefined && !TIMING_METHODS.includes(target.timingMethod)) {
|
|
96
|
+
warnings.invalidTimingMethod(target.timingMethod);
|
|
97
|
+
target.timingMethod = undefined;
|
|
98
|
+
}
|
|
90
99
|
|
|
91
100
|
// The script timings for this entity, which will be used to populate part of the MicroFrontEndTiming custom event.
|
|
92
101
|
const timings = (0, _scriptTracker.findScriptTimings)(target);
|
|
102
|
+
// Always applied when a manifest is present -- totalWeight/renderBlocking accumulate from manifest assets
|
|
103
|
+
// regardless of timingMethod; actual timing widening inside stays gated to 'scripts'/'all' (see applyManifestTimings).
|
|
104
|
+
if (target.manifest) (0, _scriptTracker.applyManifestTimings)(timings, target);
|
|
93
105
|
|
|
94
106
|
// Track MFE vitals for this entity, which will be used to populate part of the MicroFrontEndTiming custom event.
|
|
95
107
|
const vitals = (0, _mfeVitals.trackMFEVitals)(target, timings);
|
|
@@ -263,6 +275,12 @@ function register(agentRef, target) {
|
|
|
263
275
|
// fetch time and script time together
|
|
264
276
|
timeToRegister: timings.registeredAt,
|
|
265
277
|
// timestamp when register() was called
|
|
278
|
+
totalWeight: timings.totalWeight,
|
|
279
|
+
// sum of transferSize bytes across every detected asset (entry script + matched manifest assets)
|
|
280
|
+
// renderBlocking: true if any detected asset was 'blocking', false if only 'non-blocking' assets were seen, omitted entirely if no detected asset reported the attribute at all
|
|
281
|
+
...(timings.renderBlocking !== undefined && {
|
|
282
|
+
renderBlocking: timings.renderBlocking
|
|
283
|
+
}),
|
|
266
284
|
// leave room to extend these with more data keys as needed
|
|
267
285
|
...(vitals.fcp.value >= 0 && {
|
|
268
286
|
'vitals.fcp.value': vitals.fcp.value
|
|
@@ -95,6 +95,7 @@ import { dispatchGlobalEvent } from '../dispatch/global-event';
|
|
|
95
95
|
* | 77 | Agent rejected post message, could not validate origin. |
|
|
96
96
|
* | 78 | RegisteredIframeEntity could not determine parent origin and will not register, to avoid trusting messages from any origin. |
|
|
97
97
|
* | 79 | Unable to initialize Connector and/or Harvester. |
|
|
98
|
+
* | 80 | An invalid manifest option was provided to register() and will be ignored. |
|
|
98
99
|
* | 81 | Entities were detected that share a name with different IDs - This can cause multiple entities to have the same name in New Relic. |
|
|
99
100
|
* | 82 | Entities were detected that share an ID with different names - This can cause your entity's name to change unexpectedly. |
|
|
100
101
|
*
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2020-2026 New Relic, Inc. All rights reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { cleanURL } from '../url/clean-url';
|
|
7
|
+
import { warn } from '../util/console';
|
|
8
|
+
import { single } from '../util/invoke';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @typedef {Object} AssetFile
|
|
12
|
+
* @property {string|RegExp} matcher - the path/path-fragment string, or RegExp, used to match a resolved URL against this asset
|
|
13
|
+
* @property {'script'|'asset'} [type] - optional override for script-capability inference. When omitted, script-capability is inferred from a
|
|
14
|
+
* `.js` suffix on a string `matcher` (a RegExp `matcher` is never inferred as a script). Supply `type: 'script'` to explicitly flag an entry
|
|
15
|
+
* as a script regardless of its matcher shape/suffix (e.g. an extensionless URL, or a RegExp targeting a script path), or `type: 'asset'` to
|
|
16
|
+
* explicitly flag it as non-script. Any other value is invalid, logs a warning, and is ignored (falls back to inference).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Warns at most once per page for any invalid manifest entry (bad `matcher` or bad `type`) -- mirrors the
|
|
20
|
+
* existing `invalidTimingMethod` single()-wrapped warning pattern in register.js. */
|
|
21
|
+
const warnInvalidManifestEntry = single(secondary => warn(80, secondary));
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @typedef {Object} ParsedManifestAsset
|
|
25
|
+
* @property {string|RegExp} pattern - the original matcher supplied by the customer
|
|
26
|
+
* @property {(url: string) => boolean} test - precompiled matcher against a resolved URL
|
|
27
|
+
* @property {boolean} isScript
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @typedef {Object} ParsedManifest
|
|
32
|
+
* @property {ParsedManifestAsset[]} assets - all supplied assets
|
|
33
|
+
* @property {ParsedManifestAsset[]} scripts - the subset of assets inferred/declared as scripts (`.js`)
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Parses a raw manifest supplied to `register()` into precompiled matcher closures. Parsing happens once, at
|
|
38
|
+
* registration time, so downstream event attribution (which runs on every ajax/error/log/websocket event) never has
|
|
39
|
+
* to re-derive matching logic from the raw customer input.
|
|
40
|
+
* @param {{assets?: Array<AssetFile>}} [rawManifest]
|
|
41
|
+
* @returns {ParsedManifest|undefined} undefined if no usable assets were supplied, so callers can cheaply skip all manifest logic
|
|
42
|
+
*/
|
|
43
|
+
export function parseManifest(rawManifest) {
|
|
44
|
+
if (!Array.isArray(rawManifest?.assets) || !rawManifest.assets.length) return undefined;
|
|
45
|
+
const assets = rawManifest.assets.map(parseAsset).filter(Boolean);
|
|
46
|
+
if (!assets.length) return undefined;
|
|
47
|
+
return {
|
|
48
|
+
assets,
|
|
49
|
+
scripts: assets.filter(asset => asset.isScript)
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @param {AssetFile} entry
|
|
55
|
+
* @returns {ParsedManifestAsset|undefined}
|
|
56
|
+
*/
|
|
57
|
+
function parseAsset(entry) {
|
|
58
|
+
if (!entry || typeof entry !== 'object') return undefined;
|
|
59
|
+
const {
|
|
60
|
+
matcher,
|
|
61
|
+
type
|
|
62
|
+
} = entry;
|
|
63
|
+
const inferredIsScript = typeof matcher === 'string' && isScriptPath(matcher);
|
|
64
|
+
let isScript = inferredIsScript;
|
|
65
|
+
if (type !== undefined) {
|
|
66
|
+
if (isValidType(type)) {
|
|
67
|
+
isScript = isScriptType(type);
|
|
68
|
+
} else {
|
|
69
|
+
// Invalid `type` never overrides -- fall back to inference-only behavior rather than forcing `isScript: false`,
|
|
70
|
+
// so a typo'd `type` can't silently break stack-trace attribution for an otherwise-valid `.js` matcher.
|
|
71
|
+
warnInvalidManifestEntry(type);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (isRegExp(matcher)) {
|
|
75
|
+
// Reset lastIndex before every test -- a `g`/`y` flagged matcher otherwise carries state across calls
|
|
76
|
+
// (this closure is reused for every event), causing intermittent, input-order-dependent match failures.
|
|
77
|
+
return {
|
|
78
|
+
pattern: matcher,
|
|
79
|
+
test: url => {
|
|
80
|
+
matcher.lastIndex = 0;
|
|
81
|
+
return matcher.test(cleanURL(url));
|
|
82
|
+
},
|
|
83
|
+
isScript
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
if (typeof matcher === 'string' && matcher.length > 0) {
|
|
87
|
+
return {
|
|
88
|
+
pattern: matcher,
|
|
89
|
+
test: url => cleanURL(url).includes(matcher),
|
|
90
|
+
isScript
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Every other matcher shape (missing, empty string, null, number, plain object, ...) is invalid -- notably an
|
|
95
|
+
// empty string must be rejected here rather than falling through to the string branch above, since
|
|
96
|
+
// ''.includes('') is always true and would otherwise silently match every URL.
|
|
97
|
+
warnInvalidManifestEntry(matcher);
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
function isScriptPath(path) {
|
|
101
|
+
return path.endsWith('.js');
|
|
102
|
+
}
|
|
103
|
+
function isValidType(type) {
|
|
104
|
+
return type === 'script' || type === 'asset';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Cross-realm-safe check for whether a value is a RegExp. `instanceof RegExp` only returns true when the value's
|
|
109
|
+
* prototype chain links to THIS realm's `RegExp.prototype` -- a regex literal constructed in a different realm
|
|
110
|
+
* (an iframe, a Worker via structured clone, a WebDriver sandbox such as Firefox's geckodriver executeScript
|
|
111
|
+
* context) is still a genuine RegExp, just not an instance of this realm's constructor, and would otherwise be
|
|
112
|
+
* silently dropped by parseAsset below.
|
|
113
|
+
* @param {*} value
|
|
114
|
+
* @returns {boolean}
|
|
115
|
+
*/
|
|
116
|
+
function isRegExp(value) {
|
|
117
|
+
return Object.prototype.toString.call(value) === '[object RegExp]';
|
|
118
|
+
}
|
|
119
|
+
function isScriptType(type) {
|
|
120
|
+
return type === 'script';
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Determines whether a resolved URL matches any asset in a parsed manifest.
|
|
125
|
+
* @param {ParsedManifest|undefined} parsed
|
|
126
|
+
* @param {string} url
|
|
127
|
+
* @param {{scriptsOnly?: boolean}} [options]
|
|
128
|
+
* @returns {boolean}
|
|
129
|
+
*/
|
|
130
|
+
export function matchManifestAsset(parsed, url, {
|
|
131
|
+
scriptsOnly = false
|
|
132
|
+
} = {}) {
|
|
133
|
+
if (!parsed || !url) return false;
|
|
134
|
+
const candidates = scriptsOnly ? parsed.scripts : parsed.assets;
|
|
135
|
+
return candidates.some(asset => asset.test(url));
|
|
136
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2020-2026 New Relic, Inc. All rights reserved.
|
|
3
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {(start: number, end: number) => void} RecordManifestScriptWindowFn - Widens the live scriptStart/
|
|
8
|
+
* scriptEnd window with one manifest script asset's DOM correlation timing. `start`/`end` are that asset's
|
|
9
|
+
* `correlation.script.start`/`.end`, or falsy if not yet resolved. See `findScriptTimings`, which registers the
|
|
10
|
+
* concrete implementation, for the exact widening semantics (never shrinks either bound).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @typedef {Object} TimingsInternals
|
|
15
|
+
* @property {Set<string>} weighedAssetUrls - Always present (seeded by `getOrCreateInternals`, see
|
|
16
|
+
* `script-tracker.js`). Cleaned URLs already folded into `timings.totalWeight`/`timings.renderBlocking` by
|
|
17
|
+
* `applyResourceWeight`, so the same underlying resource (e.g. a manifest asset that's also the .register calling
|
|
18
|
+
* script itself) is never counted twice.
|
|
19
|
+
* @property {RecordManifestScriptWindowFn} recordManifestScriptWindow - Always present (seeded by
|
|
20
|
+
* `getOrCreateInternals`, see `script-tracker.js`). `findScriptTimings` overrides the seeded default with one that
|
|
21
|
+
* folds into the live `scriptStart`/`scriptEnd` getters instead.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export default {};
|
|
@@ -12,8 +12,10 @@ import { CORRELATION_STALE_THRESHOLD_MS } from './script-tracker-constants';
|
|
|
12
12
|
import { timingFactory } from './timing-factory';
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
|
-
* @typedef {import('
|
|
15
|
+
* @typedef {import('../../loaders/api/register-api-types').RegisterAPITimings} RegisterAPITimings
|
|
16
16
|
* @typedef {import('../../loaders/api/register-api-types').RegisterAPITarget} RegisterAPITarget
|
|
17
|
+
* @typedef {import('./script-tracker-types').RecordManifestScriptWindowFn} RecordManifestScriptWindowFn
|
|
18
|
+
* @typedef {import('./script-tracker-types').TimingsInternals} TimingsInternals
|
|
17
19
|
*/
|
|
18
20
|
|
|
19
21
|
/** export for testing purposes */
|
|
@@ -33,11 +35,43 @@ export const scriptCorrelations = new Map();
|
|
|
33
35
|
let poSubscribers = [];
|
|
34
36
|
|
|
35
37
|
/**
|
|
36
|
-
*
|
|
38
|
+
* Bookkeeping keyed by a `timings` object, kept off the object itself since it's exposed directly to customers via
|
|
39
|
+
* `register().metadata.timings`.
|
|
40
|
+
* @type {WeakMap<RegisterAPITimings, TimingsInternals>}
|
|
41
|
+
*/
|
|
42
|
+
const timingsInternals = new WeakMap();
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Gets (or lazily creates) the bookkeeping record for a `timings` object. A fresh record's `recordManifestScriptWindow`
|
|
46
|
+
* defaults to widening `timings.scriptStart`/`scriptEnd` directly -- correct for a plain `timings` object never
|
|
47
|
+
* produced by `findScriptTimings`. `findScriptTimings` overrides that default with one that folds into its live
|
|
48
|
+
* getters instead.
|
|
49
|
+
* @param {RegisterAPITimings} timings
|
|
50
|
+
* @returns {TimingsInternals}
|
|
51
|
+
*/
|
|
52
|
+
function getOrCreateInternals(timings) {
|
|
53
|
+
let internals = timingsInternals.get(timings);
|
|
54
|
+
if (!internals) {
|
|
55
|
+
internals = {
|
|
56
|
+
weighedAssetUrls: new Set(),
|
|
57
|
+
recordManifestScriptWindow: (start, end) => {
|
|
58
|
+
if (start) timings.scriptStart = timings.scriptStart > 0 ? Math.min(timings.scriptStart, start) : start;
|
|
59
|
+
if (end) timings.scriptEnd = timings.scriptEnd > 0 ? Math.max(timings.scriptEnd, end) : end;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
timingsInternals.set(timings, internals);
|
|
63
|
+
}
|
|
64
|
+
return internals;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Retrieves a script correlation by URL using exact matching. Exported so other features (e.g. generic_events'
|
|
69
|
+
* resource attribution) can key off the same DOM node/load-timing tracking this module already does for every
|
|
70
|
+
* `<script>` element, rather than setting up a second, redundant observer.
|
|
37
71
|
* @param {string} targetUrl - The URL to find
|
|
38
72
|
* @returns {ScriptCorrelation | undefined} - The correlation object if found
|
|
39
73
|
*/
|
|
40
|
-
function findCorrelation(targetUrl) {
|
|
74
|
+
export function findCorrelation(targetUrl) {
|
|
41
75
|
return scriptCorrelations.get(targetUrl);
|
|
42
76
|
}
|
|
43
77
|
|
|
@@ -86,20 +120,23 @@ if (globalScope.MutationObserver && globalScope.document) {
|
|
|
86
120
|
});
|
|
87
121
|
}
|
|
88
122
|
if (globalScope.PerformanceObserver?.supportedEntryTypes.includes('resource')) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
* after the buffer fills up we won't be able to get the script timing information from the resource timing API
|
|
92
|
-
*/
|
|
123
|
+
// Tracked via an observer (not a later buffer read) because the performance buffer stops accepting new entries
|
|
124
|
+
// once full, instead of dropping old ones -- a late register() call could otherwise miss timing entirely.
|
|
93
125
|
const scriptObserver = new PerformanceObserver(list => {
|
|
94
|
-
list.getEntries().
|
|
95
|
-
//
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
126
|
+
list.getEntries().forEach(entry => {
|
|
127
|
+
// Correlation bookkeeping only makes sense for script-like entries -- gated on validEntryCriteria so
|
|
128
|
+
// scriptCorrelations doesn't grow for every image/css/font load on the page.
|
|
129
|
+
if (validEntryCriteria(entry)) {
|
|
130
|
+
const entryUrl = cleanURL(entry.name);
|
|
131
|
+
const correlation = getOrCreateCorrelation(entryUrl);
|
|
132
|
+
correlation.performance.start = Math.floor(entry.startTime);
|
|
133
|
+
correlation.performance.end = Math.floor(entry.responseEnd);
|
|
134
|
+
correlation.performance.value = entry;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Late-resolution subscribers can be for any asset type (not just scripts), so every entry is checked here,
|
|
138
|
+
// unfiltered. Skipped when nothing is pending, the common case.
|
|
139
|
+
if (!poSubscribers.length) return;
|
|
103
140
|
const canClear = [];
|
|
104
141
|
poSubscribers.forEach(({
|
|
105
142
|
test,
|
|
@@ -198,6 +235,33 @@ function applyPerformanceEntry(timings, entry) {
|
|
|
198
235
|
timings.fetchEnd = Math.floor(entry.responseEnd);
|
|
199
236
|
timings.asset = entry.name;
|
|
200
237
|
timings.type = entry.initiatorType;
|
|
238
|
+
applyResourceWeight(timings, entry);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Accumulates the byte weight and render-blocking status of a single detected asset (the entry script or a resolved
|
|
243
|
+
* manifest asset) into a timings object. Shared by both the entry-script path (`applyPerformanceEntry`) and the
|
|
244
|
+
* manifest path (`applyManifestEntry`) so `totalWeight`/`renderBlocking` reflect every asset actually detected,
|
|
245
|
+
* regardless of which path found it.
|
|
246
|
+
* @param {RegisterAPITimings} timings
|
|
247
|
+
* @param {PerformanceResourceTiming} entry
|
|
248
|
+
*/
|
|
249
|
+
function applyResourceWeight(timings, entry) {
|
|
250
|
+
// De-dupe by cleaned URL: a manifest can list the .register calling script itself as one of its own assets,
|
|
251
|
+
// which would otherwise weigh the same resource twice (once via findScriptTimings, once via applyManifestTimings).
|
|
252
|
+
const url = cleanURL(entry.name);
|
|
253
|
+
const {
|
|
254
|
+
weighedAssetUrls
|
|
255
|
+
} = getOrCreateInternals(timings);
|
|
256
|
+
if (weighedAssetUrls.has(url)) return;
|
|
257
|
+
weighedAssetUrls.add(url);
|
|
258
|
+
|
|
259
|
+
// transferSize is 0 for cross-origin responses without Timing-Allow-Origin (a privacy restriction, not a
|
|
260
|
+
// zero-byte asset) -- adding 0 is correct either way.
|
|
261
|
+
timings.totalWeight = (timings.totalWeight || 0) + (entry.transferSize || 0);
|
|
262
|
+
// 'blocking' always wins and never gets downgraded; 'non-blocking' only applies if nothing already resolved
|
|
263
|
+
// true; no value at all (unsupported browser) leaves renderBlocking untouched (stays `undefined`).
|
|
264
|
+
if (entry.renderBlockingStatus === 'blocking') timings.renderBlocking = true;else if (entry.renderBlockingStatus === 'non-blocking' && timings.renderBlocking !== true) timings.renderBlocking = false;
|
|
201
265
|
}
|
|
202
266
|
|
|
203
267
|
/**
|
|
@@ -220,8 +284,114 @@ function subscribeToLatePerformanceEntry(timings, mfeScriptUrl) {
|
|
|
220
284
|
}
|
|
221
285
|
|
|
222
286
|
/**
|
|
223
|
-
*
|
|
224
|
-
*
|
|
287
|
+
* Applies one manifest asset's performance entry to a timings object: weight/renderBlocking always accumulate;
|
|
288
|
+
* fetchStart/fetchEnd and scriptStart/scriptEnd widen (never shrink) only when `timingMethod` calls for it; asset/
|
|
289
|
+
* type get anchored to the first script asset seen to resolve.
|
|
290
|
+
* @param {RegisterAPITimings} timings
|
|
291
|
+
* @param {PerformanceResourceTiming} entry
|
|
292
|
+
* @param {import('./manifest').ParsedManifestAsset} asset - the manifest asset this entry resolved
|
|
293
|
+
* @param {{ resolved: boolean }} entryState - shared "first script asset wins" guard for a single `applyManifestTimings` call
|
|
294
|
+
* @param {'entry'|'scripts'|'all'} [timingMethod] - the registered MFE's timing method; `undefined`/'entry' means weight/render-blocking still accumulate, but no timing widening happens at all
|
|
295
|
+
*/
|
|
296
|
+
function applyManifestEntry(timings, entry, asset, entryState, timingMethod) {
|
|
297
|
+
// Weight isn't a timing concern, so it accumulates for every matched asset regardless of timingMethod.
|
|
298
|
+
applyResourceWeight(timings, entry);
|
|
299
|
+
if (timingMethod !== 'scripts' && timingMethod !== 'all') return; // no timing-widening effect at the 'entry' default/unset
|
|
300
|
+
|
|
301
|
+
const widensAllAssets = timingMethod === 'all';
|
|
302
|
+
// Under 'scripts', only script assets widen the fetch window; under 'all', every matched asset does.
|
|
303
|
+
if (widensAllAssets || asset.isScript) {
|
|
304
|
+
const start = Math.floor(entry.startTime);
|
|
305
|
+
const end = Math.floor(entry.responseEnd);
|
|
306
|
+
// fetchStart/fetchEnd default to 0 ("not yet found") -- only fold into the min/max once they're positive,
|
|
307
|
+
// or 0 would permanently win Math.min.
|
|
308
|
+
timings.fetchStart = timings.fetchStart > 0 ? Math.min(timings.fetchStart, start) : start;
|
|
309
|
+
timings.fetchEnd = timings.fetchEnd > 0 ? Math.max(timings.fetchEnd, end) : end;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// Non-script assets never execute, so only script assets widen the execution window or anchor asset/type.
|
|
313
|
+
if (asset.isScript) {
|
|
314
|
+
const correlation = findCorrelation(cleanURL(entry.name));
|
|
315
|
+
if (correlation) {
|
|
316
|
+
// Widens the aggregate scriptStart/scriptEnd window with this asset's current correlation timing. Re-called
|
|
317
|
+
// as a 'load'/'error' listener below if its DOM completion hasn't fired yet, so a later, larger end still counts.
|
|
318
|
+
const widenScriptWindowForAsset = () => {
|
|
319
|
+
const {
|
|
320
|
+
start: scriptStart,
|
|
321
|
+
end: scriptEnd
|
|
322
|
+
} = correlation.script;
|
|
323
|
+
getOrCreateInternals(timings).recordManifestScriptWindow(scriptStart, scriptEnd);
|
|
324
|
+
};
|
|
325
|
+
widenScriptWindowForAsset();
|
|
326
|
+
if (!correlation.dom.end && correlation.dom.value) {
|
|
327
|
+
;
|
|
328
|
+
['load', 'error'].forEach(eventType => correlation.dom.value.addEventListener(eventType, widenScriptWindowForAsset, {
|
|
329
|
+
once: true
|
|
330
|
+
}));
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (!entryState.resolved) {
|
|
334
|
+
timings.asset = entry.name;
|
|
335
|
+
timings.type = entry.initiatorType;
|
|
336
|
+
entryState.resolved = true;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Subscribes to late resource timing emissions for manifest assets not yet resolved against the buffered entries.
|
|
343
|
+
* Reuses the shared page-wide scriptObserver/poSubscribers mechanism (one PerformanceObserver for all MFEs, not
|
|
344
|
+
* one per MFE) and, unlike that observer's own correlation bookkeeping, checks every resource entry -- not just
|
|
345
|
+
* script-like ones -- so lazy-loaded images/fonts/stylesheets resolve too.
|
|
346
|
+
* @param {RegisterAPITimings} timings
|
|
347
|
+
* @param {Set<import('./manifest').ParsedManifestAsset>} pending - manifest assets still unresolved
|
|
348
|
+
* @param {{ resolved: boolean }} entryState - shared "first script asset wins" guard for a single `applyManifestTimings` call
|
|
349
|
+
* @param {'entry'|'scripts'|'all'} [timingMethod] - forwarded to `applyManifestEntry` for each late-resolving asset
|
|
350
|
+
*/
|
|
351
|
+
function subscribeToLateManifestEntries(timings, pending, entryState, timingMethod) {
|
|
352
|
+
if (!globalScope.PerformanceObserver?.supportedEntryTypes?.includes('resource')) return;
|
|
353
|
+
poSubscribers.push({
|
|
354
|
+
addedAt: now(),
|
|
355
|
+
test: entry => {
|
|
356
|
+
const matched = [...pending].find(asset => asset.test(entry.name));
|
|
357
|
+
if (matched) {
|
|
358
|
+
applyManifestEntry(timings, entry, matched, entryState, timingMethod);
|
|
359
|
+
pending.delete(matched);
|
|
360
|
+
}
|
|
361
|
+
return pending.size === 0;
|
|
362
|
+
}
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Applies a registered MFE's manifest to a timings object (already populated by `findScriptTimings`). No-op if no
|
|
368
|
+
* manifest is present. Weight/renderBlocking always accumulate from every detected manifest asset; timing widening
|
|
369
|
+
* (fetchStart/fetchEnd/scriptStart/scriptEnd/asset anchor) is opt-in via `timingMethod` -- see `applyManifestEntry`.
|
|
370
|
+
* @param {RegisterAPITimings} timings - the timings object to widen in place
|
|
371
|
+
* @param {RegisterAPITarget} target - the registered MFE target, which may carry a parsed `manifest`
|
|
372
|
+
*/
|
|
373
|
+
export function applyManifestTimings(timings, target) {
|
|
374
|
+
const parsedManifest = target?.manifest;
|
|
375
|
+
if (!parsedManifest || !parsedManifest.assets.length) return;
|
|
376
|
+
const entryState = {
|
|
377
|
+
resolved: false
|
|
378
|
+
};
|
|
379
|
+
const pending = new Set(parsedManifest.assets);
|
|
380
|
+
const resourceEntries = globalScope.performance?.getEntriesByType('resource') || [];
|
|
381
|
+
resourceEntries.forEach(entry => {
|
|
382
|
+
const matched = [...pending].find(asset => asset.test(entry.name));
|
|
383
|
+
if (matched) {
|
|
384
|
+
applyManifestEntry(timings, entry, matched, entryState, target.timingMethod);
|
|
385
|
+
pending.delete(matched);
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
if (pending.size) subscribeToLateManifestEntries(timings, pending, entryState, target.timingMethod);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Uses the initiator function's stack to find script timing information via the resource timing API.
|
|
393
|
+
* @param {RegisterAPITarget} [target] - the MFE target being registered; its id scopes stale-correlation
|
|
394
|
+
* detection per-MFE rather than per-script-URL (see isCorrelationStale below)
|
|
225
395
|
* @returns {RegisterAPITimings} Object containing script fetch start and end times, and the asset URL if found
|
|
226
396
|
*/
|
|
227
397
|
export function findScriptTimings(target) {
|
|
@@ -234,7 +404,9 @@ export function findScriptTimings(target) {
|
|
|
234
404
|
scriptStart: 0,
|
|
235
405
|
scriptEnd: 0,
|
|
236
406
|
asset: undefined,
|
|
237
|
-
type: 'unknown'
|
|
407
|
+
type: 'unknown',
|
|
408
|
+
totalWeight: 0,
|
|
409
|
+
renderBlocking: undefined
|
|
238
410
|
};
|
|
239
411
|
const stack = getDeepStackTrace();
|
|
240
412
|
if (!stack) return timings;
|
|
@@ -271,9 +443,8 @@ export function findScriptTimings(target) {
|
|
|
271
443
|
}
|
|
272
444
|
|
|
273
445
|
// A correlation can be reused across multiple `register()` calls for the same script URL (e.g. an SPA
|
|
274
|
-
// remounting the same MFE without the script
|
|
275
|
-
//
|
|
276
|
-
// below can ignore the stale data instead of reporting it as if it were fresh.
|
|
446
|
+
// remounting the same MFE without the script reloading) -- its dom/performance timings would then describe
|
|
447
|
+
// the *original* load. Detect that so scriptStart/scriptEnd below can ignore the stale data.
|
|
277
448
|
const correlation = timings.correlation;
|
|
278
449
|
const alreadyClaimedByThisMFE = !!mfeId && !!correlation?.claimedBy.has(mfeId);
|
|
279
450
|
if (correlation && mfeId) correlation.claimedBy.add(mfeId);
|
|
@@ -284,10 +455,35 @@ export function findScriptTimings(target) {
|
|
|
284
455
|
return staleness > CORRELATION_STALE_THRESHOLD_MS;
|
|
285
456
|
};
|
|
286
457
|
|
|
287
|
-
//
|
|
288
|
-
//
|
|
289
|
-
|
|
290
|
-
|
|
458
|
+
// Only reached for a real (non-inline), stack-attributable script -- scriptStart/scriptEnd become live getters
|
|
459
|
+
// below, so manifest widening needs a hook that composes with them instead of overriding them (see
|
|
460
|
+
// recordManifestScriptWindow's doc comment). Every other path keeps getOrCreateInternals' plain-value-widening
|
|
461
|
+
// default, which is already correct there.
|
|
462
|
+
let manifestScriptStart = 0;
|
|
463
|
+
let manifestScriptEnd = 0;
|
|
464
|
+
/**
|
|
465
|
+
* Widens the running manifestScriptStart/manifestScriptEnd accumulators with one asset's correlation timing.
|
|
466
|
+
* Never shrinks either bound; a falsy (unresolved) start/end is ignored.
|
|
467
|
+
* @type {RecordManifestScriptWindowFn}
|
|
468
|
+
*/
|
|
469
|
+
getOrCreateInternals(timings).recordManifestScriptWindow = (start, end) => {
|
|
470
|
+
if (start) manifestScriptStart = manifestScriptStart > 0 ? Math.min(manifestScriptStart, start) : start;
|
|
471
|
+
if (end) manifestScriptEnd = manifestScriptEnd > 0 ? Math.max(manifestScriptEnd, end) : end;
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
// Getters, since correlation data may still arrive after this function returns -- we want the freshest value
|
|
475
|
+
// at harvest time. Non-stale: fall back to fetchEnd (best approximation) if correlation isn't available yet.
|
|
476
|
+
// Stale: fall back to registeredAt, since fetchEnd would derive from the same stale correlation. Manifest
|
|
477
|
+
// widening is re-read on every access rather than baked in once, so it composes with a correlation that
|
|
478
|
+
// resolves later.
|
|
479
|
+
Object.defineProperty(timings, 'scriptStart', timingFactory(() => {
|
|
480
|
+
const ownStart = isCorrelationStale() ? timings.registeredAt : correlation?.script.start ?? timings.fetchEnd;
|
|
481
|
+
return manifestScriptStart > 0 ? Math.min(ownStart, manifestScriptStart) : ownStart;
|
|
482
|
+
}));
|
|
483
|
+
Object.defineProperty(timings, 'scriptEnd', timingFactory(() => {
|
|
484
|
+
const ownEnd = isCorrelationStale() ? timings.registeredAt : correlation?.script.end ?? timings.registeredAt;
|
|
485
|
+
return manifestScriptEnd > 0 ? Math.max(ownEnd, manifestScriptEnd) : ownEnd;
|
|
486
|
+
}));
|
|
291
487
|
} catch (error) {
|
|
292
488
|
// Don't let stack parsing errors break anything
|
|
293
489
|
}
|