diff --git a/README.md b/README.md index e6aefe9..8dbda83 100644 --- a/README.md +++ b/README.md @@ -37,8 +37,8 @@ You can set `window.paceOptions` before bringing in the file: ```javascript paceOptions = { - // Disable the 'elements' source - elements: false, + // Don't wait for any elements to appear + waitFor: [], // Only show the progress on regular and ajax-y page navigation, // not every request @@ -46,14 +46,44 @@ paceOptions = { } ``` -You can also put options on the script tag (the value must be valid JSON): +You can also put options on Pace's own script tag (the value must be valid JSON). They apply after `window.paceOptions`: ```html - + ``` -Pace reads its options once, when pace.js loads, so set them before including it. -Assigning `Pace.options` afterwards has no effect. +To change settings later, call `Pace.configure({ ... })`; `Pace.start({ ... })` does the same, then starts. Settings +about requests and navigation (`restartOnNavigation`, `restartOnRequestAfter`, `trackXHR`, `trackFetch`, +`trackWebSockets`, `requestMethods`, `ignoreRequests` and `maxWait`) apply from the next request or navigation; the +others from the next time the bar starts, so a bar that is showing doesn't change halfway. `Pace.getOptions()` returns a +copy of the settings in use. + +A wrong value or an unknown name is ignored, and the console shows a warning (once) that says what Pace expected. Pace +never throws because of a wrong value. + +| Setting | Default | What it does | +|---|---|---| +| `startOnPageLoad` | `true` | Show the bar while the page loads. With a bundler, call `Pace.start()` instead. | +| `restartOnNavigation` | `true` | Restart when the page calls `history.pushState` or `replaceState`. | +| `restartOnRequestAfter` | `500` | Restart for a tracked request still running after this many milliseconds; `false` to never. | +| `target` | `'body'` | A selector for the element the bar is added to. | +| `className` | `''` | Class names added to the bar's `.pace-progress` element. | +| `trackDocument` | `true` | Wait for the document to load. | +| `trackEventLag` | `true` | Wait until the page's scripts stop keeping it busy. | +| `waitFor` | `['body']` | Selectors that must each match an element; `[]` to not wait for any. | +| `trackXHR` | `true` | Track `XMLHttpRequest` requests. | +| `trackFetch` | `true` | Track `fetch()` requests. | +| `trackWebSockets` | `true` | Track WebSocket connections until they open. | +| `requestMethods` | `['GET']` | The methods of the requests to track, in any case. | +| `ignoreRequests` | `[]` | URL patterns (non-empty strings and regular expressions) of requests not to track. | +| `maxWait` | `15000` | The longest Pace waits for one request, in milliseconds; `false` for no limit. | +| `minVisible` | `250` | The shortest time the bar is shown, in milliseconds. | +| `hideDelay` | `100` | How long the full bar stays before it's hidden, in milliseconds. | +| `catchupTime` | `100` | About how many milliseconds the bar takes to catch up when the progress jumps. | +| `initialRate` | `0.03` | How fast the bar moves before any progress is known, in percent per millisecond. | +| `maxProgressPerFrame` | `20` | The most the bar moves in one frame, in percent. | +| `easeFactor` | `1.25` | How the bar slows down as it fills; higher values slow it later. | +| `extraSources` | `[]` | Your own progress sources, see Collectors below. | If you load pace with a bundler or module loader (AMD or CommonJS), it doesn't start on its own: set `window.paceOptions` before pace loads, then call `Pace.start()`. `import` statements run @@ -62,7 +92,7 @@ before the rest of a file, so put the options in their own file and import it fi ```javascript // pace-options.js window.paceOptions = { - document: false + trackDocument: false }; ``` @@ -113,16 +143,16 @@ Collectors are the bits of code which gather progress information. Pace includes Checks for event loop lag signaling that javascript is being executed -They can each be configured or disabled through configuration options of the same name. +They can each be configured or disabled through settings: ```javascript paceOptions = { - ajax: false, // disabled - document: false, // disabled - eventLag: false, // disabled - elements: { - selectors: ['.my-page'] - } + trackXHR: false, // disabled + trackFetch: false, // disabled + trackWebSockets: false, // disabled + trackDocument: false, // disabled + trackEventLag: false, // disabled + waitFor: ['.my-page'] }; ``` @@ -142,13 +172,11 @@ may never appear: ```javascript paceOptions = { - elements: { - selectors: ['.timeline, .timeline-error', '.user-profile, .profile-error'] - } + waitFor: ['.timeline, .timeline-error', '.user-profile, .profile-error'] } ``` -Pace will consider the elements test successful when each selector matches something. For +Pace will consider the elements test successful when each selector matches something (it checks every 100 ms). For this example, when either `.timeline` or `.timeline-error` exist, and either `.user-profile` or `.profile-error` exist. @@ -160,7 +188,7 @@ Most users want the progress bar to automatically restart when a pushState event ```javascript paceOptions = { - restartOnPushState: false + restartOnNavigation: false } ``` @@ -179,15 +207,18 @@ paceOptions = { You can always trigger a restart manually by calling `Pace.restart()` -See [the source](https://github.com/CodeByZach/pace/blob/master/pace.js) for a full list of options. - API --- Pace exposes the following methods: - `Pace.start`: Show the progress bar and start updating. Called automatically if you don't use AMD or CommonJS. -While a run is in progress (not yet `done`), it only stores the options for the next run. +While a run is in progress (not yet `done`), it doesn't restart it; the options it's given apply as described in +Configuration above. + +- `Pace.configure`: Change settings without starting the bar, see Configuration above. + +- `Pace.getOptions`: A copy of the settings in use. - `Pace.restart`: Show the progress bar if it's hidden and start reporting the progress from scratch. Called automatically whenever `pushState` or `replaceState` is called by default. @@ -208,7 +239,7 @@ Pace fires the following events: - `restart`: When pace is restarted (manually, or by a new AJAX request) - `progress`: On every frame while the bar is running, with the current progress (0–100) - `done`: When pace is finished -- `hide`: When the pace is hidden (can be later than `done`, based on `ghostTime` and `minTime`) +- `hide`: When the pace is hidden (can be later than `done`, based on `hideDelay` and `minVisible`) You can bind onto events using the `on`, `off` and `once` methods: @@ -229,32 +260,30 @@ Only `GET` requests are tracked by default. To also show the bar for other metho ```javascript paceOptions = { - ajax: { - trackMethods: ['GET', 'POST'] - } + requestMethods: ['GET', 'POST'] } ``` `fetch()` requests are tracked the same way, until their response arrives: Pace can't see a response's body load -without reading it. To stop tracking them, set `trackFetch: false` inside `ajax`. +without reading it. To stop tracking them, set `trackFetch: false`. Pace waits for each request at most `maxWait` milliseconds after it's sent (15000 by default), so a request that never -finishes can't hold the bar forever. The request itself keeps going. Set a different number, or `false` to wait for -every request until it ends (anything other than a number from 0 to 2147483647, about 24 days, means the same): +finishes can't hold the bar forever. The request itself keeps going. Set a different number (up to 2147483647, about 24 +days), or `false` to wait for every request until it ends: ```javascript paceOptions = { - ajax: { - maxWait: 30000 - } + maxWait: 30000 } ``` -You can disable all ajax tracking by setting `ajax` to false: +You can disable all ajax tracking by turning off each kind of request: ```javascript paceOptions = { - ajax: false + trackXHR: false, + trackFetch: false, + trackWebSockets: false } ``` @@ -288,9 +317,7 @@ You can also ignore URLs based on a pattern: ```javascript paceOptions = { - ajax: { - ignoreURLs: ['some-substring', /some-regexp/] - } + ignoreRequests: ['some-substring', /some-regexp/] } ``` @@ -302,11 +329,11 @@ resources on the page. Requests a page keeps open on purpose, such as long polling for chat or live updates, show the bar each time one starts, and so do slow requests a page makes in the background, such as prefetching links. Add their URLs to -`ignoreURLs`. +`ignoreRequests`. -WebSocket connections are tracked too. To stop that, set `trackWebSockets: false` inside `ajax`. When `trackFetch` or -`trackWebSockets` is false the first time Pace starts, Pace leaves `fetch` or `WebSocket` alone, so `Pace.track` can't -track them either. +WebSocket connections are tracked too. To stop that, set `trackWebSockets: false`. While `trackXHR`, `trackFetch` or +`trackWebSockets` is false, Pace doesn't track that kind of request, not even inside `Pace.track`, and until Pace has started +with it on, Pace leaves `XMLHttpRequest`, `fetch` or `WebSocket` alone. A few things Pace can't track: @@ -320,7 +347,7 @@ A few things Pace can't track: Avoid calling `Pace.restart()` for every request, for example from jQuery's `ajaxStart`. It restarts the bar even for ignored requests, and parallel requests restart it several times. To show the bar for `POST` requests, add `POST` to -`trackMethods` as shown above. +`requestMethods` as shown above. Dependencies ------------ diff --git a/pace.js b/pace.js index c20e418..4a923e3 100644 --- a/pace.js +++ b/pace.js @@ -4,35 +4,164 @@ * Licensed MIT © HubSpot, Inc. and Zachary Miller */ (function () { - const defaultOptions = { - className: '', - catchupTime: 100, - initialRate: 0.03, - minTime: 250, - ghostTime: 100, - maxProgressPerFrame: 20, - easeFactor: 1.25, - startOnPageLoad: true, - restartOnPushState: true, - restartOnRequestAfter: 500, - target: 'body', - elements: { - checkInterval: 100, - selectors: ['body'], - }, - eventLag: { - minSamples: 10, - sampleCount: 3, - lagThreshold: 3, - }, - ajax: { - trackMethods: ['GET'], - trackWebSockets: true, - trackFetch: true, - ignoreURLs: [], - maxWait: 15000, + // The longest delay a timer can wait: setTimeout treats more, and Infinity, as 0. + const MAX_DELAY = 2147483647; + + const isNumber = (value) => typeof value === 'number' && Number.isFinite(value); + const isMilliseconds = (value) => isNumber(value) && value >= 0 && value <= MAX_DELAY; + + // querySelector throws on anything that isn't a valid selector. + const isSelector = (value) => { + if (typeof value !== 'string') { + return false; + } + try { + document.createDocumentFragment().querySelector(value); + return true; + } catch { + return false; + } + }; + + // RegExp.prototype's source getter throws for anything that isn't a RegExp, + // so this also accepts a RegExp made in another frame, which instanceof + // wouldn't, and rejects an object that only claims to be one. + const regExpSource = Object.getOwnPropertyDescriptor(RegExp.prototype, 'source').get; + const isRegExp = (value) => { + try { + regExpSource.call(value); + return value !== RegExp.prototype; + } catch { + return false; + } + }; + + // Whether `new value()` works, without calling or reading anything from it: + // Reflect.construct checks that its target is a constructor before it reads + // the arguments, which throw here. + const notArguments = { + get length() { + throw notArguments; }, }; + const isConstructor = (value) => { + try { + Reflect.construct(value, notArguments); + } catch (error) { + return error === notArguments; + } + }; + + const BOOLEAN = { expected: 'true or false', test: (value) => typeof value === 'boolean' }; + const MILLISECONDS = { expected: `a number of milliseconds from 0 to ${MAX_DELAY}`, test: isMilliseconds }; + const MILLISECONDS_OR_FALSE = { expected: `false or ${MILLISECONDS.expected}`, test: (value) => value === false || isMilliseconds(value) }; + const ABOVE_ZERO = { expected: 'a number greater than 0', test: (value) => isNumber(value) && value > 0 }; + const listOf = (expected, test) => ({ expected: `an array of ${expected}`, test: Array.isArray, item: test }); + + // Each setting with its default and the values it accepts. + const SETTINGS = new Map([ + ['startOnPageLoad', [true, BOOLEAN]], + ['restartOnNavigation', [true, BOOLEAN]], + ['restartOnRequestAfter', [500, MILLISECONDS_OR_FALSE]], + ['target', ['body', { expected: 'a valid CSS selector', test: isSelector }]], + ['className', ['', { expected: 'a string', test: (value) => typeof value === 'string' }]], + ['trackDocument', [true, BOOLEAN]], + ['trackEventLag', [true, BOOLEAN]], + ['waitFor', [['body'], listOf('valid CSS selectors', isSelector)]], + ['trackXHR', [true, BOOLEAN]], + ['trackFetch', [true, BOOLEAN]], + ['trackWebSockets', [true, BOOLEAN]], + ['requestMethods', [['GET'], listOf('strings', (item) => typeof item === 'string')]], + ['ignoreRequests', [[], listOf('non-empty strings and RegExps', (item) => (typeof item === 'string' && item !== '') || isRegExp(item))]], + ['maxWait', [15000, MILLISECONDS_OR_FALSE]], + ['minVisible', [250, MILLISECONDS]], + ['hideDelay', [100, MILLISECONDS]], + ['catchupTime', [100, ABOVE_ZERO]], + ['initialRate', [0.03, { expected: 'a number of 0 or more', test: (value) => isNumber(value) && value >= 0 }]], + ['maxProgressPerFrame', [20, ABOVE_ZERO]], + ['easeFactor', [1.25, ABOVE_ZERO]], + ['extraSources', [[], listOf('constructors', isConstructor)]], + ]); + + // Version 1 settings, and what replaced them. + const RENAMED = new Map([ + ['ajax', 'trackXHR, trackFetch, trackWebSockets, requestMethods, ignoreRequests and maxWait'], + ['document', 'trackDocument'], + ['elements', 'waitFor'], + ['eventLag', 'trackEventLag'], + ['ghostTime', 'hideDelay'], + ['minTime', 'minVisible'], + ['restartOnPushState', 'restartOnNavigation'], + ]); + + // A copy of a setting's value that shares nothing that can change: a list + // becomes a plain array, read once, and its RegExps (whose lastIndex changes, + // and which the page could freeze) are copied. + const copyValue = (value) => { + if (!Array.isArray(value)) { + return value; + } + const copy = []; + for (let i = 0, n = value.length; i < n; i++) { + const item = value[i]; + copy.push(isRegExp(item) ? new RegExp(item) : item); + } + return copy; + }; + + const copyOptions = (settings) => { + const copy = {}; + for (const name of SETTINGS.keys()) { + copy[name] = copyValue(settings[name]); + } + return copy; + }; + + const options = copyOptions(Object.fromEntries([...SETTINGS].map(([name, [value]]) => [name, value]))); + + // A value as a warning shows it: its type, and the value itself when that is short. + const describe = (value) => { + if (value == null) { + return String(value); + } + if (Array.isArray(value)) { + return 'array'; + } + switch (typeof value) { + case 'string': { + const json = JSON.stringify(value); + return `string ${json.length > 50 ? json.slice(0, 48) + '…"' : json}`; + } + case 'object': + return Object.prototype.toString.call(value).slice(8, -1); + case 'function': + return 'function'; + default: + return `${typeof value} ${String(value)}`; + } + }; + + const warned = new Set(); + + // Logs each distinct warning once. + const warn = (message) => { + message = `Pace: ${message}`; + if (!warned.has(message)) { + warned.add(message); + console.warn(message); + } + }; + + // What is wrong with `value` for a setting that accepts `check`, or undefined. + const problemWith = (check, value) => { + if (!check.test(value)) { + return describe(value); + } + const index = check.item ? value.findIndex((item) => !check.item(item)) : -1; + if (index !== -1) { + return `array containing ${describe(value[index])}`; + } + }; const now = () => performance.now(); @@ -46,25 +175,6 @@ return obj[key]; }; - const extend = (out, ...sources) => { - for (const source of sources) { - if (!source) { - continue; - } - for (const key in source) { - if (!Object.prototype.hasOwnProperty.call(source, key)) continue; - if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue; - const val = source[key]; - if (out[key] != null && typeof out[key] === 'object' && val != null && typeof val === 'object') { - extend(out[key], val); - } else { - out[key] = val; - } - } - } - return out; - }; - const avgAmplitude = (arr) => { let sum = 0; let count = 0; @@ -75,22 +185,6 @@ return sum / count; }; - const getFromDOM = (key = 'options', json = true) => { - const el = document.querySelector(`script[data-pace-${key}]`); - if (!el) { - return; - } - const data = el.getAttribute(`data-pace-${key}`); - if (!json) { - return data; - } - try { - return JSON.parse(data); - } catch (e) { - console.error('Error parsing inline pace options', e); - } - }; - const Pace = window.Pace || {}; window.Pace = Pace; @@ -166,21 +260,74 @@ }, }); - const options = (Pace.options = extend({}, defaultOptions, window.paceOptions, getFromDOM())); - - // `true` turns a collector on with its default settings. - const normalizeOptions = () => { - for (const key of ['ajax', 'document', 'eventLag', 'elements']) { - if (options[key] === true) { - options[key] = defaultOptions[key]; + // Applies the settings in `given`, from `channel` (named in warnings). A wrong + // value or an unknown name is ignored with a warning; undefined means not given. + // Each value is copied, then the copy is checked and kept, so changing the + // page's own list later changes nothing. An error from reading a setting (a + // getter that throws, say) is reported, and the other settings still apply. + const applyOptions = (given, channel) => { + if (given === undefined) { + return; + } + try { + if (Object.prototype.toString.call(given) !== '[object Object]') { + warn(`ignored the options from ${channel}: expected an object, got ${describe(given)}.`); + return; } + for (const name of Object.keys(given)) { + try { + const value = copyValue(given[name]); + if (value === undefined) { + continue; + } + if (SETTINGS.has(name)) { + const [, check] = SETTINGS.get(name); + const problem = problemWith(check, value); + if (problem) { + warn(`ignored the ${name} option from ${channel}: expected ${check.expected}, got ${problem}.`); + } else { + options[name] = value; + } + } else if (RENAMED.has(name)) { + warn(`ignored the ${name} option from ${channel}: use ${RENAMED.get(name)} instead.`); + } else { + const match = [...SETTINGS.keys()].find((known) => known.toLowerCase() === name.toLowerCase()); + warn(`ignored the unknown option ${name} from ${channel}.${match ? ` Did you mean ${match}?` : ''}`); + } + } catch (error) { + reportException(error); + } + } + } catch (error) { + reportException(error); + } + }; + + // Pace's own " }); + test(`${api}: ignoreRequests patterns see the full URL`, async ({ page, open }) => { + await open({ head: "" }); await idle(page); await clearEvents(page); await request(page, { ms: 900, api }); // a relative URL expect(await page.evaluate(() => events)).toEqual([]); }); - test(`${api}: ajax.ignoreURLs patterns also see the path and query of a request to the page's origin, not another's`, async ({ page, open }) => { + test(`${api}: ignoreRequests patterns also see the path and query of a request to the page's origin, not another's`, async ({ page, open }) => { await page.route('http://other.test/**', async (route) => { await new Promise((resolve) => setTimeout(resolve, 900)); await route.fulfill({ headers: { 'access-control-allow-origin': '*' }, body: 'ok' }); }); - await open({ head: "" }); + await open({ head: "" }); await idle(page); await clearEvents(page); await request(page, { ms: 900, api, origin: 'http://pace.test', query: '#part' }); // an absolute URL @@ -28,8 +28,8 @@ for (const api of ['XMLHttpRequest', 'fetch']) { expect(await page.evaluate(() => events)).toEqual(RESTARTED); }); - test(`${api}: ajax.ignoreURLs patterns also see the URL as the page wrote it`, async ({ page, open }) => { - await open({ head: "" }); + test(`${api}: ignoreRequests patterns also see the URL as the page wrote it`, async ({ page, open }) => { + await open({ head: "" }); await idle(page); await clearEvents(page); // Neither appears in the full URL, which has %20 for the space and a lowercase domain. @@ -38,8 +38,8 @@ for (const api of ['XMLHttpRequest', 'fetch']) { expect(await page.evaluate(() => events)).toEqual([]); }); - test(`${api}: ajax.ignoreURLs patterns see the full URL resolved against `, async ({ page, open }) => { - await open({ head: '' }); + test(`${api}: ignoreRequests patterns see the full URL resolved against `, async ({ page, open }) => { + await open({ head: '' }); await idle(page); await clearEvents(page); await page.evaluate((api) => (api === 'fetch' @@ -54,7 +54,7 @@ for (const api of ['XMLHttpRequest', 'fetch']) { expect(await page.evaluate(() => events)).toEqual([]); }); - test.describe(`${api} with default ajax options`, () => { + test.describe(`${api} with default request settings`, () => { test.beforeEach(async ({ page, open }) => { await open({ head: NO_EVENT_LAG }); await idle(page); @@ -91,39 +91,22 @@ for (const api of ['XMLHttpRequest', 'fetch']) { }); }); - test.describe(`${api} with ajax options`, () => { + test.describe(`${api} with request settings`, () => { test.beforeEach(async ({ page, open }) => { - await open({ head: "" }); + await open({ head: "" }); await idle(page); await clearEvents(page); }); - test('ajax.trackMethods can add POST', async ({ page }) => { + test('requestMethods can add POST', async ({ page }) => { await request(page, { ms: 900, method: 'POST', api }); await idle(page); expect(await page.evaluate(() => events)).toEqual(RESTARTED); }); - test('ajax.ignoreURLs skips matching URLs', async ({ page }) => { + test('ignoreRequests skips matching URLs', async ({ page }) => { await request(page, { ms: 900, query: '&ignored', api }); expect(await page.evaluate(() => events)).toEqual([]); }); }); } - -test.describe('with ajax.trackMethods that is not an array', () => { - test('a string matches nothing, not substrings', async ({ page, open }) => { - await open({ head: "" }); - await idle(page); - await clearEvents(page); - await request(page, { ms: 900 }); - expect(await page.evaluate(() => events)).toEqual([]); - }); - - test('a number does not break the page\'s requests', async ({ page, open }) => { - await open({ head: '' }); - await idle(page); - // Resolves only if the page's xhr.open() didn't throw. - await request(page, { ms: 100 }); - }); -}); diff --git a/tests/contract.spec.mjs b/tests/contract.spec.mjs index 57ae739..b73ec2f 100644 --- a/tests/contract.spec.mjs +++ b/tests/contract.spec.mjs @@ -59,10 +59,10 @@ test('reads options from data-pace-options on its ' }); - await page.evaluate(() => Pace.start({ eventLag: false })); + await page.evaluate(() => Pace.start({ trackEventLag: false })); await idle(page); }); diff --git a/tests/fetch.spec.mjs b/tests/fetch.spec.mjs index 399f510..306c8ca 100644 --- a/tests/fetch.spec.mjs +++ b/tests/fetch.spec.mjs @@ -7,22 +7,17 @@ import { test, expect, idle, request, clearEvents, RESTARTED, NO_EVENT_LAG } fro const SAVE_FETCH = ''; test('pace hooks into fetch only once it starts', async ({ page, open }) => { - await open({ head: SAVE_FETCH + '' }); + await open({ head: SAVE_FETCH + '' }); expect(await page.evaluate(() => fetch === nativeFetch)).toBe(true); await page.evaluate(() => Pace.start()); expect(await page.evaluate(() => [fetch === nativeFetch, fetch.length === nativeFetch.length])).toEqual([false, true]); }); -for (const [name, options] of [ - ['trackFetch: false', '{ eventLag: false, ajax: { trackFetch: false } }'], - ['ajax: false', '{ eventLag: false, ajax: false }'], -]) { - test(`with ${name}, fetch stays native`, async ({ page, open }) => { - await open({ head: `${SAVE_FETCH}` }); - await idle(page); - expect(await page.evaluate(() => fetch === nativeFetch)).toBe(true); - }); -} +test('with trackFetch: false, fetch stays native', async ({ page, open }) => { + await open({ head: `${SAVE_FETCH}` }); + await idle(page); + expect(await page.evaluate(() => fetch === nativeFetch)).toBe(true); +}); test('a fetch during page load holds the bar until it settles', async ({ page, open }) => { await open({ @@ -55,8 +50,8 @@ test('the method comes from init, then from a Request', async ({ page, open }) = } }); -test('ajax.ignoreURLs patterns see the URL of a Request', async ({ page, open }) => { - await open({ head: "" }); +test('ignoreRequests patterns see the URL of a Request', async ({ page, open }) => { + await open({ head: "" }); await idle(page); await clearEvents(page); await page.evaluate(() => fetch(new Request('/delay?ms=900&ignored')).then((response) => response.text())); @@ -64,7 +59,7 @@ test('ajax.ignoreURLs patterns see the URL of a Request', async ({ page, open }) }); test('a Request made in another frame is read like one made in this frame', async ({ page, open }) => { - await open({ head: "", body: '' }); + await open({ head: "", body: '' }); await idle(page); await clearEvents(page); await page.evaluate(() => { @@ -82,7 +77,7 @@ test('turning trackFetch off in a later Pace.start() stops tracking fetch', asyn await idle(page); await page.evaluate(() => { Pace.stop(); - Pace.start({ ajax: { trackFetch: false } }); + Pace.start({ trackFetch: false }); }); await idle(page); await clearEvents(page); @@ -197,7 +192,7 @@ test.describe('with a real server', () => { }); test('a tracked Request keeps its body for the server', async ({ page, server }) => { - await page.goto(`${server}/?options=${encodeURIComponent("{ eventLag: false, ajax: { trackMethods: ['POST'] } }")}`); + await page.goto(`${server}/?options=${encodeURIComponent("{ trackEventLag: false, requestMethods: ['POST'] }")}`); await idle(page); await clearEvents(page); const result = await page.evaluate(async () => { diff --git a/tests/fixtures.mjs b/tests/fixtures.mjs index c363717..4592333 100644 --- a/tests/fixtures.mjs +++ b/tests/fixtures.mjs @@ -15,7 +15,7 @@ const root = new URL('..', import.meta.url); // `server` is the origin of a real server on 127.0.0.1, one per worker, for what routed // responses don't reproduce: responses that arrive in parts, network errors, requests that never // end, and WebSockets. (Chrome doesn't let the fake public origin above connect to 127.0.0.1.) -// /?options=JS a page that sets window.paceOptions to JS (default { eventLag: false }), +// /?options=JS a page that sets window.paceOptions to JS (default { trackEventLag: false }), // loads pace and records its events like open(); with ?socket it opens // a WebSocket to /socket, recording window.openedAt // /delay?ms=N answers after N ms. No Content-Length (chunked), so a request's progress @@ -66,7 +66,7 @@ export const test = base.extend({ } res.writeHead(200, { 'content-type': 'text/html' }); res.end(` - + `; -export const NO_EVENT_LAG = ''; +export const NO_EVENT_LAG = ''; diff --git a/tests/lifecycle.spec.mjs b/tests/lifecycle.spec.mjs index da17cb7..15a464b 100644 --- a/tests/lifecycle.spec.mjs +++ b/tests/lifecycle.spec.mjs @@ -4,7 +4,7 @@ import { test, expect, idle, request, clearEvents, RESTARTED, HOLD, NO_EVENT_LAG // Like HOLD, plus other options. const hold = (extra) => ``; const bodyClasses = (page) => page.evaluate(() => [...document.body.classList].filter((name) => name.startsWith('pace-'))); @@ -48,7 +48,7 @@ test('Pace.start() while running does nothing', async ({ page, open }) => { }); test('pushState while the bar is finishing starts a new run that finishes once', async ({ page, open }) => { - await open({ head: hold('{ ghostTime: 1000 }') }); + await open({ head: hold('{ hideDelay: 1000 }') }); await page.evaluate(() => new Promise((resolve) => { Pace.once('done', () => setTimeout(resolve, 100)); hold.progress = 100; @@ -65,7 +65,7 @@ test('pushState while the bar is finishing starts a new run that finishes once', }); test('Pace.stop() from a done handler: no hide and no bar', async ({ page, open }) => { - await open({ head: hold('{ ghostTime: 300 }') }); + await open({ head: hold('{ hideDelay: 300 }') }); await page.evaluate(() => { Pace.once('done', () => Pace.stop()); hold.progress = 100; }); await page.waitForTimeout(800); expect(await page.evaluate(() => events)).toEqual(['start', 'done', 'stop']); @@ -73,7 +73,7 @@ test('Pace.stop() from a done handler: no hide and no bar', async ({ page, open }); test('a request that starts while the bar is finishing restarts it', async ({ page, open }) => { - await open({ head: hold('{ ghostTime: 1000 }') }); + await open({ head: hold('{ hideDelay: 1000 }') }); const loaded = page.evaluate(() => new Promise((resolve) => { Pace.once('done', () => { const xhr = new XMLHttpRequest(); @@ -141,7 +141,7 @@ test('waits for the last of several requests, whatever order they finish in', as test('waits for every selector, whatever order they appear in', async ({ page, open }) => { await open({ - head: "", + head: "", body: `" }); - await page.evaluate(() => Pace.start({ elements: { selectors: ['#late'] } })); + await open({ head: "" }); + await page.evaluate(() => Pace.start({ waitFor: ['#late'] })); await page.waitForTimeout(800); expect(await page.evaluate(() => events)).toEqual(['start']); await page.evaluate(() => { const el = document.createElement('i'); el.id = 'late'; document.body.appendChild(el); }); @@ -238,16 +238,16 @@ test('a navigation from a progress handler leaves one bar', async ({ page, open }); test('Pace.stop() while the bar first renders means no start event', async ({ page, open }) => { - await open({ head: "" }); + await open({ head: "" }); await page.evaluate(() => { Pace.once('change', () => Pace.stop()); Pace.start(); }); await page.waitForTimeout(300); expect(await page.evaluate(() => [events, Pace.running])).toEqual([['stop'], false]); }); -test('an invalid selector neither leaves pace stuck nor breaks navigation', async ({ page, open }) => { +test('an extra source that throws neither leaves pace stuck nor breaks navigation', async ({ page, open }) => { const errors = []; page.on('pageerror', (error) => errors.push(error.message)); - await open({ head: "" }); + await open({ head: "" }); const [search, running] = await page.evaluate(() => { history.pushState({}, '', '?next'); return [location.search, Pace.running]; diff --git a/tests/max-wait.spec.mjs b/tests/max-wait.spec.mjs index d79f299..bcb61ab 100644 --- a/tests/max-wait.spec.mjs +++ b/tests/max-wait.spec.mjs @@ -1,21 +1,8 @@ -// ajax.maxWait: pace waits for each tracked request at most this many ms from when it was sent, +// maxWait: pace waits for each tracked request at most this many ms from when it was sent, // so one request that never ends can't hold the bar forever. The request itself keeps going. import { test, expect, idle, request, clearEvents, RESTARTED } from './fixtures.mjs'; -const options = (maxWait) => ``; - -// A value a timer can't wait for (setTimeout would treat it as 0) means no limit, like false. -for (const value of ['Infinity', 'null', 'undefined', '2 ** 31']) { - test(`with maxWait: ${value}, pace waits for a request until it ends`, async ({ page, open }) => { - await open({ head: options(value) }); - await idle(page); - await clearEvents(page); - const loadedAt = await request(page, { ms: 900 }); - await idle(page); - expect(await page.evaluate(() => events)).toEqual(RESTARTED); - expect(await page.evaluate(() => eventTimes.done)).toBeGreaterThanOrEqual(loadedAt - 50); - }); -} +const options = (maxWait) => ``; for (const [api, send] of [ ['XMLHttpRequest', "var xhr = new XMLHttpRequest(); xhr.open('GET', '/delay?ms=4000'); xhr.onload = function () { loaded = xhr.responseText; }; xhr.send();"], @@ -109,7 +96,7 @@ test.describe('with a real server', () => { }; test('by default, pace stops waiting for a request 15 s after it was sent', async ({ page, server }) => { - await hangAfterLoad(page, server, '{ eventLag: false }'); + await hangAfterLoad(page, server, '{ trackEventLag: false }'); await page.clock.runFor(1000); // the bar restarts at 500 ms await page.clock.fastForward(13500); expect(await page.evaluate(() => events)).toEqual(['restart', 'stop', 'start']); @@ -118,7 +105,7 @@ test.describe('with a real server', () => { }); test('with maxWait: false, pace keeps waiting for a request that never ends', async ({ page, server }) => { - await hangAfterLoad(page, server, '{ eventLag: false, ajax: { maxWait: false } }'); + await hangAfterLoad(page, server, '{ trackEventLag: false, maxWait: false }'); await page.clock.runFor(1000); // the bar restarts at 500 ms await page.clock.fastForward(59000); await page.clock.runFor(1000); @@ -126,7 +113,7 @@ test.describe('with a real server', () => { }); test('a WebSocket whose handshake is never answered holds the bar only until maxWait', async ({ page, server }) => { - await page.goto(`${server}/?socket=never&options=${encodeURIComponent('{ eventLag: false, ajax: { maxWait: 1500 } }')}`); + await page.goto(`${server}/?socket=never&options=${encodeURIComponent('{ trackEventLag: false, maxWait: 1500 }')}`); await idle(page); const doneAt = await page.evaluate(() => eventTimes.done); expect(doneAt).toBeGreaterThanOrEqual(1400); diff --git a/tests/navigation.spec.mjs b/tests/navigation.spec.mjs index 396a3fa..060e47a 100644 --- a/tests/navigation.spec.mjs +++ b/tests/navigation.spec.mjs @@ -10,8 +10,8 @@ test('history.pushState restarts the bar', async ({ page, open }) => { expect(await page.evaluate(() => events)).toEqual(RESTARTED); }); -test('restartOnPushState: false does not restart the bar', async ({ page, open }) => { - await open({ head: '' }); +test('restartOnNavigation: false does not restart the bar', async ({ page, open }) => { + await open({ head: '' }); await idle(page); await clearEvents(page); await page.evaluate(() => history.pushState({}, '', '/next')); diff --git a/tests/requests.spec.mjs b/tests/requests.spec.mjs index 6688a15..bf245fc 100644 --- a/tests/requests.spec.mjs +++ b/tests/requests.spec.mjs @@ -64,8 +64,8 @@ test('WebSocket keeps its prototype and constants', async ({ page, open }) => { expect(result).toEqual({ instance: true, open: 1, url: 'ws://127.0.0.1:9/', subclass: 'hi' }); }); -test('with ajax: false, pace leaves XMLHttpRequest and WebSocket alone, and Pace.track does not throw', async ({ page, open }) => { - await open({ head: SAVE_NATIVES + '' }); +test('with trackXHR and trackWebSockets off, pace leaves XMLHttpRequest and WebSocket alone, and Pace.track does not throw', async ({ page, open }) => { + await open({ head: SAVE_NATIVES + '' }); await idle(page); const result = await page.evaluate(() => new Promise((resolve) => { const untouched = XMLHttpRequest === NativeXHR && XMLHttpRequest.prototype.open === nativeOpen && WebSocket === NativeWebSocket; @@ -78,7 +78,7 @@ test('with ajax: false, pace leaves XMLHttpRequest and WebSocket alone, and Pace }); test('pace hooks into XMLHttpRequest only once it starts', async ({ page, open }) => { - await open({ head: SAVE_NATIVES + '' }); + await open({ head: SAVE_NATIVES + '' }); expect(await page.evaluate(() => XMLHttpRequest.prototype.open === nativeOpen)).toBe(true); await page.evaluate(() => Pace.start()); expect(await page.evaluate(() => XMLHttpRequest.prototype.open === nativeOpen)).toBe(false); @@ -105,8 +105,8 @@ test('a request opened but never sent on an idle page does not restart the bar', expect(await page.evaluate(() => events)).toEqual([]); }); -test('a URL object works with ajax.ignoreURLs', async ({ page, open }) => { - await open({ head: "" }); +test('a URL object works with ignoreRequests', async ({ page, open }) => { + await open({ head: "" }); await idle(page); await clearEvents(page); await page.evaluate(() => new Promise((resolve, reject) => { @@ -120,7 +120,7 @@ test('a URL object works with ajax.ignoreURLs', async ({ page, open }) => { }); test('a URL object changed after open() is matched as open() used it', async ({ page, open }) => { - await open({ head: "" }); + await open({ head: "" }); await idle(page); await clearEvents(page); await page.evaluate(() => new Promise((resolve, reject) => { @@ -135,8 +135,8 @@ test('a URL object changed after open() is matched as open() used it', async ({ expect(await page.evaluate(() => events)).toEqual([]); }); -test('an ajax.ignoreURLs pattern with the g flag ignores every matching request', async ({ page, open }) => { - await open({ head: '' }); +test('an ignoreRequests pattern with the g flag ignores every matching request', async ({ page, open }) => { + await open({ head: '' }); await idle(page); await clearEvents(page); // Two requests, so a pattern that kept its lastIndex from the first would miss the second. @@ -144,8 +144,8 @@ test('an ajax.ignoreURLs pattern with the g flag ignores every matching request' expect(await page.evaluate(() => events)).toEqual([]); }); -test('an ajax.ignoreURLs entry that is neither a string nor a RegExp is skipped', async ({ page, open }) => { - await open({ head: '' }); +test('ignoreRequests with an entry that is neither a string nor a RegExp is ignored, and requests still work', async ({ page, open }) => { + await open({ head: '' }); await idle(page); await request(page, { ms: 10 }); // rejects if send() throws }); @@ -237,7 +237,7 @@ test('an open() that throws on a loading request does not stop tracking it', asy }); test('a background request that no run was tracking does not hold a navigation', async ({ page, open }) => { - await open({ head: '' }); + await open({ head: '' }); await idle(page); await clearEvents(page); const loaded = request(page, { ms: 3000 }); @@ -313,7 +313,7 @@ test('a navigation keeps tracking the requests of the run it replaces', async ({ }); test('with trackWebSockets: false, WebSocket stays native', async ({ page, open }) => { - await open({ head: SAVE_NATIVES + '' }); + await open({ head: SAVE_NATIVES + '' }); await idle(page); expect(await page.evaluate(() => WebSocket === NativeWebSocket)).toBe(true); }); @@ -328,8 +328,8 @@ test.describe('with a real server', () => { expect(doneAt).toBeGreaterThanOrEqual(openedAt); }); - test('ajax.ignoreURLs patterns see the full URL of a WebSocket', async ({ page, server }) => { - await page.goto(`${server}/?options=${encodeURIComponent('{ eventLag: false, ajax: { ignoreURLs: [/^ws:\\/\\/127\\.0\\.0\\.1:\\d+\\/socket/] } }')}`); + test('ignoreRequests patterns see the full URL of a WebSocket', async ({ page, server }) => { + await page.goto(`${server}/?options=${encodeURIComponent('{ trackEventLag: false, ignoreRequests: [/^ws:\\/\\/127\\.0\\.0\\.1:\\d+\\/socket/] }')}`); await idle(page); await clearEvents(page); await page.evaluate(() => { window.socket = new WebSocket('/socket?never'); }); // a relative URL diff --git a/tests/settings.spec.mjs b/tests/settings.spec.mjs new file mode 100644 index 0000000..51986a1 --- /dev/null +++ b/tests/settings.spec.mjs @@ -0,0 +1,371 @@ +// Settings: their names and defaults, how they are given, checked, changed and read. +import { test, expect, idle, request, clearEvents, RESTARTED, HOLD } from './fixtures.mjs'; + +const options = (js) => ``; + +// The console warnings the page logs, from now on. +const warnings = (page) => { + const messages = []; + page.on('console', (message) => { + if (message.type() === 'warning') messages.push(message.text()); + }); + return messages; +}; + +const DEFAULTS = { + startOnPageLoad: true, + restartOnNavigation: true, + restartOnRequestAfter: 500, + target: 'body', + className: '', + trackDocument: true, + trackEventLag: true, + waitFor: ['body'], + trackXHR: true, + trackFetch: true, + trackWebSockets: true, + requestMethods: ['GET'], + ignoreRequests: [], + maxWait: 15000, + minVisible: 250, + hideDelay: 100, + catchupTime: 100, + initialRate: 0.03, + maxProgressPerFrame: 20, + easeFactor: 1.25, + extraSources: [], +}; + +test('Pace.getOptions() returns every setting with its default', async ({ page, open }) => { + await open(); + expect(await page.evaluate(() => Pace.getOptions())).toEqual(DEFAULTS); + expect(await page.evaluate(() => 'options' in Pace)).toBe(false); +}); + +test('Pace.getOptions() returns a new copy each time', async ({ page, open }) => { + await open({ head: options("{ waitFor: ['body'], ignoreRequests: [/a/] }") }); + const [same, after] = await page.evaluate(() => { + const first = Pace.getOptions(); + first.waitFor.push('#changed'); + first.ignoreRequests.length = 0; + first.minVisible = 0; + return [first === Pace.getOptions(), Pace.getOptions()]; + }); + expect(same).toBe(false); + expect(after.waitFor).toEqual(['body']); + expect(after.ignoreRequests).toHaveLength(1); + expect(after.minVisible).toBe(250); +}); + +test('a list given to pace is copied: changing it afterwards changes nothing', async ({ page, open }) => { + await open({ head: options('{ startOnPageLoad: false }') }); + const waitFor = await page.evaluate(() => { + const list = ['body']; + Pace.configure({ waitFor: list }); + list.push('#changed'); + return Pace.getOptions().waitFor; + }); + expect(waitFor).toEqual(['body']); +}); + +test('Pace.configure() changes settings without starting the bar', async ({ page, open }) => { + await open({ head: options('{ startOnPageLoad: false }') }); + await page.evaluate(() => Pace.configure({ className: 'configured', hideDelay: 50 })); + expect(await page.evaluate(() => [Pace.getOptions().className, Pace.getOptions().hideDelay, events])).toEqual(['configured', 50, []]); + await expect(page.locator('.pace')).toHaveCount(0); + await page.evaluate(() => Pace.start()); + await expect(page.locator('.pace-progress')).toHaveClass('pace-progress configured'); +}); + +test('a setting changed during a run applies from the next run', async ({ page, open }) => { + await open({ head: HOLD }); + await page.evaluate(() => Pace.configure({ hideDelay: 1000 })); + await page.evaluate(() => { hold.progress = 100; }); + await idle(page); + expect(await page.evaluate(() => eventTimes.hide - eventTimes.done)).toBeLessThan(500); + await page.evaluate(() => { Pace.restart(); hold.progress = 100; }); + await expect.poll(() => page.evaluate(() => events.filter((name) => name === 'hide').length), { timeout: 5000 }).toBe(2); + expect(await page.evaluate(() => eventTimes.hide - eventTimes.done)).toBeGreaterThanOrEqual(950); +}); + +test('Pace.configure() before the first start leaves the page\'s request functions alone', async ({ page, open }) => { + await open({ head: '' + options('{ startOnPageLoad: false, trackFetch: false }') }); + await page.evaluate(() => Pace.configure({ trackFetch: true, trackXHR: true })); + expect(await page.evaluate(() => [fetch === nativeFetch, XMLHttpRequest.prototype.open === nativeOpen])).toEqual([true, true]); +}); + +test('pace hooks into each kind of request only once', async ({ page, open }) => { + await open({ head: options('{ trackEventLag: false }') }); + await idle(page); + const same = await page.evaluate(() => { + const hooks = () => [XMLHttpRequest.prototype.open, XMLHttpRequest.prototype.send, window.fetch, window.WebSocket]; + const before = hooks(); + Pace.configure({}); + Pace.start({}); + Pace.restart(); + return hooks().every((hook, i) => hook === before[i]); + }); + expect(same).toBe(true); +}); + +test('requestMethods match whatever their case', async ({ page, open }) => { + await open({ head: options("{ trackEventLag: false, requestMethods: ['get', 'post'] }") }); + await idle(page); + await clearEvents(page); + await request(page, { ms: 900, method: 'POST' }); + await idle(page); + expect(await page.evaluate(() => events)).toEqual(RESTARTED); +}); + +test('ignoreRequests works with a RegExp the page has frozen, or one made in another frame', async ({ page, open }) => { + await open({ head: options('{ trackEventLag: false }'), body: '' }); + await idle(page); + await clearEvents(page); + await page.evaluate(() => Pace.configure({ ignoreRequests: [Object.freeze(/ms=900/g), frames[0].eval('/ms=901/')] })); + await request(page, { ms: 900 }); + await request(page, { ms: 901 }); + expect(await page.evaluate(() => events)).toEqual([]); +}); + +test('turning trackFetch on later tracks the next fetch, and pace leaves fetch alone until then', async ({ page, open }) => { + await open({ head: '' + options('{ trackEventLag: false, trackFetch: false }') }); + await idle(page); + expect(await page.evaluate(() => window.fetch === window.nativeFetch)).toBe(true); + await clearEvents(page); + await page.evaluate(() => Pace.configure({ trackFetch: true })); + await request(page, { ms: 900, api: 'fetch' }); + await idle(page); + expect(await page.evaluate(() => events)).toEqual(RESTARTED); +}); + +test('trackXHR: false leaves XMLHttpRequest alone', async ({ page, open }) => { + await open({ head: '' + options('{ trackEventLag: false, trackXHR: false }') }); + await idle(page); + await clearEvents(page); + await request(page, { ms: 900 }); + expect(await page.evaluate(() => [events, XMLHttpRequest.prototype.open === window.nativeOpen])).toEqual([[], true]); +}); + +test('minVisible: the bar stays at least this long', async ({ page, open }) => { + await open({ head: options('{ trackEventLag: false, minVisible: 1500 }') }); + await idle(page); + const shown = await page.evaluate(() => eventTimes.hide - eventTimes.start); + expect(shown).toBeGreaterThanOrEqual(1450); +}); + +test('trackDocument: false does not wait for the page to load', async ({ page, open }) => { + // The image holds the load event for 3 s. + await open({ + head: options('{ trackEventLag: false, trackDocument: false }') + "", + body: '', + }); + await idle(page); + const [doneAt, loadedAt] = await page.evaluate(() => [eventTimes.done, window.loadedAt]); + expect(doneAt).toBeLessThan(loadedAt - 1000); +}); + +test('trackEventLag: false does not wait for the page to stop being busy', async ({ page, open }) => { + // Measuring event lag takes at least 500 ms (ten samples, 50 ms apart). + await open({ head: options('{ trackEventLag: false, trackDocument: false }') }); + await idle(page); + expect(await page.evaluate(() => eventTimes.done - eventTimes.start)).toBeLessThan(400); +}); + +test.describe('wrong values and unknown names', () => { + test('a wrong value is ignored with a warning, and the setting keeps its value', async ({ page, open }) => { + const logged = warnings(page); + await open({ head: options("{ minVisible: 'slow', hideDelay: -1, maxWait: Infinity, trackXHR: 'no', target: 5, requestMethods: ['GET', 7], catchupTime: 0 }") }); + expect(logged).toEqual([ + 'Pace: ignored the minVisible option from window.paceOptions: expected a number of milliseconds from 0 to 2147483647, got string "slow".', + 'Pace: ignored the hideDelay option from window.paceOptions: expected a number of milliseconds from 0 to 2147483647, got number -1.', + 'Pace: ignored the maxWait option from window.paceOptions: expected false or a number of milliseconds from 0 to 2147483647, got number Infinity.', + 'Pace: ignored the trackXHR option from window.paceOptions: expected true or false, got string "no".', + 'Pace: ignored the target option from window.paceOptions: expected a valid CSS selector, got number 5.', + 'Pace: ignored the requestMethods option from window.paceOptions: expected an array of strings, got array containing number 7.', + 'Pace: ignored the catchupTime option from window.paceOptions: expected a number greater than 0, got number 0.', + ]); + expect(await page.evaluate(() => Pace.getOptions())).toEqual(DEFAULTS); + }); + + test('an unknown name is ignored with a warning, which suggests the name that differs only in case', async ({ page, open }) => { + const logged = warnings(page); + await open({ head: options("{ classname: 'a', colour: 'red' }") }); + expect(logged).toEqual([ + 'Pace: ignored the unknown option classname from window.paceOptions. Did you mean className?', + 'Pace: ignored the unknown option colour from window.paceOptions.', + ]); + await expect(page.locator('.pace-progress')).toHaveClass('pace-progress'); + }); + + test('a version 1 name is ignored with a warning that names what replaced it', async ({ page, open }) => { + const logged = warnings(page); + await open({ head: options("{ ajax: { trackMethods: ['POST'] }, eventLag: false, elements: { selectors: ['#x'] }, document: false, restartOnPushState: false, minTime: 0, ghostTime: 0 }") }); + expect(logged).toEqual([ + 'Pace: ignored the ajax option from window.paceOptions: use trackXHR, trackFetch, trackWebSockets, requestMethods, ignoreRequests and maxWait instead.', + 'Pace: ignored the eventLag option from window.paceOptions: use trackEventLag instead.', + 'Pace: ignored the elements option from window.paceOptions: use waitFor instead.', + 'Pace: ignored the document option from window.paceOptions: use trackDocument instead.', + 'Pace: ignored the restartOnPushState option from window.paceOptions: use restartOnNavigation instead.', + 'Pace: ignored the minTime option from window.paceOptions: use minVisible instead.', + 'Pace: ignored the ghostTime option from window.paceOptions: use hideDelay instead.', + ]); + expect(await page.evaluate(() => Pace.getOptions())).toEqual(DEFAULTS); + }); + + test('each problem is warned about once', async ({ page, open }) => { + const logged = warnings(page); + await open({ head: options('{ startOnPageLoad: false }') }); + await page.evaluate(() => { + Pace.configure({ minVisible: 'slow' }); + Pace.configure({ minVisible: 'slow' }); + Pace.start({ minVisible: 'slow' }); + }); + expect(logged).toEqual([ + 'Pace: ignored the minVisible option from Pace.configure(): expected a number of milliseconds from 0 to 2147483647, got string "slow".', + 'Pace: ignored the minVisible option from Pace.start(): expected a number of milliseconds from 0 to 2147483647, got string "slow".', + ]); + }); + + test('an invalid selector in target or waitFor is ignored with a warning, and pace keeps working', async ({ page, open }) => { + const logged = warnings(page); + await open({ head: options("{ trackEventLag: false, target: '#a[', waitFor: ['body', '#b['] }") }); + await idle(page); + expect(logged).toEqual([ + 'Pace: ignored the target option from window.paceOptions: expected a valid CSS selector, got string "#a[".', + 'Pace: ignored the waitFor option from window.paceOptions: expected an array of valid CSS selectors, got array containing string "#b[".', + ]); + }); + + test('Pace.start() and Pace.configure() never throw, whatever they are given', async ({ page, open }) => { + const logged = warnings(page); + await open({ head: options('{ trackEventLag: false }') }); + await idle(page); + const status = await page.evaluate(() => { + Pace.configure(5); + Pace.configure({ requestMethods: null, waitFor: '.x' }); + Pace.start(null); + // A misconfiguration must not break the page's own requests either. + const xhr = new XMLHttpRequest(); + xhr.open('GET', '/delay?ms=0'); + return new Promise((resolve) => { + xhr.onload = () => resolve(xhr.status); + xhr.send(); + }); + }); + expect(status).toBe(200); + expect(logged).toEqual([ + 'Pace: ignored the options from Pace.configure(): expected an object, got number 5.', + 'Pace: ignored the requestMethods option from Pace.configure(): expected an array of strings, got null.', + 'Pace: ignored the waitFor option from Pace.configure(): expected an array of valid CSS selectors, got string ".x".', + 'Pace: ignored the options from Pace.start(): expected an object, got null.', + ]); + }); + + test('an error from reading the options is reported, not thrown', async ({ page, open }) => { + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + await open({ head: options('{ startOnPageLoad: false }') }); + const threw = await page.evaluate(() => { + try { + Pace.configure({ className: 'before', get target() { throw new Error('getter'); }, hideDelay: 50 }); + return false; + } catch { + return true; + } + }); + expect(threw).toBe(false); + await expect.poll(() => errors).toEqual(['getter']); + // The other settings still apply. + expect(await page.evaluate(() => [Pace.getOptions().className, Pace.getOptions().hideDelay])).toEqual(['before', 50]); + }); + + test('a value is checked as it is stored: a list is read once, and an error while checking one setting skips only that one', async ({ page, open }) => { + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + await open({ head: options('{ startOnPageLoad: false }') }); + const result = await page.evaluate(() => { + // A list whose first item is 'GET' when checked and 7 afterwards. + let reads = 0; + const methods = []; + Object.defineProperty(methods, 0, { get: () => (reads++ ? 7 : 'GET'), enumerable: true }); + const revoked = Proxy.revocable({}, {}); + revoked.revoke(); + Pace.configure({ requestMethods: methods, className: 'a', target: revoked.proxy, hideDelay: 50 }); + Pace.start(); + const xhr = new XMLHttpRequest(); + xhr.open('GET', '/delay?ms=0'); + return [Pace.getOptions().requestMethods, Pace.getOptions().className, Pace.getOptions().hideDelay]; + }); + expect(result).toEqual([['GET'], 'a', 50]); + await expect.poll(() => errors.length).toBe(1); // the revoked proxy + }); + + test('ignoreRequests rejects an empty string, which would match every URL, and an object that only claims to be a RegExp', async ({ page, open }) => { + const logged = warnings(page); + await open({ head: options("{ startOnPageLoad: false }") }); + await page.evaluate(() => { + Pace.configure({ ignoreRequests: [''] }); + Pace.configure({ ignoreRequests: [{ [Symbol.toStringTag]: 'RegExp' }] }); + }); + expect(logged).toEqual([ + 'Pace: ignored the ignoreRequests option from Pace.configure(): expected an array of non-empty strings and RegExps, got array containing string "".', + 'Pace: ignored the ignoreRequests option from Pace.configure(): expected an array of non-empty strings and RegExps, got array containing RegExp.', + ]); + expect(await page.evaluate(() => Pace.getOptions().ignoreRequests)).toEqual([]); + }); + + test('an extra source is checked without reading anything from it', async ({ page, open }) => { + await open({ head: options('{ startOnPageLoad: false }') }); + const [reads, accepted] = await page.evaluate(() => { + const reads = []; + const source = new Proxy(class {}, { get: (target, key) => { reads.push(String(key)); return target[key]; } }); + Pace.configure({ extraSources: [source] }); + return [reads, Pace.getOptions().extraSources.length]; + }); + expect([reads, accepted]).toEqual([[], 1]); + }); + + test('an extra source that can\'t be constructed with new is ignored with a warning', async ({ page, open }) => { + const logged = warnings(page); + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + await open({ head: options('{ trackEventLag: false, extraSources: [() => {}] }') }); + await idle(page); + expect(errors).toEqual([]); + expect(logged).toEqual(['Pace: ignored the extraSources option from window.paceOptions: expected an array of constructors, got array containing function.']); + }); + + test('page markup that takes the name paceOptions is ignored with a warning', async ({ page, open }) => { + // A form with id="paceOptions" becomes window.paceOptions, and an input named target + // becomes its target property. + const logged = warnings(page); + await open({ head: '
' }); + await idle(page); + expect(logged).toEqual(['Pace: ignored the options from window.paceOptions: expected an object, got HTMLFormElement.']); + }); + + test('data-pace-options that is not valid JSON is ignored with a warning', async ({ page, open }) => { + const logged = warnings(page); + await open({ paceAttributes: `data-pace-options="{ className: 'a' }"` }); + expect(logged).toEqual([`Pace: ignored the options from data-pace-options: expected valid JSON, got string "{ className: 'a' }".`]); + await expect(page.locator('.pace-progress')).toHaveClass('pace-progress'); + }); +}); + +test.describe('data-pace-options', () => { + test('is read only from pace\'s own ` }); + await expect(page.locator('.pace-progress')).toHaveClass('pace-progress'); + }); + + test('is read from pace\'s own