@stacksjs/testing 0.75.572 → 0.75.573
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +12 -7
- package/package.json +15 -15
package/dist/browser.js
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{randomUUID as
|
|
2
|
+
import{randomUUID as He}from"crypto";import{closeSync as Ue,existsSync as we,mkdtempSync as je,openSync as Je,readSync as Ve,rmSync as X,statSync as We}from"fs";import{availableParallelism as Ge,freemem as Ke,loadavg as ze,tmpdir as Ye,totalmem as Xe}from"os";import{join as Q}from"path";import j from"process";import{spawnOwnedProcess as Qe}from"@stacksjs/cli/owned-process";import{createHash as qe}from"crypto";import{existsSync as M,lstatSync as Fe,mkdirSync as ke,mkdtempSync as Oe,readdirSync as D,readFileSync as De,readlinkSync as oe,renameSync as W,rmSync as G,writeFileSync as Le}from"fs";import{tmpdir as Ae}from"os";import{basename as K,join as w}from"path";import O from"process";var ae=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"],Ie=["google-chrome","google-chrome-stable","chromium","chromium-browser","chrome"],ce=["KSProductID","KSUpdateURL","KSChannelID","KSVersion"],ie="dev.stacks.testing.chrome";function le(){if(O.env.CHROME_PATH)return O.env.CHROME_PATH;if(O.platform==="darwin"){let e=ae.find((t)=>M(t));if(e)return e}for(let e of Ie){let t=Bun.which(e);if(t)return t}return null}function ue(e){let t=/^(.*?\.app)\/Contents\/MacOS\/[^/]+$/.exec(e);return t?t[1]:null}function q(e,t){let r=Bun.spawnSync(["/usr/libexec/PlistBuddy","-c",t,e],{stdout:"pipe",stderr:"pipe"});return{ok:r.exitCode===0,out:r.stdout.toString().trim()}}function de(e){let t=ue(e);if(!t||O.platform!=="darwin")return!1;let r=w(t,"Contents/Info.plist");return M(r)&&ce.some((n)=>q(r,`Print :${n}`).ok)}function pe(e){let t=[];for(let r of D(e,{withFileTypes:!0})){if(!r.isDirectory())continue;let n=w(e,r.name);if(t.push(...pe(n)),!r.name.endsWith(".framework")||!M(w(n,"Versions")))continue;let s=q(w(n,"Resources/Info.plist"),"Print :CFBundleIdentifier");if(!s.ok||!s.out)throw Error(`Framework has no signing identifier: ${n}`);for(let i of D(w(n,"Versions"),{withFileTypes:!0}).filter((o)=>o.isDirectory()).sort((o,c)=>o.name.localeCompare(c.name)))t.push({path:w(n,"Versions",i.name),identifier:s.out})}return t}function z(e){let t=[];for(let r of D(e,{withFileTypes:!0})){if(!r.isDirectory())continue;let n=w(e,r.name);t.push(...z(n));let s=w(n,"Versions");if(!r.name.endsWith(".framework")||!M(s))continue;let i;try{i=K(oe(w(s,"Current")))}catch{continue}if(!M(w(s,i)))continue;for(let o of D(s,{withFileTypes:!0}))if(o.isDirectory()&&o.name!==i)t.push(w(s,o.name))}return t}function Ne(e){return Bun.spawnSync(["codesign","--verify","--deep","--strict",e],{stdout:"pipe",stderr:"pipe"}).exitCode===0}function me(e){let t=[],r=(n,s)=>{for(let i of D(n,{withFileTypes:!0}).sort((o,c)=>o.name<c.name?-1:o.name>c.name?1:0)){let o=w(n,i.name),c=`${s}${i.name}`;if(i.isSymbolicLink()){t.push(`${c} link ${oe(o)}`);continue}if(i.isDirectory()){r(o,`${c}/`);continue}let a=Fe(o,{bigint:!0});t.push(`${c} file ${a.size} ${a.mtimeNs}`)}};return r(e,""),qe("sha256").update(t.join(`
|
|
3
|
+
`)).digest("hex")}var Y=(e)=>`${e}.verified`,he="stacks-chrome-verified-1";function _e(e){try{return De(Y(e),"utf8")===`${he}
|
|
4
|
+
${me(e)}
|
|
5
|
+
`}catch{return!1}}function fe(e){let t=`${Y(e)}.${O.pid}`;try{Le(t,`${he}
|
|
6
|
+
${me(e)}
|
|
7
|
+
`),W(t,Y(e))}catch{G(t,{force:!0})}}function Be(e){if(_e(e))return!0;if(!Ne(e))return!1;return fe(e),!0}function ge(e={}){if(O.platform!=="darwin")throw Error("prepareMacChrome is for macOS; elsewhere launch Chrome as installed");let t=e.source??ae[0],r=ue(t);if(!r||!M(r))throw Error(`No Chrome app bundle at ${t}`);let n=w(r,"Contents/Info.plist"),s=q(n,"Print :CFBundleShortVersionString").out||"unknown",i=q(n,"Print :CFBundleExecutable").out||"Google Chrome",o=e.directory??w(Ae(),`stacks-chrome-${s.replace(/[^\w.-]/g,"_")}`),c=w(o,"Chrome.app"),a=M(o)?D(o,{withFileTypes:!0}).filter((d)=>d.isDirectory()&&(d.name==="Chrome.app"||d.name.startsWith("Chrome-")&&d.name.endsWith(".app"))).map((d)=>w(o,d.name)).sort():[];for(let d of a){let u=w(d,"Contents/MacOS",i),f=w(d,"Contents/Info.plist");if(M(u)&&q(f,"Print :CFBundleIdentifier").out===ie&&q(f,"Print :CFBundleShortVersionString").out===s&&z(d).length===0&&Be(d))return{executable:u,app:d,reused:!0}}ke(o,{recursive:!0});let l=Oe(w(o,"staging-")),m=w(l,"Chrome.app"),g=(d,u)=>{let f=Bun.spawnSync(d,{stdout:"pipe",stderr:"pipe"});if(f.exitCode!==0)throw Error(`${u} failed: ${f.stderr.toString().trim()}`)};try{g(["/bin/cp","-cR",r,m],"Cloning Chrome"),g(["/usr/bin/xattr","-cr",m],"Clearing extended attributes");let d=w(m,"Contents/Info.plist");for(let p of ce)q(d,`Delete :${p}`);g(["/usr/libexec/PlistBuddy","-c",`Set :CFBundleIdentifier ${ie}`,d],"Renaming the Chrome bundle");for(let p of z(m))G(p,{recursive:!0,force:!0});let u=pe(m);for(let p of u)g(["codesign","--force","--deep","--sign","-",p.path],"Re-signing framework code");for(let p of u)g(["codesign","--force","--sign","-","--requirements",`=designated => identifier ${JSON.stringify(p.identifier)}`,p.path],"Sealing a framework version");g(["codesign","--force",...u.length?[]:["--deep"],"--sign","-",m],"Sealing Chrome"),g(["codesign","--verify","--deep","--strict",m],"Verifying Chrome");let f=M(c)?w(o,`Chrome-${K(l)}.app`):c;try{W(m,f)}catch(p){if(f!==c||!["EEXIST","ENOTEMPTY"].includes(p.code??""))throw p;f=w(o,`Chrome-${K(l)}.app`),W(m,f)}return fe(f),{executable:w(f,"Contents/MacOS",i),app:f,reused:!1}}finally{G(l,{recursive:!0,force:!0})}}async function te(e,t=12000,r={}){let n=Date.now(),s=await e();while(!s&&Date.now()-n<t)await Bun.sleep(r.intervalMs??100),s=await e();if(!s)throw Error(`Timed out after ${t}ms${r.label?` waiting for ${r.label}`:""}`);return s}async function Ft(e,t,r={}){let n=typeof t==="string"?t:t.selector,s=typeof t==="string"?void 0:t.text,i=r.timeoutMs??12000,o=`an enabled, unobscured ${n}${s===void 0?"":` named ${JSON.stringify(s)}`}`,c=Date.now()+i,a=`__stacksTestingClick${He().replaceAll("-","")}`,l=`${a}Stop`,m=0,g,d=()=>g,u,f=e.on("Runtime.bindingCalled",(y)=>{if(y.name!==a)return;let h=JSON.parse(y.payload);if(h.attempt!==m)return;if(g=h,h.clicked||h.blocked)u?.(h)}),p=(y=!1)=>e.evaluate(`window[${JSON.stringify(l)}]?.(${y})`);try{let y=!1;await te(async()=>{if(!y)await e.send("Runtime.addBinding",{name:a}),y=!0;m++,g=void 0;let h=await e.evaluate(`(async () => {
|
|
3
8
|
const matches = [...document.querySelectorAll(${JSON.stringify(n)})].filter(node => ${s===void 0?"true":`node.textContent.trim() === ${JSON.stringify(s)}`})
|
|
4
9
|
if (matches.length > 1) throw new Error('Ambiguous click target: ' + ${JSON.stringify(n)})
|
|
5
10
|
const node = matches[0]
|
|
@@ -55,10 +60,10 @@ import{randomUUID as $e}from"crypto";import{closeSync as qe,existsSync as ue,mkd
|
|
|
55
60
|
} })
|
|
56
61
|
events.forEach(type => window.addEventListener(type, intercept, { capture: true, passive: false }))
|
|
57
62
|
return { x, y }
|
|
58
|
-
})()`);if(!h)return null;let v=!1,C;try{await e.send("Input.dispatchMouseEvent",{type:"mousePressed",...h,button:"left",clickCount:1}),await e.send("Input.dispatchMouseEvent",{type:"mouseReleased",...h,button:"left",clickCount:1}),v=!0;let
|
|
59
|
-
Chrome startup: ${JSON.stringify(t)}`,{cause:e});this.diagnostics=t;this.name="ChromeLaunchError"}}async function
|
|
63
|
+
})()`);if(!h)return null;let v=!1,C;try{await e.send("Input.dispatchMouseEvent",{type:"mousePressed",...h,button:"left",clickCount:1}),await e.send("Input.dispatchMouseEvent",{type:"mouseReleased",...h,button:"left",clickCount:1}),v=!0;let T=d(),L=T&&(T.clicked||T.blocked)?T:await new Promise((A,_)=>{u=A,C=setTimeout(()=>_(Error(`Timed out after ${i}ms waiting for ${o}: input delivery was not verified`)),Math.max(0,c-Date.now()))});if(L.clicked)return!0;if(L.accepted)throw Error(`Click target changed after input delivery began: ${n}`);return null}catch(T){if(!v&&!d()?.clicked)await p(!0).catch(()=>{}),await e.send("Input.dispatchMouseEvent",{type:"mouseReleased",...h,button:"left",clickCount:1}).catch(()=>{});throw T}finally{if(clearTimeout(C),u=void 0,d()?.clicked)p().catch(()=>{});else await p()}},i,{label:o})}finally{f(),p().catch(()=>{}),await e.send("Runtime.removeBinding",{name:a}).catch(()=>{}),e.evaluate(`delete window[${JSON.stringify(a)}]`).catch(()=>{})}}var Ze=new Set(["Fetch.continueRequest","Fetch.fulfillRequest","Fetch.failRequest","Fetch.continueResponse"]);function et(e,t){let r="";for(let n=0;n<e.length;n++){let s=e[n];if(s==="\\"&&n+1<e.length)r+=be(e[++n]);else if(s==="*")r+="[\\s\\S]*";else if(s==="?")r+="[\\s\\S]";else r+=be(s)}return new RegExp(`^${r}$`).test(t)}function be(e){return e.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}function ve(e,t){let r=t.responseStatusCode!=null||t.responseErrorReason!=null?"Response":"Request";if((e.requestStage??"Request")!==r)return!1;if(e.resourceType&&e.resourceType!==t.resourceType)return!1;return et(e.urlPattern??"*",t.request?.url??"")}class Te{socket;id=0;pending=new Map;listeners=new Map;commandTimeoutMs;interceptors=[];ownFetch=null;answered=new Map;frameLoaders=new Map;requestLoaders=new Map;speculativeRequests=new Set;errors=[];inFlight=new Map;get foregroundInFlight(){return new Map([...this.inFlight].filter(([e])=>!this.speculativeRequests.has(e)))}closed=!1;closeCause;socketFailure;constructor(e,t={}){this.socket=e;this.commandTimeoutMs=t.commandTimeoutMs??30000,e.addEventListener("close",(r)=>this.markClosed({origin:"remote",code:r.code,reason:r.reason,wasClean:r.wasClean,transportError:this.socketFailure})),e.addEventListener("error",(r)=>{let n=r;this.socketFailure??={message:n.message,error:n.error}}),e.addEventListener("message",(r)=>this.receive(String(r.data)))}closedError(){let e=this.closeCause,t;if(e instanceof Error)t=e.message;else if(e)t=JSON.stringify({origin:e.origin,code:e.code,reason:e.reason,wasClean:e.wasClean,transportError:e.transportError?{message:e.transportError.message}:void 0});return Error(`Chrome closed the connection${t?`: ${t}`:""}`,{cause:e})}markClosed(e){if(this.closed)return;this.closed=!0,this.closeCause=e,this.frameLoaders.clear(),this.requestLoaders.clear();for(let[t,r]of this.pending)clearTimeout(r.timer),r.reject(this.closedError()),this.pending.delete(t)}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(t.id){let r=this.pending.get(t.id);if(!r)return;if(this.pending.delete(t.id),clearTimeout(r.timer),t.error)r.reject(Error(t.error.message));else r.resolve(t.result);return}if(this.track(t.method,t.params??{}),t.method==="Fetch.requestPaused"&&!this.routePaused(t.params??{}))return;this.dispatch(t.method,t.params??{})}dispatch(e,t){for(let r of[...this.listeners.get(e)??[]])try{r(t)}catch(n){this.errors.push(`Listener for ${e} threw: ${n?.message??String(n)}`)}}routePaused(e){this.remember(e.requestId,!1);let t=this.interceptors.filter((s)=>s.patterns.some((i)=>ve(i,e)));for(let s of t)try{let i=s.handler(e,this);if(i&&typeof i.catch==="function")i.catch((o)=>this.errors.push(`Fetch handler threw: ${o?.message??String(o)}`))}catch(i){this.errors.push(`Fetch handler threw: ${i?.message??String(i)}`)}let r=(this.listeners.get("Fetch.requestPaused")?.size??0)>0,n=this.ownFetch?this.ownFetch.patterns.some((s)=>ve(s,e)):!1;if(!t.length&&!n&&!r)this.send("Fetch.continueRequest",{requestId:e.requestId}).catch(()=>{});return r&&(n||!t.length)}remember(e,t){if(this.answered.delete(e),this.answered.set(e,t),this.answered.size>2000){for(let[r]of this.answered)if(this.answered.delete(r),this.answered.size<=1000)break}}async applyFetch(){let e=[...this.interceptors.flatMap((t)=>t.patterns),...this.ownFetch?.patterns??[]];if(!e.length)return await this.command("Fetch.disable");return await this.command("Fetch.enable",{...this.ownFetch?.params,patterns:e})}async intercept(e,t){if(!e.length)throw TypeError("intercept needs at least one pattern");let r={patterns:e.map((s)=>({...s})),handler:t};this.interceptors.push(r);try{await this.applyFetch()}catch(s){throw this.interceptors=this.interceptors.filter((i)=>i!==r),s}let n=!1;return async()=>{if(n)return;if(n=!0,this.interceptors=this.interceptors.filter((s)=>s!==r),!this.closed)await this.applyFetch()}}finishRequest(e){this.inFlight.delete(e),this.requestLoaders.delete(e),this.speculativeRequests.delete(e)}retireFrameRequests(e,t){for(let[r,n]of this.requestLoaders)if(n.frameId===e&&(t===void 0||n.loaderId===t))this.finishRequest(r)}track(e,t){if(e==="Network.requestWillBeSent"){let{requestId:r,frameId:n,loaderId:s}=t;if(this.requestLoaders.delete(r),this.speculativeRequests.delete(r),t.type==="Prefetch"||Object.entries(t.request?.headers??{}).some(([o,c])=>/^(?:sec-)?purpose$/i.test(o)&&String(c).split(/[\s;,]+/).some((a)=>a.toLowerCase()==="prefetch")))this.speculativeRequests.add(r);if(n&&s)this.requestLoaders.set(r,{frameId:n,loaderId:s});this.inFlight.set(t.requestId,`${t.request?.method} ${t.request?.url}`)}else if(e==="Network.loadingFinished"||e==="Network.loadingFailed")this.finishRequest(t.requestId);else if(e==="Network.responseReceived"&&t.response?.mimeType==="text/event-stream")this.finishRequest(t.requestId);else if(e==="Page.frameNavigated"&&t.frame?.id&&t.frame?.loaderId){let{id:r,loaderId:n}=t.frame,s=this.frameLoaders.get(r);if(s&&s!==n)this.retireFrameRequests(r,s);this.frameLoaders.set(r,n)}else if(e==="Page.frameDetached"&&t.reason==="remove")this.frameLoaders.delete(t.frameId),this.retireFrameRequests(t.frameId);if(e==="Runtime.exceptionThrown")this.errors.push(t.exceptionDetails?.exception?.description||t.exceptionDetails?.text||"Runtime exception");else if(e==="Runtime.consoleAPICalled"&&t.type==="error")this.errors.push((t.args||[]).map((r)=>r.value??r.description??"").join(" "));else if(e==="Log.entryAdded"&&t.entry?.level==="error"&&!String(t.entry.text).includes("favicon"))this.errors.push(t.entry.text);else if(e==="Network.loadingFailed"&&!t.canceled)this.errors.push(`Network: ${t.errorText||"request failed"}`)}on(e,t){let r=this.listeners.get(e);if(!r)this.listeners.set(e,r=new Set);return r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t)}once(e,t=()=>!0,r=this.commandTimeoutMs){return new Promise((n,s)=>{if(this.closed)return s(this.closedError());let i=setTimeout(()=>{c(),clearInterval(o),s(Error(`Timed out after ${r}ms waiting for ${e}`))},r),o=setInterval(()=>{if(!this.closed)return;clearTimeout(i),clearInterval(o),c(),s(this.closedError())},100),c=this.on(e,(a)=>{if(!t(a))return;clearTimeout(i),clearInterval(o),c(),n(a)})})}send(e,t={}){if(e==="Fetch.enable"){let{patterns:r,...n}=t;return this.ownFetch={patterns:r?.length?r.map((s)=>({...s})):[{urlPattern:"*"}],params:n},this.closed?this.command(e,t):this.applyFetch()}if(e==="Fetch.disable")return this.ownFetch=null,this.closed?this.command(e,t):this.applyFetch();if(Ze.has(e)&&typeof t.requestId==="string"){if(this.answered.get(t.requestId)===!0)return Promise.resolve({});if(this.answered.has(t.requestId))this.remember(t.requestId,!0)}return this.command(e,t)}command(e,t={}){let r=++this.id;return new Promise((n,s)=>{if(this.closed)return s(this.closedError());let i=setTimeout(()=>{this.pending.delete(r),s(Error(`Chrome command timed out: ${e}`))},this.commandTimeoutMs);this.pending.set(r,{resolve:n,reject:s,timer:i}),this.socket.send(JSON.stringify({id:r,method:e,params:t}))})}async evaluate(e){let t=await this.send("Runtime.evaluate",{expression:e,awaitPromise:!0,returnByValue:!0});if(t.exceptionDetails)throw Error(t.exceptionDetails.exception?.description||t.exceptionDetails.text);return t.result?.value}disconnect(){this.markClosed(Error("CDP session disconnected by caller"));try{this.socket.close()}catch{}}}async function re(e,t={}){let r=new WebSocket(e);return await new Promise((n,s)=>{let i=(l)=>{if(clearTimeout(a),r.removeEventListener("open",o),r.removeEventListener("error",c),r.removeEventListener("close",c),l){try{r.close()}catch{}s(l)}else n()},o=()=>i(),c=()=>i(Error(`Could not connect to Chrome at ${e}`)),a=setTimeout(()=>i(Error(`Timed out connecting to Chrome at ${e}`)),t.connectTimeoutMs??30000);r.addEventListener("open",o,{once:!0}),r.addEventListener("error",c,{once:!0}),r.addEventListener("close",c,{once:!0})}),new Te(r,t)}function tt(){return le()}function rt(e){return de(e)}function nt(e={}){return ge(e)}function R(e,t){e.phase=t,e.phaseStartedMs[t]=Date.now()-e.started}function ye(){return{cpuCount:Ge(),loadAverage:ze(),freeMemory:Ke(),totalMemory:Xe(),...j.platform==="linux"?{linux:Object.fromEntries(Object.entries({cpuPressure:"/proc/pressure/cpu",memoryPressure:"/proc/pressure/memory",ioPressure:"/proc/pressure/io",cpuQuota:"/sys/fs/cgroup/cpu.max",cpuStat:"/sys/fs/cgroup/cpu.stat",memoryEvents:"/sys/fs/cgroup/memory.events"}).map(([e,t])=>[e,U(t)]))}:{}}}class ee extends Error{diagnostics;constructor(e,t){super(`${e instanceof Error?e.message:String(e)}
|
|
64
|
+
Chrome startup: ${JSON.stringify(t)}`,{cause:e});this.diagnostics=t;this.name="ChromeLaunchError"}}async function Z(e,t){let r;try{return await Promise.race([e.then(()=>!0),new Promise((n)=>{r=setTimeout(()=>n(!1),t)})])}finally{clearTimeout(r)}}function U(e){let t;try{t=Je(e,"r");let r=Buffer.alloc(1024);return r.subarray(0,Ve(t,r,0,r.length,0)).toString("utf8")}catch{return null}finally{if(t!==void 0)try{Ue(t)}catch{}}}var st=["*/_stx/hmr*"];async function it(e,t=st){if(!t.length)return async()=>{};return await e.intercept(t.map((r)=>({urlPattern:r})),(r,n)=>{n.send("Fetch.fulfillRequest",{requestId:r.requestId,responseCode:200,responseHeaders:[{name:"Content-Type",value:"text/event-stream"}],body:Buffer.from(`retry: 86400000
|
|
60
65
|
|
|
61
|
-
`).toString("base64")}).catch(()=>{})})}var
|
|
62
|
-
[stderr read failed: ${String(E)}]`.slice(-16384)}),
|
|
63
|
-
`);if(k&&C===null)C=E-s.started;return k},
|
|
64
|
-
`),F=Number(P);if(!Number.isInteger(F)||F<1||F>65535)throw Error("Chrome wrote an invalid DevToolsActivePort");return{pid:l,chromePath:t,profile:
|
|
66
|
+
`).toString("base64")}).catch(()=>{})})}var Ce=new Map;function ot(e){let t=e.chromePath??j.env.CHROME_PATH;if(t)return t;let r=tt();if(!r)throw Error("No Chrome found: install Google Chrome or Chromium, or set CHROME_PATH");if((e.stableMacChrome??!0)&&j.platform==="darwin"&&rt(r)){let s=Ce.get(r);if(s&&[...N.values()].some((o)=>o.chromePath===s&&!o.exited()))return s;let i=nt({source:r}).executable;return Ce.set(r,i),i}return r}async function Re(e,t,r,n,s){R(s,"process-start");let i=ye();if(!we(t))throw Error(`Chrome was not found at ${t}`);let o=e.profile||je(Q(Ye(),"stacks-browser-"));X(Q(o,"DevToolsActivePort"),{force:!0});let c=Q(o,"DevToolsActivePort"),a,l=null,m,g;try{a=Qe([t,...e.headless===!1?[]:["--headless=new"],"--remote-debugging-port=0",`--user-data-dir=${o}`,"--no-first-run","--no-default-browser-check","--disable-background-networking","--disable-component-update","--disable-extensions","--hide-scrollbars","--use-mock-keychain",...e.args??[],"about:blank"],{stdin:"ignore",stdout:"ignore",stderr:"pipe",stopGraceMs:2000}),a.exited.then((b)=>{m=b},(b)=>{g=b}),l=await I(a.started,Math.max(1,n-(Date.now()-r)),"starting Chrome owner")}catch(b){let S=null;try{if(await a?.stop(),!e.profile)X(o,{recursive:!0,force:!0})}catch(P){S=String(P)}throw new ee(b,{pid:l,chromePath:t,profile:o,temporaryProfile:!e.profile,elapsedMs:Date.now()-r,phase:s.phase,phaseStartedMs:{...s.phaseStartedMs},exitCodeBeforeCleanup:null,signalCodeBeforeCleanup:null,exitCode:null,signalCode:null,portFileExisted:!1,portFileContents:null,stderrTail:"",stderrTruncated:!1,cleanupError:S})}let d=a,u="",f=!1,p,y=Promise.resolve(),h,v=()=>h??=(async()=>{let b=!1,S=[];try{await d.stop(),b=!0}catch(P){S.push(String(P)),b=!1}finally{try{if(!await Z(y,100)&&p){if(!await Z(p.cancel(),100))throw Error("Chrome stderr cancellation did not finish")}if(!await Z(y,100))throw Error("Chrome stderr reader did not finish")}catch(P){S.push(String(P))}finally{if(b&&!e.profile)try{X(o,{recursive:!0,force:!0})}catch(P){S.push(String(P))}}}if(S.length)throw Error(`Chrome cleanup failed: ${S.join("; ")}`)})(),C=null,T=0,L=()=>m!==void 0||g!==void 0,A=()=>{let b=n-(Date.now()-r);if(b<=0)throw Error(`Timed out after ${n}ms starting Chrome`);if(L())throw Error("Chrome exited during startup");return b},_=async(b,S,P=s)=>{let J=Date.now()-P.started,F=P.phase,E={...P.phaseStartedMs},k=m?.code??null,B=m?.signal??null,H=we(c),$e=U(c),ne=null;try{ne=We(c).mtimeMs-P.started}catch{}let Me=ye(),se=null;if(S)try{await v()}catch(V){se=V instanceof Error?V.message:String(V)}return new ee(b,{pid:l,chromePath:t,profile:o,temporaryProfile:!e.profile,elapsedMs:J,phase:F,phaseStartedMs:E,exitCodeBeforeCleanup:k,signalCodeBeforeCleanup:B,exitCode:m?.code??null,signalCode:m?.signal??null,portFileExisted:H,portFileContents:$e,portFileModifiedAfterStartMs:ne,portFileObservedMs:C,maxPortPollGapMs:T,resourcesAtStart:i,resourcesAtFailure:Me,stderrTail:u,stderrTruncated:f,cleanupError:se})};try{p=d.stderr.getReader();let b=p;y=(async()=>{let E=new TextDecoder;for(;;){let{value:k,done:B}=await b.read(),H=E.decode(k,{stream:!B});if(f||=u.length+H.length>16384,u=(u+H).slice(-16384),B)return}})().catch((E)=>{u=`${u}
|
|
67
|
+
[stderr read failed: ${String(E)}]`.slice(-16384)}),R(s,"devtools-port");let S=Date.now();await te(()=>{let E=Date.now();T=Math.max(T,E-S),S=E,A();let k=U(c)?.includes(`
|
|
68
|
+
`);if(k&&C===null)C=E-s.started;return k},A(),{label:"Chrome to start"});let[P,J=""]=(U(c)??"").split(`
|
|
69
|
+
`),F=Number(P);if(!Number.isInteger(F)||F<1||F>65535)throw Error("Chrome wrote an invalid DevToolsActivePort");return{pid:l,chromePath:t,profile:o,port:F,browserPath:J.trim(),remaining:A,close:v,failure:_,exited:L}}catch(b){throw await _(b,!0)}}async function I(e,t,r){let n;try{return await Promise.race([e,new Promise((s,i)=>{n=setTimeout(()=>i(Error(`Timed out after ${t}ms ${r}`)),t)})])}finally{clearTimeout(n)}}async function Ee(e,t){if(await Promise.all([e.send("Page.enable"),e.send("Runtime.enable"),e.send("Network.enable"),e.send("Log.enable"),...t.viewport===!1?[]:[e.send("Emulation.setDeviceMetricsOverride",{deviceScaleFactor:1,mobile:!1,width:1440,height:1000,...t.viewport})]]),t.userAgent!==!1){let r=typeof t.userAgent==="string"?t.userAgent:String((await e.send("Browser.getVersion")).userAgent||"").replace("HeadlessChrome","Chrome");if(r)await e.send("Network.setUserAgentOverride",{userAgent:r})}if(t.quietLiveReload!==!1)await it(e,t.quietLiveReload);if(t.acceptDialogs!==!1)e.on("Page.javascriptDialogOpening",(r)=>{e.errors.push(`Dialog (${r.type}) on ${r.url}: ${r.message||"(no message)"}`),e.send("Page.handleJavaScriptDialog",{accept:!0}).catch(()=>{})})}var at=1500,x=new Map,N=new Map;async function kt(){let e=[...x.values()];x.clear(),await Promise.allSettled(e.map(async(t)=>{let r=await t;if(clearTimeout(r.linger),r.browser.disconnect(),await r.chrome.close(),r.chrome.pid!==null)N.delete(r.chrome.pid)}))}async function ct(e,t,r,n,s,i){let o=x.get(e);if(o){let a=s-(Date.now()-n);if(a<=0)throw Error(`Timed out after ${s}ms starting Chrome`);let l=await I(o.catch(()=>null),a,"waiting for shared Chrome");if(l&&!l.browser.closed&&!l.chrome.exited())return clearTimeout(l.linger),l.sessions++,l;if(x.get(e)===o)x.delete(e)}let c=(async()=>{let a=await Re(t,r,n,s,i);if(a.pid!==null)N.set(a.pid,{profile:a.profile,chromePath:a.chromePath,exited:a.exited});try{if(!a.browserPath.startsWith("/devtools/browser/"))throw Error("Chrome wrote no browser endpoint in DevToolsActivePort");R(i,"browser-connect");let l=await re(`ws://127.0.0.1:${a.port}${a.browserPath}`,{...t,connectTimeoutMs:Math.min(t.connectTimeoutMs??30000,a.remaining())});return{chrome:a,browser:l,sessions:0}}catch(l){if(a.pid!==null)N.delete(a.pid);throw await a.failure(l,!0)}})();x.set(e,c);try{let a=await c;return a.sessions++,a}catch(a){if(x.get(e)===c)x.delete(e);throw a}}function Pe(e,t,r=!1){if(t.sessions=Math.max(0,t.sessions-1),t.sessions>0)return Promise.resolve();let n=async()=>{if(t.sessions>0)return;let s=x.get(e),i=s&&await s.catch(()=>null);if(t.sessions>0)return;if(i===t&&x.get(e)===s)x.delete(e);if(t.browser.disconnect(),await t.chrome.close(),t.chrome.pid!==null)N.delete(t.chrome.pid)};if(r)return n();return clearTimeout(t.linger),t.linger=setTimeout(()=>{n().catch(()=>{})},at),Promise.resolve()}async function lt(e,t,r,n,s){let i=JSON.stringify([t,e.headless!==!1,e.args??[]]),o=await ct(i,e,t,r,n,s),c=()=>{let g=n-(Date.now()-r);if(g<=0)throw Error(`Timed out after ${n}ms starting Chrome`);return g},a,l,m=async()=>{if(a&&!o.browser.closed)await o.browser.send("Target.disposeBrowserContext",{browserContextId:a}).catch(()=>{})};try{R(s,"context-create"),a=(await I(o.browser.send("Target.createBrowserContext",{disposeOnDetach:!1}),c(),"creating a browser context")).browserContextId,R(s,"target-create");let{targetId:g}=await I(o.browser.send("Target.createTarget",{url:"about:blank",browserContextId:a}),c(),"opening a page"),d=`ws://127.0.0.1:${o.chrome.port}/devtools/page/${g}`;R(s,"page-connect");let u=l=await re(d,{...e,connectTimeoutMs:Math.min(e.connectTimeoutMs??30000,c())});R(s,"page-prepare"),await I(Ee(u,e),c(),"preparing the page"),c();let f;return{cdp:u,close:()=>f??=(async()=>{u.disconnect(),await m(),await Pe(i,o)})(),target:d,port:o.chrome.port,chromePath:t}}catch(g){l?.disconnect(),await m();let d=o.sessions<=1,u=await o.chrome.failure(g,!1,s);throw await Pe(i,o,d).catch((f)=>{u.diagnostics.cleanupError=f instanceof Error?f.message:String(f)}),u}}async function ut(e,t,r,n,s){let i=await Re(e,t,r,n,s),o,c,a=()=>c??=(async()=>{o?.disconnect(),await i.close()})(),l=setTimeout(()=>o?.disconnect(),Math.max(1,n-(Date.now()-r)));try{let m=i.port;R(s,"target-discovery");let g=await te(async()=>{let u=await fetch(`http://127.0.0.1:${m}/json/list`,{signal:AbortSignal.timeout(Math.min(1000,i.remaining()))}).then((f)=>f.json()).catch(()=>[]);return Array.isArray(u)&&u.length?u:null},Math.min(12000,i.remaining()),{label:"a page target"}),d=g.find((u)=>u.type==="page"&&u.url==="about:blank")||g.find((u)=>u.type==="page");if(!d)throw Error("Chrome did not expose a page target");return R(s,"page-connect"),o=await re(d.webSocketDebuggerUrl,{...e,connectTimeoutMs:Math.min(e.connectTimeoutMs??30000,i.remaining())}),i.remaining(),R(s,"page-prepare"),await Ee(o,e),i.remaining(),clearTimeout(l),{cdp:o,close:a,target:d.webSocketDebuggerUrl,port:m,chromePath:t}}catch(m){throw clearTimeout(l),o?.disconnect(),await i.failure(m,!0)}}async function dt(e={}){let t=e.startTimeoutMs??30000;if(!Number.isFinite(t)||t<=0)throw RangeError("startTimeoutMs must be positive and finite");let r=ot(e),n=Date.now(),s={started:n,phase:"process-acquire",phaseStartedMs:{"process-acquire":0}};return!e.profile&&e.shared!==!1&&j.env.STACKS_BROWSER_SHARED!=="0"?await lt(e,r,n,t,s):await ut(e,r,n,t,s)}async function pt(e,t={}){let r=t.quietMs??1000,n=t.timeoutMs??15000,s=Date.now(),i=0;while(Date.now()-s<n){if(e.closed)throw Error("Chrome closed the connection");if((t.includeSpeculative===!1?e.foregroundInFlight:e.inFlight).size>0||await e.evaluate("document.readyState !== 'complete'").catch(()=>!0))i=0;else if(!i)i=Date.now();else if(Date.now()-i>=r)return!0;await Bun.sleep(100)}return!1}async function mt(e,t,r={}){let n=await e.send("Page.navigate",{url:t});if(n?.errorText)throw Error(`Could not open ${t}: ${n.errorText}`);return await pt(e,r)}var ht=(e)=>e.pathname.startsWith("/api/")&&!e.pathname.endsWith("/events");function ft(e){let t={};for(let r of e)t[r]=(t[r]||0)+1;return Object.fromEntries(Object.entries(t).filter(([,r])=>r>1))}function Se(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e.replace(/[?#].*$/,"")}}function gt(e,t,r="navigation"){let n=[{url:e,apiRequests:[]}],s=!1;for(let i of t){let o=n.at(-1);if(i.type==="request"){o.apiRequests.push(i.request);continue}let c=r==="navigation"&&s&&(i.sameDocument?Se(i.url)!==Se(o.url):!0);if(s=!0,c)n.push({url:i.url,apiRequests:[]});else o.url=i.url}return n.map((i)=>({...i,duplicates:ft(i.apiRequests)}))}function wt(e){let t={};for(let r of e)for(let[n,s]of Object.entries(r.duplicates))t[n]=Math.max(t[n]??0,s);return t}async function Ot(e,t={}){let r=Date.now(),n=new URL(e).origin,s=t.isApiRequest??ht,i=[],o=[],c=[],a=null,l=t.cdp,m=[],g=l?.errors.length??0,d,u=e,f=async(p,y=[])=>{let h=gt(e,o,t.pageLoads),v=u;if(l&&!l.closed){let C=await l.evaluate("location.href").catch(()=>null);if(C&&C!=="about:blank"&&!C.startsWith("chrome-error:"))v=C}return{url:e,finalUrl:v,apiRequests:i,duplicates:wt(h),loads:h,failed:c,errors:[...l?.errors.slice(g)??[],...y],settled:p,durationMs:Date.now()-r}};try{if(!l)a=await dt(t.launch),l=a.cdp;let p=l;if(m.push(p.on("Network.requestWillBeSent",(h)=>{let v=new URL(h.request.url);if(v.origin===n&&s(v,h.request.method)){let C=`${h.request.method} ${v.pathname}${v.search}`;i.push(C),o.push({type:"request",request:C})}})),m.push(p.on("Network.responseReceived",(h)=>{let v=new URL(h.response.url);if(v.origin===n&&h.response.status>=400)c.push(`${h.response.status} ${v.pathname}`)})),m.push(p.on("Page.frameNavigated",(h)=>{if(h.frame?.parentId)return;d=h.frame?.id??d,u=h.frame?.unreachableUrl||`${h.frame?.url??u}${h.frame?.urlFragment??""}`,o.push({type:"navigated",url:u,sameDocument:!1})})),m.push(p.on("Page.navigatedWithinDocument",(h)=>{if(d&&h.frameId!==d)return;u=h.url,o.push({type:"navigated",url:h.url,sameDocument:!0})})),await p.send("Page.enable"),d=(await p.send("Page.getFrameTree").catch(()=>null))?.frameTree?.frame?.id,t.viewport)await p.send("Emulation.setDeviceMetricsOverride",{deviceScaleFactor:1,mobile:!1,...t.viewport});await t.beforeNavigate?.(p);let y=await mt(p,e,t);return await f(y)}catch(p){return await f(!1,[`audit: ${p?.message??String(p)}`])}finally{for(let p of m)p();await a?.close().catch(()=>{})}}function xe(e){try{let t=new URL(e);return`${t.pathname}${t.search}`}catch{return e}}function Dt(e){let t=xe(e.url),r=e.finalUrl?xe(e.finalUrl):t,n=Object.entries(e.duplicates).map(([s,i])=>`${i}x ${s}`);return`${t}${r!==t?` -> ${r}`:""}: ${e.apiRequests.length} api${n.length?` | dup ${n.join(", ")}`:""}${e.failed.length?` | failed ${e.failed.join(", ")}`:""}${e.errors.length?` | errors ${e.errors.slice(0,3).join(" ; ")}`:""}${e.settled?"":" | never settled"}`}function Lt(e){return e.settled&&!Object.keys(e.duplicates).length&&!e.failed.length&&!e.errors.length}export{Te as Cdp,ee as ChromeLaunchError,st as LIVE_RELOAD_PATTERNS,at as SHARED_CHROME_LINGER_MS,Ot as auditPage,rt as chromeHasUpdater,Ft as click,kt as closeSharedBrowsers,re as connect,ft as duplicateRequests,tt as findChrome,Dt as formatPageAudit,dt as launch,wt as loadDuplicates,et as matchesUrlPattern,mt as navigate,Lt as pageAuditClean,ve as pausedRequestMatches,nt as prepareMacChrome,it as quietLiveReload,pt as settle,gt as splitPageLoads,te as waitFor};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/testing",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.573",
|
|
6
6
|
"description": "The Stacks way of testing.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -91,24 +91,24 @@
|
|
|
91
91
|
"prepublishOnly": "bun run build"
|
|
92
92
|
},
|
|
93
93
|
"dependencies": {
|
|
94
|
-
"@stacksjs/auth": "0.75.
|
|
95
|
-
"@stacksjs/cache": "0.75.
|
|
96
|
-
"@stacksjs/cli": "0.75.
|
|
97
|
-
"@stacksjs/config": "0.75.
|
|
98
|
-
"@stacksjs/database": "0.75.
|
|
99
|
-
"@stacksjs/email": "0.75.
|
|
100
|
-
"@stacksjs/events": "0.75.
|
|
101
|
-
"@stacksjs/hq": "0.75.
|
|
102
|
-
"@stacksjs/path": "0.75.
|
|
103
|
-
"@stacksjs/router": "0.75.
|
|
104
|
-
"@stacksjs/server": "0.75.
|
|
105
|
-
"@stacksjs/storage": "0.75.
|
|
106
|
-
"@stacksjs/strings": "0.75.
|
|
94
|
+
"@stacksjs/auth": "0.75.573",
|
|
95
|
+
"@stacksjs/cache": "0.75.573",
|
|
96
|
+
"@stacksjs/cli": "0.75.573",
|
|
97
|
+
"@stacksjs/config": "0.75.573",
|
|
98
|
+
"@stacksjs/database": "0.75.573",
|
|
99
|
+
"@stacksjs/email": "0.75.573",
|
|
100
|
+
"@stacksjs/events": "0.75.573",
|
|
101
|
+
"@stacksjs/hq": "0.75.573",
|
|
102
|
+
"@stacksjs/path": "0.75.573",
|
|
103
|
+
"@stacksjs/router": "0.75.573",
|
|
104
|
+
"@stacksjs/server": "0.75.573",
|
|
105
|
+
"@stacksjs/storage": "0.75.573",
|
|
106
|
+
"@stacksjs/strings": "0.75.573",
|
|
107
107
|
"@stacksjs/ts-cloud": "^0.16.125",
|
|
108
108
|
"very-happy-dom": "^0.4.1"
|
|
109
109
|
},
|
|
110
110
|
"devDependencies": {
|
|
111
111
|
"@dtsx/dtsx": "^0.11.54",
|
|
112
|
-
"better-dx": "^0.2.
|
|
112
|
+
"better-dx": "^0.2.39"
|
|
113
113
|
}
|
|
114
114
|
}
|