From 6bddc5ec392135f753a6dadd25f9d3b02ea8dc8f Mon Sep 17 00:00:00 2001 From: Zachary Miller Date: Mon, 16 Nov 2026 10:30:14 -0500 Subject: [PATCH 1/2] Add Pace.version, run only the first copy of pace on a page - Pace.version is the package version. The build stamps it from package.json into pace.js, as it already does for the header, so CI's check that the build is up to date also catches a mismatch. - Pace.running is read-only: an accessor, so assigning to it does nothing (or throws in strict-mode code) instead of changing what pace reports. - Pace.bar, Pace.sources and Pace.bindings are removed: they exposed pace's internals. The event handlers live in pace's closure. - A second copy of pace on a page (another script tag or bundle) logs a warning and does nothing else; a bundled one exports the first copy. Before, it merged into window.Pace and wrapped XMLHttpRequest, fetch and history again, so the page showed two bars. The first copy is found through window[Symbol.for('pace-js')], which page markup can't replace (element names are strings), or, for Pace 1.x, which doesn't set it, a window.Pace with a start function. A copy registers itself only once it's complete. zone.js and Sentry also let the first copy win; Datadog and Lit warn about a second one. - Any other window.Pace, such as an element with id="Pace", is replaced. Before, pace added its functions to it, and a cross-origin frame named Pace stopped pace at load. --- README.md | 11 +++++ pace.js | 100 ++++++++++++++++++++++++++----------- pace.min.js | 2 +- scripts/build.mjs | 24 +++++---- tests/properties.spec.mjs | 101 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 200 insertions(+), 38 deletions(-) create mode 100644 tests/properties.spec.mjs diff --git a/README.md b/README.md index 8dbda83..22ea6ab 100644 --- a/README.md +++ b/README.md @@ -229,6 +229,17 @@ whenever `pushState` or `replaceState` is called by default. - `Pace.ignore`: Explicitly ignore one or more requests, see Tracking below +And these properties: + +- `Pace.running`: Whether a run is in progress, from `Pace.start()` until the bar is hidden or `Pace.stop()`. Read-only: +assigning to it does nothing, or throws a TypeError in strict-mode code such as modules. + +- `Pace.version`: The version of pace.js, such as `'2.0.0'`. + +If a page loads pace.js again after it's already there (a second script tag or bundle, or after Pace 1.x), the later +copy only logs a warning and the first one keeps running. Pace 1.x loaded after this version can't tell, so load only +one copy. + Events ------ diff --git a/pace.js b/pace.js index 4a923e3..05666bf 100644 --- a/pace.js +++ b/pace.js @@ -4,6 +4,46 @@ * Licensed MIT © HubSpot, Inc. and Zachary Miller */ (function () { + const VERSION = '1.3.1'; + + // Hands `value` to a module loader. False when pace was loaded by a ' }); + await idle(page); + expect(logged).toEqual([`Pace: pace.js ${version} was loaded after another copy (${version}); only the first copy runs.`]); + await clearEvents(page); + await request(page, { ms: 900 }); + await idle(page); + expect(await page.evaluate(() => events)).toEqual(RESTARTED); + await expect(page.locator('.pace')).toHaveCount(1); + }); + + test('leaves the first copy and its hooks alone', async ({ page, open }) => { + await open({ + head: NO_EVENT_LAG + ` +`, + }); + expect(await page.evaluate(() => { + const hooks = [XMLHttpRequest.prototype.open, XMLHttpRequest.prototype.send, window.fetch, window.WebSocket, history.pushState, history.replaceState]; + return window.Pace === first.Pace && hooks.every((hook, i) => hook === first.hooks[i]); + })).toBe(true); + }); + + test('finds the first copy even when window.Pace no longer points to it', async ({ page, open }) => { + const logged = warnings(page); + await open({ head: NO_EVENT_LAG + '' }); + await page.waitForFunction(() => document.querySelector('.pace.pace-inactive')); + await expect(page.locator('.pace')).toHaveCount(1); + expect(logged).toEqual([`Pace: pace.js ${version} was loaded after another copy (${version}); only the first copy runs.`]); + }); + + test('an older pace already on the page counts as a first copy', async ({ page, open }) => { + // Pace 1.x puts an object with a start function on window.Pace. + const logged = warnings(page); + await open({ head: '' }); + await page.waitForTimeout(500); + await expect(page.locator('.pace')).toHaveCount(0); + expect(await page.evaluate(() => typeof Pace.getOptions)).toBe('undefined'); + expect(logged).toEqual([`Pace: pace.js ${version} was loaded after another copy; only the first copy runs.`]); + }); + + test('loaded with a bundler, exports the first copy', async ({ page, open }) => { + await open({ head: NO_EVENT_LAG + '' }); + expect(await page.evaluate(() => [module.exports === window.Pace, module.exports.version])).toEqual([true, version]); + }); +}); From 0b769176d4584fda40c3d75711172804a771d383 Mon Sep 17 00:00:00 2001 From: Zachary Miller Date: Mon, 23 Nov 2026 10:56:49 -0500 Subject: [PATCH 2/2] Keep Pace.running right when a start fails, and correct earlier claims - An extra source that throws while pace constructs it is reported like an uncaught error (reportError), and the run goes on without it. The errors are reported once the run is set up, so an error listener that calls Pace.start() doesn't start a second run. Before, Pace.start() threw, and if a run was finishing, Pace.running stayed true and kept pace-running for good. This also covers values that pass the constructor check but still throw, such as Symbol. - The bar is added once exists, and Pace.stop() works before it does. A target that exists before , such as 'html' with pace in , threw at load and left Pace.running true; history.pushState called from after pace made the restart throw, so the page never showed the bar. - README: pace.min.js is about 5.7 kB gzipped; it said about 4 kB, which stopped being true as the file grew. The smallest theme is 0.3 kB, not 0.2. Pace.getOptions() returns the current settings; a bar that is showing keeps the non-request settings it started with. progress fires up to about 30 times a second, and restart also fires on pushState and replaceState. - The warnings for the version 1 eventLag and elements settings also say that their tuning settings and checkInterval were removed. Corrects earlier commit messages: - f46eecd: a frozen RegExp with the g flag made send() throw inside RegExp.prototype.test, which writes lastIndex; pace's own reset of lastIndex did nothing. A
stopped the bar only when it had a control named after a setting, such as target. - 6bddc5e: in Sentry, the first copy sets the shared version, but each version keeps its own state. Datadog's second copy warns, then replaces the global. Lit warns only in development builds. - 6a2c31b: a library that patched XMLHttpRequest.prototype after pace patched the plain prototype object of pace's wrapper function, so it never saw a request. WebSocket is still replaced, by a subclass, so instanceof, its constants and prototype patches keep working. Reopening a request, and sending it again from its own load handler, already worked before that commit. - b17e3c0, and the matching code comment: setTimeout treats Infinity as 0 but wraps larger numbers around 2^32 (2^32 + 300 ms fires after about 300 ms), so only 0 to 2^31 - 1 means the delay given. --- README.md | 10 ++--- pace.js | 78 +++++++++++++++++++----------------- pace.min.js | 2 +- tests/lifecycle.spec.mjs | 85 ++++++++++++++++++++++++++++++++++++---- tests/settings.spec.mjs | 4 +- 5 files changed, 128 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 22ea6ab..0d6666a 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ To change settings later, call `Pace.configure({ ... })`; `Pace.start({ ... })` 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. +copy of the current settings (a bar that is showing keeps the other settings it started with). 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. @@ -218,7 +218,7 @@ Configuration above. - `Pace.configure`: Change settings without starting the bar, see Configuration above. -- `Pace.getOptions`: A copy of the settings in use. +- `Pace.getOptions`: A copy of the current settings. - `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. @@ -247,8 +247,8 @@ Pace fires the following events: - `start`: When pace is initially started, or as a part of a restart - `stop`: When pace is manually stopped, or as a part of a restart -- `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) +- `restart`: When pace is restarted (manually, by a new AJAX request, or on `pushState` or `replaceState`) +- `progress`: While the bar is running, with the current progress (0–100), up to about 30 times a second - `done`: When pace is finished - `hide`: When the pace is hidden (can be later than `done`, based on `hideDelay` and `minVisible`) @@ -379,7 +379,7 @@ If you run into a compatibility issue, please create an issue. Size ---- -pace.min.js is about 4 kB gzipped. The themes are between 0.2 and 3.2 kB gzipped. +pace.min.js is about 5.7 kB gzipped. The themes are between 0.3 and 3.2 kB gzipped. Issues ------ diff --git a/pace.js b/pace.js index 05666bf..3d69fb5 100644 --- a/pace.js +++ b/pace.js @@ -44,7 +44,8 @@ return; } - // The longest delay a timer can wait: setTimeout treats more, and Infinity, as 0. + // The longest delay a timer can wait (2^31 - 1 ms). setTimeout treats Infinity as 0 + // and wraps larger numbers around 2^32. const MAX_DELAY = 2147483647; const isNumber = (value) => typeof value === 'number' && Number.isFinite(value); @@ -123,15 +124,15 @@ ['extraSources', [[], listOf('constructors', isConstructor)]], ]); - // Version 1 settings, and what replaced them. + // Version 1 settings, what replaced them, and what was removed. const RENAMED = new Map([ - ['ajax', 'trackXHR, trackFetch, trackWebSockets, requestMethods, ignoreRequests and maxWait'], - ['document', 'trackDocument'], - ['elements', 'waitFor'], - ['eventLag', 'trackEventLag'], - ['ghostTime', 'hideDelay'], - ['minTime', 'minVisible'], - ['restartOnPushState', 'restartOnNavigation'], + ['ajax', 'use trackXHR, trackFetch, trackWebSockets, requestMethods, ignoreRequests and maxWait instead'], + ['document', 'use trackDocument instead'], + ['elements', 'use waitFor instead (checkInterval was removed)'], + ['eventLag', 'use trackEventLag instead (its tuning settings were removed)'], + ['ghostTime', 'use hideDelay instead'], + ['minTime', 'use minVisible instead'], + ['restartOnPushState', 'use restartOnNavigation instead'], ]); // A copy of a setting's value that shares nothing that can change: a list @@ -337,7 +338,7 @@ options[name] = value; } } else if (RENAMED.has(name)) { - warn(`ignored the ${name} option from ${channel}: use ${RENAMED.get(name)} instead.`); + warn(`ignored the ${name} option from ${channel}: ${RENAMED.get(name)}.`); } else { const match = [...SETTINGS.keys()].find((known) => known.toLowerCase() === name.toLowerCase()); warn(`ignored the unknown option ${name} from ${channel}.${match ? ` Did you mean ${match}?` : ''}`); @@ -387,7 +388,7 @@ } if (this.el == null) { const targetElement = document.querySelector(this.settings.target); - if (!targetElement) { + if (!targetElement || !document.body) { return null; } this.el = document.createElement('div'); @@ -410,8 +411,8 @@ finish() { this.el?.classList.replace('pace-active', 'pace-inactive'); - document.body.classList.remove('pace-running'); - document.body.classList.add('pace-done'); + document.body?.classList.remove('pace-running'); + document.body?.classList.add('pace-done'); } update(prog) { @@ -650,9 +651,10 @@ return send.apply(this, args); } // One listener per XMLHttpRequest, added before send() because a - // synchronous request ends inside it. Every way a request ends passes - // readyState 4 (done) or, when the page aborts it from that handler, 0; - // a request in flight is always at 1 to 3. + // synchronous request ends inside it. A request that ends passes + // readyState 4 (done) or, when the page aborts it from that handler, 0, + // except a synchronous one that fails: send() throws (caught below). A + // request in flight is always at 1 to 3. if (!listening.has(this)) { listening.add(this); this.addEventListener('readystatechange', () => { @@ -1122,26 +1124,27 @@ current.collectors.push(collector); current.sources.push(collector); }; - // Built before the run counts as started: if an extra source throws, pace - // stays idle. - try { - add(new AjaxMonitor()); - if (settings.waitFor.length) { - add(new ElementMonitor(settings.waitFor)); - } - if (settings.trackDocument) { - add(new DocumentMonitor()); - } - if (settings.trackEventLag) { - add(new EventLagMonitor()); - } - const extraSources = settings.extraSources; - for (let i = 0, n = extraSources.length; i < n; i++) { + add(new AjaxMonitor()); + if (settings.waitFor.length) { + add(new ElementMonitor(settings.waitFor)); + } + if (settings.trackDocument) { + add(new DocumentMonitor()); + } + if (settings.trackEventLag) { + add(new EventLagMonitor()); + } + // An extra source that throws while it's constructed is reported once the + // run is set up (an error listener may call Pace.start), and the run goes on + // without it. + const errors = []; + const extraSources = settings.extraSources; + for (let i = 0, n = extraSources.length; i < n; i++) { + try { current.sources.push(new extraSources[i](copyOptions(settings))); + } catch (error) { + errors.push(error); } - } catch (error) { - stopCollectors(current); - throw error; } run = current; running = true; @@ -1164,6 +1167,9 @@ animate(current); }; show(); + for (const error of errors) { + reportException(error); + } }; // Request settings apply to the next request; the others from the next run. @@ -1190,8 +1196,8 @@ Pace.stop = () => { endRun(); running = false; - document.body.classList.remove('pace-running'); - document.body.classList.add('pace-done'); + document.body?.classList.remove('pace-running'); + document.body?.classList.add('pace-done'); Pace.trigger('stop'); }; diff --git a/pace.min.js b/pace.min.js index f7aaac5..37ea9f9 100644 --- a/pace.min.js +++ b/pace.min.js @@ -2,4 +2,4 @@ * pace.js v1.3.1 * https://github.com/CodeByZach/pace/ * Licensed MIT © HubSpot, Inc. and Zachary Miller - */(function(){const Y="1.3.1",K=t=>typeof define=="function"&&define.amd?(define(()=>t),!0):typeof exports=="object"?(module.exports=t,!0):!1,Z=Symbol.for("pace-js"),kt=()=>{try{return typeof window.Pace?.start=="function"?window.Pace:void 0}catch{return}},O=window[Z]??kt();if(O){const t=typeof O.version=="string"?` (${O.version})`:"";console.warn(`Pace: pace.js ${Y} was loaded after another copy${t}; only the first copy runs.`),K(O);return}const z=2147483647,$=t=>typeof t=="number"&&Number.isFinite(t),Q=t=>$(t)&&t>=0&&t<=z,tt=t=>{if(typeof t!="string")return!1;try{return document.createDocumentFragment().querySelector(t),!0}catch{return!1}},St=Object.getOwnPropertyDescriptor(RegExp.prototype,"source").get,et=t=>{try{return St.call(t),t!==RegExp.prototype}catch{return!1}},C={get length(){throw C}},xt=t=>{try{Reflect.construct(t,C)}catch(e){return e===C}},f={expected:"true or false",test:t=>typeof t=="boolean"},N={expected:`a number of milliseconds from 0 to ${z}`,test:Q},st={expected:`false or ${N.expected}`,test:t=>t===!1||Q(t)},j={expected:"a number greater than 0",test:t=>$(t)&&t>0},q=(t,e)=>({expected:`an array of ${t}`,test:Array.isArray,item:e}),w=new Map([["startOnPageLoad",[!0,f]],["restartOnNavigation",[!0,f]],["restartOnRequestAfter",[500,st]],["target",["body",{expected:"a valid CSS selector",test:tt}]],["className",["",{expected:"a string",test:t=>typeof t=="string"}]],["trackDocument",[!0,f]],["trackEventLag",[!0,f]],["waitFor",[["body"],q("valid CSS selectors",tt)]],["trackXHR",[!0,f]],["trackFetch",[!0,f]],["trackWebSockets",[!0,f]],["requestMethods",[["GET"],q("strings",t=>typeof t=="string")]],["ignoreRequests",[[],q("non-empty strings and RegExps",t=>typeof t=="string"&&t!==""||et(t))]],["maxWait",[15e3,st]],["minVisible",[250,N]],["hideDelay",[100,N]],["catchupTime",[100,j]],["initialRate",[.03,{expected:"a number of 0 or more",test:t=>$(t)&&t>=0}]],["maxProgressPerFrame",[20,j]],["easeFactor",[1.25,j]],["extraSources",[[],q("constructors",xt)]]]),rt=new Map([["ajax","trackXHR, trackFetch, trackWebSockets, requestMethods, ignoreRequests and maxWait"],["document","trackDocument"],["elements","waitFor"],["eventLag","trackEventLag"],["ghostTime","hideDelay"],["minTime","minVisible"],["restartOnPushState","restartOnNavigation"]]),nt=t=>{if(!Array.isArray(t))return t;const e=[];for(let s=0,r=t.length;s{const e={};for(const s of w.keys())e[s]=nt(t[s]);return e},a=b(Object.fromEntries([...w].map(([t,[e]])=>[t,e]))),L=t=>{if(t==null)return String(t);if(Array.isArray(t))return"array";switch(typeof t){case"string":{const e=JSON.stringify(t);return`string ${e.length>50?e.slice(0,48)+'\u2026"':e}`}case"object":return Object.prototype.toString.call(t).slice(8,-1);case"function":return"function";default:return`${typeof t} ${String(t)}`}},ot=new Set,k=t=>{t=`Pace: ${t}`,ot.has(t)||(ot.add(t),console.warn(t))},Et=(t,e)=>{if(!t.test(e))return L(e);const s=t.item?e.findIndex(r=>!t.item(r)):-1;if(s!==-1)return`array containing ${L(e[s])}`},l=()=>performance.now(),F=window.requestAnimationFrame,Rt=window.cancelAnimationFrame,it=(t,e,...s)=>typeof t[e]=="function"?t[e].apply(t,s):t[e],Ot=t=>{let e=0,s=0;for(const r of t)e+=Math.abs(r),s++;return e/s},i={};window.Pace=i;let T=!1;Object.defineProperties(i,{version:{value:Y,enumerable:!0},running:{get:()=>T,enumerable:!0}});const g=Object.create(null),ct=(t,e)=>{g[t]&&(g[t]=g[t].filter(s=>e(s)?(s.removed=!0,!1):!0))},S=t=>{typeof reportError=="function"?reportError(t):queueMicrotask(()=>{throw t})};Object.assign(i,{on(t,e,s,r){r??=!1,g[t]??=[],g[t].push({handler:e,ctx:s,once:r})},once(t,e,s){i.on(t,e,s,!0)},off(t,e){ct(t,s=>e==null||s.handler===e)},trigger(t,...e){if(g[t]){for(const s of g[t].slice())if(!s.removed){s.once&&ct(t,r=>r===s);try{s.handler.apply(s.ctx??i,e)}catch(r){S(r)}}}}});const W=(t,e)=>{if(t!==void 0)try{if(Object.prototype.toString.call(t)!=="[object Object]"){k(`ignored the options from ${e}: expected an object, got ${L(t)}.`);return}for(const s of Object.keys(t))try{const r=nt(t[s]);if(r===void 0)continue;if(w.has(s)){const[,n]=w.get(s),o=Et(n,r);o?k(`ignored the ${s} option from ${e}: expected ${n.expected}, got ${o}.`):a[s]=r}else if(rt.has(s))k(`ignored the ${s} option from ${e}: use ${rt.get(s)} instead.`);else{const n=[...w.keys()].find(o=>o.toLowerCase()===s.toLowerCase());k(`ignored the unknown option ${s} from ${e}.${n?` Did you mean ${n}?`:""}`)}}catch(r){S(r)}}catch(s){S(s)}},qt=Object.getOwnPropertyDescriptor(Document.prototype,"currentScript").get.call(document),Lt=()=>{const t=qt?.getAttribute("data-pace-options");if(t!=null)try{return JSON.parse(t)}catch{k(`ignored the options from data-pace-options: expected valid JSON, got ${L(t)}.`)}};W(window.paceOptions,"window.paceOptions"),W(Lt(),"data-pace-options"),i.getOptions=()=>b(a);class at{constructor(e){this.settings=e,this.progress=0}getElement(){if(this.destroyed)return null;if(this.el==null){const e=document.querySelector(this.settings.target);if(!e)return null;this.el=document.createElement("div"),this.el.className="pace pace-active",document.body.classList.remove("pace-done"),document.body.classList.add("pace-running");const s=document.createElement("div");s.className="pace-progress"+(this.settings.className!==""?" "+this.settings.className:"");const r=document.createElement("div");r.className="pace-progress-inner",s.appendChild(r);const n=document.createElement("div");n.className="pace-activity",this.el.appendChild(s),this.el.appendChild(n),e.insertBefore(this.el,e.firstChild)}return this.el}finish(){this.el?.classList.replace("pace-active","pace-inactive"),document.body.classList.remove("pace-running"),document.body.classList.add("pace-done")}update(e){this.progress=e,i.trigger("progress",e),this.render()}destroy(){this.el?.remove(),this.el=void 0,this.destroyed=!0}render(){if(document.querySelector(this.settings.target)==null)return;const e=this.getElement();if(e){if(e.children[0].style.transform=`translate3d(${this.progress}%, 0, 0)`,!this.lastRenderedProgress||this.lastRenderedProgress|this.progress!==0|0){e.children[0].setAttribute("data-progress-text",`${this.progress|0}%`);let s;this.progress>=100?s="99":(s=this.progress<10?"0":"",s+=this.progress|0),e.children[0].setAttribute("data-progress",s)}i.trigger("change",this.progress),this.lastRenderedProgress=this.progress}}done(){return this.progress>=100}}class Tt{constructor(){this.bindings={}}trigger(e,s){if(this.bindings[e]!=null)for(const r of this.bindings[e].slice())r.call(this,s)}on(e,s){this.bindings[e]??=[],this.bindings[e].push(s)}off(e,s){this.bindings[e]=this.bindings[e]?.filter(r=>r!==s)}}const m=[];i.ignore=(t,...e)=>{m.unshift("ignore");const s=t.apply(null,e);return m.shift(),s},i.track=(t,...e)=>{m.unshift("track");const s=t.apply(null,e);return m.shift(),s};const At={xhr:"trackXHR",fetch:"trackFetch",socket:"trackWebSockets"},D=(t,e)=>a[At[t]]?m[0]==="track"?"force":m.length?!1:t==="socket"?!0:(e=String(e??"GET").toUpperCase(),a.requestMethods.some(s=>s.toUpperCase()===e)):!1,I=(t,e)=>{const s=[String(t)];try{const r=new URL(e??s[0],document.baseURI);s.push(r.href),r.origin===location.origin&&s.push(r.pathname+r.search+r.hash)}catch{}return s},Pt=(t,e)=>typeof t=="string"?e.includes(t):(t.lastIndex=0,t.test(e)),U=t=>{const e=a.ignoreRequests;for(let s=0,r=e.length;sPt(e[s],n)))return!0;return!1},A=new Map,x=new WeakMap,_=new Set,H=t=>A.get(t.request)===t,ht=(t,e)=>{if(!H(t)){e();return}x.get(t).push(e)},u=t=>{const e=A.get(t);if(!e)return;A.delete(t);const s=x.get(e);x.delete(e);for(const r of s)r()},V=t=>{if(u(t.request),A.set(t.request,t),x.set(t,[]),a.maxWait!==!1){const e=setTimeout(()=>u(t.request),a.maxWait);x.get(t).push(()=>clearTimeout(e))}M.trigger("request",t)},P=new WeakMap,y={xhr:!1,fetch:!1,socket:!1},lt=()=>{if(a.trackXHR&&!y.xhr){y.xhr=!0;const t=window.XMLHttpRequest.prototype,e=t.open,s=t.send,r=new WeakSet;t.open=function(...n){const[o,c]=n,d=D("xhr",o),E=e.apply(this,n);return u(this),P.delete(this),d&&P.set(this,{kind:"xhr",urls:I(c),force:d==="force"}),E},t.send=function(...n){const o=P.get(this);if(P.delete(this),!o||U(o.urls))return s.apply(this,n);r.has(this)||(r.add(this),this.addEventListener("readystatechange",()=>{(this.readyState===4||this.readyState===0)&&u(this)})),V({...o,request:this});try{return s.apply(this,n)}catch(c){throw u(this),c}}}if(a.trackWebSockets&&!y.socket){y.socket=!0;const t=window.WebSocket;window.WebSocket=class extends t{constructor(s,r){r!=null?super(s,r):super(s);const n=D("socket");if(n&&!U(I(s,this.url))){for(const o of["open","error","close"])this.addEventListener(o,()=>u(this),{once:!0});V({kind:"socket",force:n==="force",request:this})}}}}if(a.trackFetch&&!y.fetch&&typeof window.fetch=="function"){y.fetch=!0;const t=window.fetch;window.fetch=function(s){const r=arguments[1];let n=null;try{const c=Object.prototype.toString.call(s)==="[object Request]",d=D("fetch",r?.method??(c?s.method:"GET"));d&&!U(I(c?s.url:s))&&(n={kind:"fetch",force:d==="force"})}catch{}const o=t.apply(this,arguments);return n?(n.request=o,V(n),o.then(c=>(u(o),c),c=>{throw u(o),c})):o}}},Mt=t=>{v()||a.restartOnRequestAfter===!1&&!t.force||(_.add(t),setTimeout(()=>{_.delete(t),H(t)&&(v()||i.restart(),X()?.watch(t))},a.restartOnRequestAfter||0))},M=new Tt;M.on("request",Mt);class ut{constructor(){this.complete=this.complete.bind(this),this.elements=[],this.onRequest=e=>this.watch(e),M.on("request",this.onRequest);for(const e of _)this.watch(e)}watch(e){if(!H(e)||this.elements.some(r=>r.event===e))return;const s=e.kind==="xhr"?$t:Ct;this.elements.push(new s(e,this.complete))}complete(e){this.elements=this.elements.filter(s=>s!==e)}openEvents(){return this.elements.map(e=>e.event)}destroy(){M.off("request",this.onRequest)}}class $t{constructor(e,s){this.event=e,this.progress=0,e.request.addEventListener("progress",r=>{r.lengthComputable?this.progress=100*r.loaded/r.total:this.progress=this.progress+(100-this.progress)/2},!1),ht(e,()=>{s(this),this.progress=100})}}class Ct{constructor(e,s){this.event=e,this.progress=0,ht(e,()=>{s(this),this.progress=100})}}class Nt{constructor(e){this.complete=this.complete.bind(this),this.elements=[],this.trackers=[];for(let s=0,r=e.length;ss!==e)}destroy(){for(const e of this.trackers)e.destroy()}}class jt{constructor(e,s){this.selector=e,this.completeCallback=s,this.progress=0,this.check()}check(){document.querySelector(this.selector)?this.done():this.timer=setTimeout(()=>this.check(),100)}destroy(){clearTimeout(this.timer)}done(){this.completeCallback(this),this.completeCallback=null,this.progress=100}}class pt{constructor(){this.progress=this.states[document.readyState]??100,this.onChange=()=>{this.states[document.readyState]!=null&&(this.progress=this.states[document.readyState])},document.addEventListener("readystatechange",this.onChange)}destroy(){document.removeEventListener("readystatechange",this.onChange)}}pt.prototype.states={loading:0,interactive:50,complete:100};class Ft{constructor(){this.progress=0;let e=0;const s=[];let r=0,n=l();const o=this.interval=setInterval(()=>{const c=l()-n-50;n=l(),s.push(c),s.length>3&&s.shift(),e=Ot(s),++r>=10&&e<3?(this.progress=100,clearInterval(o)):this.progress=100*(3/(e+3))},50)}destroy(){clearInterval(this.interval)}}class dt{constructor(e,s){this.source=e,this.settings=s,this.last=this.sinceLastUpdate=0,this.rate=s.initialRate,this.catchup=0,this.progress=this.lastProgress=0,this.source!=null&&(this.progress=it(this.source,"progress"))}tick(e,s){s??=it(this.source,"progress"),s>=100&&(this.done=!0),s===this.last?this.sinceLastUpdate+=e:(this.sinceLastUpdate&&(this.rate=(s-this.last)/this.sinceLastUpdate),this.catchup=(s-this.progress)/this.settings.catchupTime,this.sinceLastUpdate=0,this.last=s),s>this.progress&&(this.progress+=this.catchup*e);const r=1-Math.pow(this.progress/100,this.settings.easeFactor);return this.progress+=r*this.rate*e,this.progress=Math.min(this.lastProgress+this.settings.maxProgressPerFrame,this.progress),this.progress=Math.max(0,this.progress),this.progress=Math.min(100,this.progress),this.lastProgress=this.progress,this.progress}}let h=null;const X=()=>h?.collectors.find(t=>t instanceof ut);let p=new at(b(a));const v=()=>h!=null&&(h.state==="waiting"||h.state==="running"),ft=()=>{a.restartOnNavigation&&i.restart()},Wt=window.history.pushState;window.history.pushState=(...t)=>{try{ft()}catch(e){S(e)}return Wt.apply(window.history,t)};const Dt=window.history.replaceState;window.history.replaceState=(...t)=>{try{ft()}catch(e){S(e)}return Dt.apply(window.history,t)};const B=t=>{for(const e of t.collectors.splice(0))e.destroy()},gt=()=>{if(h){const t=h;h=null,Rt(t.frame),clearTimeout(t.waitTimer),clearTimeout(t.hideTimer),B(t)}p.destroy()},It=t=>{if(p.update(100),h!==t||(t.state="finishing",B(t),i.trigger("done"),h!==t))return;const e=l()-t.startedAt;t.hideTimer=setTimeout(()=>{h=null,T=!1,p.finish(),i.trigger("hide")},Math.max(t.settings.hideDelay,t.settings.minVisible-e,0))},Ut=t=>{let e=l();const s=()=>{if(h!==t)return;const r=l()-e;if(r<30){t.frame=F(s);return}e=l();let n=0,o=0,c=!0;const d=t.sources;for(let E=0,Ht=d.length;E{mt=!0,lt();const t=b(a),e={state:"waiting",settings:t,collectors:[],sources:[],scalers:new WeakMap,uniScaler:new dt(null,t)},s=n=>{e.collectors.push(n),e.sources.push(n)};try{s(new ut),t.waitFor.length&&s(new Nt(t.waitFor)),t.trackDocument&&s(new pt),t.trackEventLag&&s(new Ft);const n=t.extraSources;for(let o=0,c=n.length;o{if(h===e){if(!p.getElement()){e.waitTimer=setTimeout(r,50);return}e.state="running",e.startedAt=l(),p.render(),h===e&&(i.trigger("start"),Ut(e))}};r()},yt=(t,e)=>{W(t,e),mt&<()};i.configure=t=>{yt(t,"Pace.configure()")},i.start=t=>{yt(t,"Pace.start()"),!v()&&(gt(),_t())},i.stop=()=>{gt(),T=!1,document.body.classList.remove("pace-running"),document.body.classList.add("pace-done"),i.trigger("stop")},i.restart=()=>{i.trigger("restart");const t=X()?.openEvents()??[];i.stop(),i.start();for(const e of t)X()?.watch(e)},Object.defineProperty(window,Z,{value:i}),!K(i)&&a.startOnPageLoad&&i.start()})(); + */(function(){const J="1.3.1",Y=t=>typeof define=="function"&&define.amd?(define(()=>t),!0):typeof exports=="object"?(module.exports=t,!0):!1,K=Symbol.for("pace-js"),kt=()=>{try{return typeof window.Pace?.start=="function"?window.Pace:void 0}catch{return}},O=window[K]??kt();if(O){const t=typeof O.version=="string"?` (${O.version})`:"";console.warn(`Pace: pace.js ${J} was loaded after another copy${t}; only the first copy runs.`),Y(O);return}const Z=2147483647,$=t=>typeof t=="number"&&Number.isFinite(t),z=t=>$(t)&&t>=0&&t<=Z,Q=t=>{if(typeof t!="string")return!1;try{return document.createDocumentFragment().querySelector(t),!0}catch{return!1}},St=Object.getOwnPropertyDescriptor(RegExp.prototype,"source").get,tt=t=>{try{return St.call(t),t!==RegExp.prototype}catch{return!1}},C={get length(){throw C}},xt=t=>{try{Reflect.construct(t,C)}catch(e){return e===C}},f={expected:"true or false",test:t=>typeof t=="boolean"},N={expected:`a number of milliseconds from 0 to ${Z}`,test:z},et={expected:`false or ${N.expected}`,test:t=>t===!1||z(t)},j={expected:"a number greater than 0",test:t=>$(t)&&t>0},q=(t,e)=>({expected:`an array of ${t}`,test:Array.isArray,item:e}),k=new Map([["startOnPageLoad",[!0,f]],["restartOnNavigation",[!0,f]],["restartOnRequestAfter",[500,et]],["target",["body",{expected:"a valid CSS selector",test:Q}]],["className",["",{expected:"a string",test:t=>typeof t=="string"}]],["trackDocument",[!0,f]],["trackEventLag",[!0,f]],["waitFor",[["body"],q("valid CSS selectors",Q)]],["trackXHR",[!0,f]],["trackFetch",[!0,f]],["trackWebSockets",[!0,f]],["requestMethods",[["GET"],q("strings",t=>typeof t=="string")]],["ignoreRequests",[[],q("non-empty strings and RegExps",t=>typeof t=="string"&&t!==""||tt(t))]],["maxWait",[15e3,et]],["minVisible",[250,N]],["hideDelay",[100,N]],["catchupTime",[100,j]],["initialRate",[.03,{expected:"a number of 0 or more",test:t=>$(t)&&t>=0}]],["maxProgressPerFrame",[20,j]],["easeFactor",[1.25,j]],["extraSources",[[],q("constructors",xt)]]]),st=new Map([["ajax","use trackXHR, trackFetch, trackWebSockets, requestMethods, ignoreRequests and maxWait instead"],["document","use trackDocument instead"],["elements","use waitFor instead (checkInterval was removed)"],["eventLag","use trackEventLag instead (its tuning settings were removed)"],["ghostTime","use hideDelay instead"],["minTime","use minVisible instead"],["restartOnPushState","use restartOnNavigation instead"]]),rt=t=>{if(!Array.isArray(t))return t;const e=[];for(let s=0,r=t.length;s{const e={};for(const s of k.keys())e[s]=rt(t[s]);return e},a=S(Object.fromEntries([...k].map(([t,[e]])=>[t,e]))),L=t=>{if(t==null)return String(t);if(Array.isArray(t))return"array";switch(typeof t){case"string":{const e=JSON.stringify(t);return`string ${e.length>50?e.slice(0,48)+'\u2026"':e}`}case"object":return Object.prototype.toString.call(t).slice(8,-1);case"function":return"function";default:return`${typeof t} ${String(t)}`}},nt=new Set,x=t=>{t=`Pace: ${t}`,nt.has(t)||(nt.add(t),console.warn(t))},Et=(t,e)=>{if(!t.test(e))return L(e);const s=t.item?e.findIndex(r=>!t.item(r)):-1;if(s!==-1)return`array containing ${L(e[s])}`},u=()=>performance.now(),F=window.requestAnimationFrame,Rt=window.cancelAnimationFrame,ot=(t,e,...s)=>typeof t[e]=="function"?t[e].apply(t,s):t[e],Ot=t=>{let e=0,s=0;for(const r of t)e+=Math.abs(r),s++;return e/s},o={};window.Pace=o;let T=!1;Object.defineProperties(o,{version:{value:J,enumerable:!0},running:{get:()=>T,enumerable:!0}});const g=Object.create(null),it=(t,e)=>{g[t]&&(g[t]=g[t].filter(s=>e(s)?(s.removed=!0,!1):!0))},y=t=>{typeof reportError=="function"?reportError(t):queueMicrotask(()=>{throw t})};Object.assign(o,{on(t,e,s,r){r??=!1,g[t]??=[],g[t].push({handler:e,ctx:s,once:r})},once(t,e,s){o.on(t,e,s,!0)},off(t,e){it(t,s=>e==null||s.handler===e)},trigger(t,...e){if(g[t]){for(const s of g[t].slice())if(!s.removed){s.once&&it(t,r=>r===s);try{s.handler.apply(s.ctx??o,e)}catch(r){y(r)}}}}});const W=(t,e)=>{if(t!==void 0)try{if(Object.prototype.toString.call(t)!=="[object Object]"){x(`ignored the options from ${e}: expected an object, got ${L(t)}.`);return}for(const s of Object.keys(t))try{const r=rt(t[s]);if(r===void 0)continue;if(k.has(s)){const[,n]=k.get(s),i=Et(n,r);i?x(`ignored the ${s} option from ${e}: expected ${n.expected}, got ${i}.`):a[s]=r}else if(st.has(s))x(`ignored the ${s} option from ${e}: ${st.get(s)}.`);else{const n=[...k.keys()].find(i=>i.toLowerCase()===s.toLowerCase());x(`ignored the unknown option ${s} from ${e}.${n?` Did you mean ${n}?`:""}`)}}catch(r){y(r)}}catch(s){y(s)}},qt=Object.getOwnPropertyDescriptor(Document.prototype,"currentScript").get.call(document),Lt=()=>{const t=qt?.getAttribute("data-pace-options");if(t!=null)try{return JSON.parse(t)}catch{x(`ignored the options from data-pace-options: expected valid JSON, got ${L(t)}.`)}};W(window.paceOptions,"window.paceOptions"),W(Lt(),"data-pace-options"),o.getOptions=()=>S(a);class ct{constructor(e){this.settings=e,this.progress=0}getElement(){if(this.destroyed)return null;if(this.el==null){const e=document.querySelector(this.settings.target);if(!e||!document.body)return null;this.el=document.createElement("div"),this.el.className="pace pace-active",document.body.classList.remove("pace-done"),document.body.classList.add("pace-running");const s=document.createElement("div");s.className="pace-progress"+(this.settings.className!==""?" "+this.settings.className:"");const r=document.createElement("div");r.className="pace-progress-inner",s.appendChild(r);const n=document.createElement("div");n.className="pace-activity",this.el.appendChild(s),this.el.appendChild(n),e.insertBefore(this.el,e.firstChild)}return this.el}finish(){this.el?.classList.replace("pace-active","pace-inactive"),document.body?.classList.remove("pace-running"),document.body?.classList.add("pace-done")}update(e){this.progress=e,o.trigger("progress",e),this.render()}destroy(){this.el?.remove(),this.el=void 0,this.destroyed=!0}render(){if(document.querySelector(this.settings.target)==null)return;const e=this.getElement();if(e){if(e.children[0].style.transform=`translate3d(${this.progress}%, 0, 0)`,!this.lastRenderedProgress||this.lastRenderedProgress|this.progress!==0|0){e.children[0].setAttribute("data-progress-text",`${this.progress|0}%`);let s;this.progress>=100?s="99":(s=this.progress<10?"0":"",s+=this.progress|0),e.children[0].setAttribute("data-progress",s)}o.trigger("change",this.progress),this.lastRenderedProgress=this.progress}}done(){return this.progress>=100}}class Tt{constructor(){this.bindings={}}trigger(e,s){if(this.bindings[e]!=null)for(const r of this.bindings[e].slice())r.call(this,s)}on(e,s){this.bindings[e]??=[],this.bindings[e].push(s)}off(e,s){this.bindings[e]=this.bindings[e]?.filter(r=>r!==s)}}const w=[];o.ignore=(t,...e)=>{w.unshift("ignore");const s=t.apply(null,e);return w.shift(),s},o.track=(t,...e)=>{w.unshift("track");const s=t.apply(null,e);return w.shift(),s};const At={xhr:"trackXHR",fetch:"trackFetch",socket:"trackWebSockets"},D=(t,e)=>a[At[t]]?w[0]==="track"?"force":w.length?!1:t==="socket"?!0:(e=String(e??"GET").toUpperCase(),a.requestMethods.some(s=>s.toUpperCase()===e)):!1,I=(t,e)=>{const s=[String(t)];try{const r=new URL(e??s[0],document.baseURI);s.push(r.href),r.origin===location.origin&&s.push(r.pathname+r.search+r.hash)}catch{}return s},Pt=(t,e)=>typeof t=="string"?e.includes(t):(t.lastIndex=0,t.test(e)),U=t=>{const e=a.ignoreRequests;for(let s=0,r=e.length;sPt(e[s],n)))return!0;return!1},A=new Map,E=new WeakMap,v=new Set,_=t=>A.get(t.request)===t,at=(t,e)=>{if(!_(t)){e();return}E.get(t).push(e)},d=t=>{const e=A.get(t);if(!e)return;A.delete(t);const s=E.get(e);E.delete(e);for(const r of s)r()},H=t=>{if(d(t.request),A.set(t.request,t),E.set(t,[]),a.maxWait!==!1){const e=setTimeout(()=>d(t.request),a.maxWait);E.get(t).push(()=>clearTimeout(e))}M.trigger("request",t)},P=new WeakMap,b={xhr:!1,fetch:!1,socket:!1},ht=()=>{if(a.trackXHR&&!b.xhr){b.xhr=!0;const t=window.XMLHttpRequest.prototype,e=t.open,s=t.send,r=new WeakSet;t.open=function(...n){const[i,c]=n,l=D("xhr",i),m=e.apply(this,n);return d(this),P.delete(this),l&&P.set(this,{kind:"xhr",urls:I(c),force:l==="force"}),m},t.send=function(...n){const i=P.get(this);if(P.delete(this),!i||U(i.urls))return s.apply(this,n);r.has(this)||(r.add(this),this.addEventListener("readystatechange",()=>{(this.readyState===4||this.readyState===0)&&d(this)})),H({...i,request:this});try{return s.apply(this,n)}catch(c){throw d(this),c}}}if(a.trackWebSockets&&!b.socket){b.socket=!0;const t=window.WebSocket;window.WebSocket=class extends t{constructor(s,r){r!=null?super(s,r):super(s);const n=D("socket");if(n&&!U(I(s,this.url))){for(const i of["open","error","close"])this.addEventListener(i,()=>d(this),{once:!0});H({kind:"socket",force:n==="force",request:this})}}}}if(a.trackFetch&&!b.fetch&&typeof window.fetch=="function"){b.fetch=!0;const t=window.fetch;window.fetch=function(s){const r=arguments[1];let n=null;try{const c=Object.prototype.toString.call(s)==="[object Request]",l=D("fetch",r?.method??(c?s.method:"GET"));l&&!U(I(c?s.url:s))&&(n={kind:"fetch",force:l==="force"})}catch{}const i=t.apply(this,arguments);return n?(n.request=i,H(n),i.then(c=>(d(i),c),c=>{throw d(i),c})):i}}},Mt=t=>{X()||a.restartOnRequestAfter===!1&&!t.force||(v.add(t),setTimeout(()=>{v.delete(t),_(t)&&(X()||o.restart(),V()?.watch(t))},a.restartOnRequestAfter||0))},M=new Tt;M.on("request",Mt);class lt{constructor(){this.complete=this.complete.bind(this),this.elements=[],this.onRequest=e=>this.watch(e),M.on("request",this.onRequest);for(const e of v)this.watch(e)}watch(e){if(!_(e)||this.elements.some(r=>r.event===e))return;const s=e.kind==="xhr"?$t:Ct;this.elements.push(new s(e,this.complete))}complete(e){this.elements=this.elements.filter(s=>s!==e)}openEvents(){return this.elements.map(e=>e.event)}destroy(){M.off("request",this.onRequest)}}class $t{constructor(e,s){this.event=e,this.progress=0,e.request.addEventListener("progress",r=>{r.lengthComputable?this.progress=100*r.loaded/r.total:this.progress=this.progress+(100-this.progress)/2},!1),at(e,()=>{s(this),this.progress=100})}}class Ct{constructor(e,s){this.event=e,this.progress=0,at(e,()=>{s(this),this.progress=100})}}class Nt{constructor(e){this.complete=this.complete.bind(this),this.elements=[],this.trackers=[];for(let s=0,r=e.length;ss!==e)}destroy(){for(const e of this.trackers)e.destroy()}}class jt{constructor(e,s){this.selector=e,this.completeCallback=s,this.progress=0,this.check()}check(){document.querySelector(this.selector)?this.done():this.timer=setTimeout(()=>this.check(),100)}destroy(){clearTimeout(this.timer)}done(){this.completeCallback(this),this.completeCallback=null,this.progress=100}}class ut{constructor(){this.progress=this.states[document.readyState]??100,this.onChange=()=>{this.states[document.readyState]!=null&&(this.progress=this.states[document.readyState])},document.addEventListener("readystatechange",this.onChange)}destroy(){document.removeEventListener("readystatechange",this.onChange)}}ut.prototype.states={loading:0,interactive:50,complete:100};class Ft{constructor(){this.progress=0;let e=0;const s=[];let r=0,n=u();const i=this.interval=setInterval(()=>{const c=u()-n-50;n=u(),s.push(c),s.length>3&&s.shift(),e=Ot(s),++r>=10&&e<3?(this.progress=100,clearInterval(i)):this.progress=100*(3/(e+3))},50)}destroy(){clearInterval(this.interval)}}class dt{constructor(e,s){this.source=e,this.settings=s,this.last=this.sinceLastUpdate=0,this.rate=s.initialRate,this.catchup=0,this.progress=this.lastProgress=0,this.source!=null&&(this.progress=ot(this.source,"progress"))}tick(e,s){s??=ot(this.source,"progress"),s>=100&&(this.done=!0),s===this.last?this.sinceLastUpdate+=e:(this.sinceLastUpdate&&(this.rate=(s-this.last)/this.sinceLastUpdate),this.catchup=(s-this.progress)/this.settings.catchupTime,this.sinceLastUpdate=0,this.last=s),s>this.progress&&(this.progress+=this.catchup*e);const r=1-Math.pow(this.progress/100,this.settings.easeFactor);return this.progress+=r*this.rate*e,this.progress=Math.min(this.lastProgress+this.settings.maxProgressPerFrame,this.progress),this.progress=Math.max(0,this.progress),this.progress=Math.min(100,this.progress),this.lastProgress=this.progress,this.progress}}let h=null;const V=()=>h?.collectors.find(t=>t instanceof lt);let p=new ct(S(a));const X=()=>h!=null&&(h.state==="waiting"||h.state==="running"),pt=()=>{a.restartOnNavigation&&o.restart()},Wt=window.history.pushState;window.history.pushState=(...t)=>{try{pt()}catch(e){y(e)}return Wt.apply(window.history,t)};const Dt=window.history.replaceState;window.history.replaceState=(...t)=>{try{pt()}catch(e){y(e)}return Dt.apply(window.history,t)};const ft=t=>{for(const e of t.collectors.splice(0))e.destroy()},gt=()=>{if(h){const t=h;h=null,Rt(t.frame),clearTimeout(t.waitTimer),clearTimeout(t.hideTimer),ft(t)}p.destroy()},It=t=>{if(p.update(100),h!==t||(t.state="finishing",ft(t),o.trigger("done"),h!==t))return;const e=u()-t.startedAt;t.hideTimer=setTimeout(()=>{h=null,T=!1,p.finish(),o.trigger("hide")},Math.max(t.settings.hideDelay,t.settings.minVisible-e,0))},Ut=t=>{let e=u();const s=()=>{if(h!==t)return;const r=u()-e;if(r<30){t.frame=F(s);return}e=u();let n=0,i=0,c=!0;const l=t.sources;for(let m=0,_t=l.length;m<_t;m++){const wt=l[m],bt=wt.elements??[wt];for(let B=0,Ht=bt.length;B{mt=!0,ht();const t=S(a),e={state:"waiting",settings:t,collectors:[],sources:[],scalers:new WeakMap,uniScaler:new dt(null,t)},s=c=>{e.collectors.push(c),e.sources.push(c)};s(new lt),t.waitFor.length&&s(new Nt(t.waitFor)),t.trackDocument&&s(new ut),t.trackEventLag&&s(new Ft);const r=[],n=t.extraSources;for(let c=0,l=n.length;c{if(h===e){if(!p.getElement()){e.waitTimer=setTimeout(i,50);return}e.state="running",e.startedAt=u(),p.render(),h===e&&(o.trigger("start"),Ut(e))}};i();for(const c of r)y(c)},yt=(t,e)=>{W(t,e),mt&&ht()};o.configure=t=>{yt(t,"Pace.configure()")},o.start=t=>{yt(t,"Pace.start()"),!X()&&(gt(),vt())},o.stop=()=>{gt(),T=!1,document.body?.classList.remove("pace-running"),document.body?.classList.add("pace-done"),o.trigger("stop")},o.restart=()=>{o.trigger("restart");const t=V()?.openEvents()??[];o.stop(),o.start();for(const e of t)V()?.watch(e)},Object.defineProperty(window,K,{value:o}),!Y(o)&&a.startOnPageLoad&&o.start()})(); diff --git a/tests/lifecycle.spec.mjs b/tests/lifecycle.spec.mjs index 15a464b..a86ecfc 100644 --- a/tests/lifecycle.spec.mjs +++ b/tests/lifecycle.spec.mjs @@ -1,5 +1,6 @@ // What starting, stopping, restarting and finishing a run do. Each run fires start, // done and hide once; stop() and restart() end the current run completely. +import fs from 'node:fs'; import { test, expect, idle, request, clearEvents, RESTARTED, HOLD, NO_EVENT_LAG } from './fixtures.mjs'; // Like HOLD, plus other options. @@ -244,14 +245,84 @@ test('Pace.stop() while the bar first renders means no start event', async ({ pa expect(await page.evaluate(() => [events, Pace.running])).toEqual([['stop'], false]); }); -test('an extra source that throws neither leaves pace stuck nor breaks navigation', async ({ page, open }) => { +test('an extra source that throws is reported, and the run goes on without it', async ({ page, open }) => { const errors = []; page.on('pageerror', (error) => errors.push(error.message)); - await open({ head: "" }); - const [search, running] = await page.evaluate(() => { - history.pushState({}, '', '?next'); - return [location.search, Pace.running]; + await open({ head: "" }); + // The working source after the two that throw still holds the bar. + await page.waitForTimeout(500); + await expect(page.locator('.pace')).toHaveClass('pace pace-active'); + await page.evaluate(() => { hold.progress = 100; }); + await idle(page); + await clearEvents(page); + await page.evaluate(() => { history.pushState({}, '', '?next'); hold.progress = 100; }); + await idle(page); + expect(await page.evaluate(() => [location.search, events, Pace.running])).toEqual(['?next', RESTARTED, false]); + // Each source, at load and on the navigation. + await expect.poll(() => errors.length).toBe(4); +}); + +test('Pace.start() while a run is finishing never throws or leaves Pace.running stuck', async ({ page, open }) => { + await open({ head: "" }); + await page.waitForFunction(() => events.includes('done')); + const [finishing, threw] = await page.evaluate(() => { + const finishing = Pace.running && !events.includes('hide'); + try { + Pace.start({ hideDelay: 0, extraSources: [function () { throw new Error('source'); }] }); + return [finishing, false]; + } catch { + return [finishing, true]; + } }); - expect([search, running]).toEqual(['?next', false]); - await expect.poll(() => errors.length).toBe(2); // at load, and on the navigation + expect([finishing, threw]).toEqual([true, false]); + await expect.poll(() => page.evaluate(() => [Pace.running, document.body.className]), { timeout: 5000 }).toEqual([false, 'pace-done']); +}); + +test('a target that exists before gets the bar once exists', async ({ page, open }) => { + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + await open({ head: "" }); + await idle(page); + expect(await page.evaluate(() => [document.querySelector('.pace').parentElement.tagName, Pace.running])).toEqual(['HTML', false]); + expect(errors).toEqual([]); +}); + +test('an error listener that restarts pace while a source error is reported leaves one bar', async ({ page, open }) => { + await open({ + head: ``, + }); + await idle(page); + await clearEvents(page); + await page.evaluate(() => { window.restartOnError = true; Pace.restart(); }); + await idle(page); + await expect(page.locator('.pace')).toHaveCount(1); + expect(await page.evaluate(() => Pace.running)).toBe(false); +}); + +test('history.pushState before exists restarts the bar', async ({ page, paceFile }) => { + // A router that sets the URL from a script in , after pace. + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + const pace = fs.readFileSync(new URL(`../${paceFile}`, import.meta.url), 'utf8'); + await page.route('http://pace.test/**', (route) => (new URL(route.request().url()).pathname === '/pace.js' + ? route.fulfill({ contentType: 'text/javascript', body: pace }) + : route.fulfill({ + contentType: 'text/html', + body: ` + + + +

page

`, + }))); + await page.goto('http://pace.test/'); + await idle(page); + expect(await page.evaluate(() => events)).toEqual(RESTARTED); + expect(errors).toEqual([]); }); diff --git a/tests/settings.spec.mjs b/tests/settings.spec.mjs index 51986a1..29252a3 100644 --- a/tests/settings.spec.mjs +++ b/tests/settings.spec.mjs @@ -202,8 +202,8 @@ test.describe('wrong values and unknown names', () => { 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 eventLag option from window.paceOptions: use trackEventLag instead (its tuning settings were removed).', + 'Pace: ignored the elements option from window.paceOptions: use waitFor instead (checkInterval was removed).', '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.',