@stacksjs/testing 0.75.621 → 0.75.623
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.d.ts +1 -0
- package/dist/browser.js +11 -11
- package/dist/index.js +7 -7
- package/package.json +15 -15
package/dist/browser.d.ts
CHANGED
package/dist/browser.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{randomUUID as He}from"crypto";import{closeSync as Ue,existsSync as
|
|
3
|
-
`)).digest("hex")}var
|
|
2
|
+
import{randomUUID as He}from"crypto";import{closeSync as Ue,existsSync as ve,mkdtempSync as je,openSync as Je,readSync as Ve,rmSync as Q,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 Z}from"path";import j from"process";import{spawnOwnedProcess as Qe}from"@stacksjs/cli/owned-process";import{createHash as Fe}from"crypto";import{existsSync as M,lstatSync as qe,mkdirSync as ke,mkdtempSync as Oe,readdirSync as D,readFileSync as De,readlinkSync as ae,renameSync as G,rmSync as K,writeFileSync as Le}from"fs";import{tmpdir as Ae}from"os";import{basename as z,join as w}from"path";import O from"process";var ce=["/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"],le=["KSProductID","KSUpdateURL","KSChannelID","KSVersion"],oe="dev.stacks.testing.chrome";function ue(){if(O.env.CHROME_PATH)return O.env.CHROME_PATH;if(O.platform==="darwin"){let e=ce.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 de(e){let t=/^(.*?\.app)\/Contents\/MacOS\/[^/]+$/.exec(e);return t?t[1]:null}function F(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 pe(e){let t=de(e);if(!t||O.platform!=="darwin")return!1;let r=w(t,"Contents/Info.plist");return M(r)&&le.some((n)=>F(r,`Print :${n}`).ok)}function he(e){let t=[];for(let r of D(e,{withFileTypes:!0})){if(!r.isDirectory())continue;let n=w(e,r.name);if(t.push(...he(n)),!r.name.endsWith(".framework")||!M(w(n,"Versions")))continue;let s=F(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 Y(e){let t=[];for(let r of D(e,{withFileTypes:!0})){if(!r.isDirectory())continue;let n=w(e,r.name);t.push(...Y(n));let s=w(n,"Versions");if(!r.name.endsWith(".framework")||!M(s))continue;let i;try{i=z(ae(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 ${ae(o)}`);continue}if(i.isDirectory()){r(o,`${c}/`);continue}let a=qe(o,{bigint:!0});t.push(`${c} file ${a.size} ${a.mtimeNs}`)}};return r(e,""),Fe("sha256").update(t.join(`
|
|
3
|
+
`)).digest("hex")}var X=(e)=>`${e}.verified`,fe="stacks-chrome-verified-1";function _e(e){try{return De(X(e),"utf8")===`${fe}
|
|
4
4
|
${me(e)}
|
|
5
|
-
`}catch{return!1}}function
|
|
5
|
+
`}catch{return!1}}function ge(e){let t=`${X(e)}.${O.pid}`;try{Le(t,`${fe}
|
|
6
6
|
${me(e)}
|
|
7
|
-
`),
|
|
7
|
+
`),G(t,X(e))}catch{K(t,{force:!0})}}function Be(e){if(_e(e))return!0;if(!Ne(e))return!1;return ge(e),!0}function we(e={}){if(O.platform!=="darwin")throw Error("prepareMacChrome is for macOS; elsewhere launch Chrome as installed");let t=e.source??ce[0],r=de(t);if(!r||!M(r))throw Error(`No Chrome app bundle at ${t}`);let n=w(r,"Contents/Info.plist"),s=F(n,"Print :CFBundleShortVersionString").out||"unknown",i=F(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((p)=>p.isDirectory()&&(p.name==="Chrome.app"||p.name.startsWith("Chrome-")&&p.name.endsWith(".app"))).map((p)=>w(o,p.name)).sort():[];for(let p of a){let u=w(p,"Contents/MacOS",i),f=w(p,"Contents/Info.plist");if(M(u)&&F(f,"Print :CFBundleIdentifier").out===oe&&F(f,"Print :CFBundleShortVersionString").out===s&&Y(p).length===0&&Be(p))return{executable:u,app:p,reused:!0}}ke(o,{recursive:!0});let l=Oe(w(o,"staging-")),h=w(l,"Chrome.app"),g=(p,u)=>{let f=Bun.spawnSync(p,{stdout:"pipe",stderr:"pipe"});if(f.exitCode!==0)throw Error(`${u} failed: ${f.stderr.toString().trim()}`)};try{g(["/bin/cp","-cR",r,h],"Cloning Chrome"),g(["/usr/bin/xattr","-cr",h],"Clearing extended attributes");let p=w(h,"Contents/Info.plist");for(let d of le)F(p,`Delete :${d}`);g(["/usr/libexec/PlistBuddy","-c",`Set :CFBundleIdentifier ${oe}`,p],"Renaming the Chrome bundle");for(let d of Y(h))K(d,{recursive:!0,force:!0});let u=he(h);for(let d of u)g(["codesign","--force","--deep","--sign","-",d.path],"Re-signing framework code");for(let d of u)g(["codesign","--force","--sign","-","--requirements",`=designated => identifier ${JSON.stringify(d.identifier)}`,d.path],"Sealing a framework version");g(["codesign","--force",...u.length?[]:["--deep"],"--sign","-",h],"Sealing Chrome"),g(["codesign","--verify","--deep","--strict",h],"Verifying Chrome");let f=M(c)?w(o,`Chrome-${z(l)}.app`):c;try{G(h,f)}catch(d){if(f!==c||!["EEXIST","ENOTEMPTY"].includes(d.code??""))throw d;f=w(o,`Chrome-${z(l)}.app`),G(h,f)}return ge(f),{executable:w(f,"Contents/MacOS",i),app:f,reused:!1}}finally{K(l,{recursive:!0,force:!0})}}async function re(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 kt(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`,h=0,g,p=()=>g,u,f=e.on("Runtime.bindingCalled",(y)=>{if(y.name!==a)return;let m=JSON.parse(y.payload);if(m.attempt!==h)return;if(g=m,m.clicked||m.blocked)u?.(m)}),d=(y=!1)=>e.evaluate(`window[${JSON.stringify(l)}]?.(${y})`);try{let y=!1;await re(async()=>{if(!y)await e.send("Runtime.addBinding",{name:a}),y=!0;h++,g=void 0;let m=await e.evaluate(`(async () => {
|
|
8
8
|
const matches = [...document.querySelectorAll(${JSON.stringify(n)})].filter(node => ${s===void 0?"true":`node.textContent.trim() === ${JSON.stringify(s)}`})
|
|
9
9
|
if (matches.length > 1) throw new Error('Ambiguous click target: ' + ${JSON.stringify(n)})
|
|
10
10
|
const node = matches[0]
|
|
@@ -28,7 +28,7 @@ ${me(e)}
|
|
|
28
28
|
const y = Math.max(0, Math.min(innerHeight - 1, rect.y + rect.height / 2))
|
|
29
29
|
const hit = document.elementFromPoint(x, y)
|
|
30
30
|
if (!hit || !node.contains(hit)) return null
|
|
31
|
-
const state = { attempt: ${
|
|
31
|
+
const state = { attempt: ${h}, accepted: 0, clicked: false, blocked: false }
|
|
32
32
|
const events = ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']
|
|
33
33
|
const detach = () => events.forEach(type => window.removeEventListener(type, intercept, true))
|
|
34
34
|
const report = () => window[${JSON.stringify(a)}](JSON.stringify(state))
|
|
@@ -60,10 +60,10 @@ ${me(e)}
|
|
|
60
60
|
} })
|
|
61
61
|
events.forEach(type => window.addEventListener(type, intercept, { capture: true, passive: false }))
|
|
62
62
|
return { x, y }
|
|
63
|
-
})()`);if(!
|
|
64
|
-
Chrome startup: ${JSON.stringify(t)}`,{cause:e});this.diagnostics=t;this.name="ChromeLaunchError"}}async function
|
|
63
|
+
})()`);if(!m)return null;let b=!1,C;try{await e.send("Input.dispatchMouseEvent",{type:"mousePressed",...m,button:"left",clickCount:1}),await e.send("Input.dispatchMouseEvent",{type:"mouseReleased",...m,button:"left",clickCount:1}),b=!0;let T=p(),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(!b&&!p()?.clicked)await d(!0).catch(()=>{}),await e.send("Input.dispatchMouseEvent",{type:"mouseReleased",...m,button:"left",clickCount:1}).catch(()=>{});throw T}finally{if(clearTimeout(C),u=void 0,p()?.clicked)d().catch(()=>{});else await d()}},i,{label:o})}finally{f(),d().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 ye(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)=>ye(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)=>ye(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 ne(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 ue()}function rt(e){return pe(e)}function nt(e={}){return we(e)}function R(e,t){e.phase=t,e.phaseStartedMs[t]=Date.now()-e.started}function Ce(){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 te 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 ee(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
|
|
65
65
|
|
|
66
|
-
`).toString("base64")}).catch(()=>{})})}var
|
|
67
|
-
[stderr read failed: ${String(E)}]`.slice(-16384)}),R(s,"devtools-port");let S=Date.now();await
|
|
68
|
-
`);if(k&&C===null)C=E-s.started;return k},A(),{label:"Chrome to start"});let[P,
|
|
69
|
-
`),
|
|
66
|
+
`).toString("base64")}).catch(()=>{})})}var Pe=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=Pe.get(r);if(s&&[...N.values()].some((o)=>o.chromePath===s&&!o.exited()))return s;let i=nt({source:r}).executable;return Pe.set(r,i),i}return r}async function Re(e,t,r,n,s){R(s,"process-start");let i=Ce();if(!ve(t))throw Error(`Chrome was not found at ${t}`);let o=e.profile||je(Z(Ye(),"stacks-browser-"));Q(Z(o,"DevToolsActivePort"),{force:!0});let c=Z(o,"DevToolsActivePort"),a,l=null,h,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((v)=>{h=v},(v)=>{g=v}),l=await I(a.started,Math.max(1,n-(Date.now()-r)),"starting Chrome owner")}catch(v){let S=null;try{if(await a?.stop(),!e.profile)Q(o,{recursive:!0,force:!0})}catch(P){S=String(P)}throw new te(v,{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 p=a,u="",f=!1,d,y=Promise.resolve(),m,b=()=>m??=(async()=>{let v=!1,S=[];try{await p.stop(),v=!0}catch(P){S.push(String(P)),v=!1}finally{try{if(!await ee(y,100)&&d){if(!await ee(d.cancel(),100))throw Error("Chrome stderr cancellation did not finish")}if(!await ee(y,100))throw Error("Chrome stderr reader did not finish")}catch(P){S.push(String(P))}finally{if(v&&!e.profile)try{Q(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=()=>h!==void 0||g!==void 0,A=()=>{let v=n-(Date.now()-r);if(v<=0)throw Error(`Timed out after ${n}ms starting Chrome`);if(L())throw Error("Chrome exited during startup");return v},_=async(v,S,P=s)=>{let V=Date.now()-P.started,q=P.phase,E={...P.phaseStartedMs},k=h?.code??null,B=h?.signal??null,H=ve(c),$e=U(c),se=null;try{se=We(c).mtimeMs-P.started}catch{}let Me=Ce(),ie=null;if(S)try{await b()}catch(W){ie=W instanceof Error?W.message:String(W)}return new te(v,{pid:l,chromePath:t,profile:o,temporaryProfile:!e.profile,elapsedMs:V,phase:q,phaseStartedMs:E,exitCodeBeforeCleanup:k,signalCodeBeforeCleanup:B,exitCode:h?.code??null,signalCode:h?.signal??null,portFileExisted:H,portFileContents:$e,portFileModifiedAfterStartMs:se,portFileObservedMs:C,maxPortPollGapMs:T,resourcesAtStart:i,resourcesAtFailure:Me,stderrTail:u,stderrTruncated:f,cleanupError:ie})};try{d=p.stderr.getReader();let v=d;y=(async()=>{let E=new TextDecoder;for(;;){let{value:k,done:B}=await v.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 re(()=>{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,V=""]=(U(c)??"").split(`
|
|
69
|
+
`),q=Number(P);if(!Number.isInteger(q)||q<1||q>65535)throw Error("Chrome wrote an invalid DevToolsActivePort");return{pid:l,chromePath:t,profile:o,port:q,browserPath:V.trim(),remaining:A,close:b,failure:_,exited:L}}catch(v){throw await _(v,!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 Ot(){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 ne(`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 Se(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,h=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"),p=`ws://127.0.0.1:${o.chrome.port}/devtools/page/${g}`;R(s,"page-connect");let u=l=await ne(p,{...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 h(),await Se(i,o)})(),target:p,port:o.chrome.port,chromePath:t}}catch(g){l?.disconnect(),await h();let p=o.sessions<=1,u=await o.chrome.failure(g,!1,s);throw await Se(i,o,p).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 h=i.port;R(s,"target-discovery");let g=await re(async()=>{let u=await fetch(`http://127.0.0.1:${h}/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"}),p=g.find((u)=>u.type==="page"&&u.url==="about:blank")||g.find((u)=>u.type==="page");if(!p)throw Error("Chrome did not expose a page target");return R(s,"page-connect"),o=await ne(p.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:p.webSocketDebuggerUrl,port:h,chromePath:t}}catch(h){throw clearTimeout(l),o?.disconnect(),await i.failure(h,!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 ht(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 mt=(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 xe(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?xe(i.url)!==xe(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 Dt(e,t={}){let r=Date.now(),n=new URL(e).origin,s=t.isApiRequest??mt,i=[],o=[],c=[],a=null,l=t.cdp,h=[],g=l?.errors.length??0,p,u=e,f=async(d,y=[])=>{let m=gt(e,o,t.pageLoads),b=u;if(l&&!l.closed){let C=await l.evaluate("location.href").catch(()=>null);if(C&&C!=="about:blank"&&!C.startsWith("chrome-error:"))b=C}return{url:e,finalUrl:b,apiRequests:i,duplicates:wt(m),loads:m,failed:c,errors:[...l?.errors.slice(g)??[],...y],settled:d,stalled:d||!l?[]:[...(t.includeSpeculative===!1?l.foregroundInFlight:l.inFlight).values()],durationMs:Date.now()-r}};try{if(!l)a=await dt(t.launch),l=a.cdp;let d=l;if(h.push(d.on("Network.requestWillBeSent",(m)=>{let b=new URL(m.request.url);if(b.origin===n&&s(b,m.request.method)){let C=`${m.request.method} ${b.pathname}${b.search}`;i.push(C),o.push({type:"request",request:C})}})),h.push(d.on("Network.responseReceived",(m)=>{let b=new URL(m.response.url);if(b.origin===n&&m.response.status>=400)c.push(`${m.response.status} ${b.pathname}`)})),h.push(d.on("Page.frameNavigated",(m)=>{if(m.frame?.parentId)return;p=m.frame?.id??p,u=m.frame?.unreachableUrl||`${m.frame?.url??u}${m.frame?.urlFragment??""}`,o.push({type:"navigated",url:u,sameDocument:!1})})),h.push(d.on("Page.navigatedWithinDocument",(m)=>{if(p&&m.frameId!==p)return;u=m.url,o.push({type:"navigated",url:m.url,sameDocument:!0})})),await d.send("Page.enable"),p=(await d.send("Page.getFrameTree").catch(()=>null))?.frameTree?.frame?.id,t.viewport)await d.send("Emulation.setDeviceMetricsOverride",{deviceScaleFactor:1,mobile:!1,...t.viewport});await t.beforeNavigate?.(d);let y=await ht(d,e,t);return await f(y)}catch(d){return await f(!1,[`audit: ${d?.message??String(d)}`])}finally{for(let d of h)d();await a?.close().catch(()=>{})}}function J(e){try{let t=new URL(e);return`${t.pathname}${t.search}`}catch{return e}}function vt(e){let t=e.indexOf(" ");return t<0?J(e):`${e.slice(0,t)} ${J(e.slice(t+1))}`}function Lt(e){let t=J(e.url),r=e.finalUrl?J(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${e.stalled.length?`, waiting on ${e.stalled.map(vt).join(", ")}`:""}`}`}function At(e){return e.settled&&!Object.keys(e.duplicates).length&&!e.failed.length&&!e.errors.length}export{Te as Cdp,te as ChromeLaunchError,st as LIVE_RELOAD_PATTERNS,at as SHARED_CHROME_LINGER_MS,Dt as auditPage,rt as chromeHasUpdater,kt as click,Ot as closeSharedBrowsers,ne as connect,ft as duplicateRequests,tt as findChrome,Lt as formatPageAudit,dt as launch,wt as loadDuplicates,et as matchesUrlPattern,ht as navigate,At as pageAuditClean,ye as pausedRequestMatches,nt as prepareMacChrome,it as quietLiveReload,pt as settle,gt as splitPageLoads,re as waitFor};
|
package/dist/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
`).join(""),l},withEnv(u){return n={...n,...u},l},withCwd(u){return
|
|
4
|
-
`);let
|
|
2
|
+
import{mkdtempSync as j,rmSync as B}from"fs";import{tmpdir as M}from"os";import{join as H,relative as G}from"path";import w from"process";function J(){w.env.NODE_ENV="test",w.env.APP_ENV="test",Q()}function Q(){if(w.env.STACKS_HOME)return;let t=j(H(M(),"stacks-home-"));w.env.STACKS_HOME=t,w.once("exit",()=>B(t,{recursive:!0,force:!0}))}async function ke(){if(J(),z())return;let{injectGlobalAutoImports:t}=await import("@stacksjs/server");await t()}function z(t=w.argv[1]??"",e=w.cwd()){return G(e,t).replaceAll("\\","/").startsWith("storage/framework/")}var O=new Set(["headers","query","body","formData","actingAs"]);function V(t){if(!t)return"";let e=new URLSearchParams;for(let[n,o]of Object.entries(t)){if(o===void 0||o===null)continue;if(Array.isArray(o)){for(let a of o)e.append(n,String(a));continue}e.append(n,String(o))}let r=e.toString();return r?`?${r}`:""}function W(t,e,r){let n=Object.keys(t).filter((o)=>!O.has(o));if(n.length===0)return;throw TypeError(`http.${e.toLowerCase()}('${r}', \u2026) got unknown option(s) ${n.map((o)=>`'${o}'`).join(", ")}. Did you mean to send a body? Wrap it: { body: { ${n[0]}: \u2026 } }. `+`Valid options are ${[...O].join(", ")}.`)}async function K(){let t=await import("@stacksjs/router");return t.serverResponse}function Y(t){let e={status:t.status,ok:t.ok,headers:t.headers,text:()=>t.text(),json:async()=>await t.clone().json(),assertStatus(r){if(this.status!==r)throw Error(`Expected status ${r}, got ${this.status}`);return e},async assertJson(r){let n=await t.clone().json();for(let[o,a]of Object.entries(r))if(JSON.stringify(n[o])!==JSON.stringify(a))throw Error(`assertJson: expected ${o}=${JSON.stringify(a)}, got ${JSON.stringify(n[o])}`);return e},assertHeader(r,n){let o=t.headers.get(r);if(o===null)throw Error(`assertHeader: missing header '${r}'`);if(n!==void 0){if(!(typeof n==="string"?o===n:n.test(o)))throw Error(`assertHeader: expected ${r}=${String(n)}, got '${o}'`)}return e}};return e}function k(t="http://localhost"){let e=null,r={},n=null;async function o(){if(!e)return null;if(n)return n;let{Auth:s}=await import("@stacksjs/auth"),i=Number(e.id);if(!Number.isFinite(i))throw TypeError(`actingAs() needs a user with a numeric id; got ${JSON.stringify(e.id)}`);let c=await s.loginUsingId(i);if(!c)throw Error(`actingAs() could not authenticate user ${i}: no such user. Create the row first (e.g. via a factory) so a token can be issued against it.`);return n=String(c.token),n}async function a(s){let i={Accept:"application/json",...r,...s.headers};if(s.body!==void 0&&s.formData===void 0)i["Content-Type"]="application/json";let c=await o();if(c&&!i.Authorization&&!i.authorization)i.Authorization=`Bearer ${c}`;return i}function d(s){if(s.formData!==void 0){if(s.body!==void 0)throw TypeError("A request carries either `body` or `formData`, not both.");let i=new FormData;for(let[c,f]of Object.entries(s.formData))i.append(c,f);return i}if(s.body===void 0)return;return typeof s.body==="string"?s.body:JSON.stringify(s.body)}async function l(s,i,c={}){let f=await K(),g=i.startsWith("http")?i:`${t}${i}`,p=V(c.query),m=p&&g.includes("?")?`${g}&${p.slice(1)}`:`${g}${p}`,R={method:s,headers:await a(c),body:d(c)},U=await f(new Request(m,R));return Y(U)}let u={actingAs(s){return e=s,n=null,u},withHeaders(s){return r={...r,...s},u},request:(s,i,c)=>l(s,i,c),get:(s)=>l("GET",s),post:(s,i)=>l("POST",s,{body:i}),put:(s,i)=>l("PUT",s,{body:i}),patch:(s,i)=>l("PATCH",s,{body:i}),delete:(s,i)=>l("DELETE",s,{body:i})};return u}function Pe(t,e){return k(e).actingAs(t)}var Ae=Object.freeze(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].reduce((t,e)=>{let r=async(n,o={})=>{W(o,e,n);let{actingAs:a,...d}=o,l=k();if(a)l.actingAs(a);return l.request(e,n,d)};return{...t,[e.toLowerCase()]:r}},{}));import P from"process";var X=60000;function Z(t){let e=[],r="",n=null,o=!1,a=!1;for(let d of t){if(o){r+=d,o=!1;continue}if(d==="\\"){o=!0,a=!0;continue}if(n){if(d===n)n=null;else r+=d;continue}if(d==='"'||d==="'"){n=d,a=!0;continue}if(/\s/.test(d)){if(a)e.push(r),r="",a=!1;continue}r+=d,a=!0}if(n)throw Error(`Unterminated ${n} in command: ${t}`);if(a)e.push(r);return e}function Fe(t){let e=typeof t==="string"?Z(t):[...t],r,n={},o=P.cwd(),a=X;async function d(){if(e.length===0)throw Error("command() needs something to run");let u=Bun.spawn(["./buddy",...e],{cwd:o,env:{...P.env,...n},stdin:r===void 0?"ignore":new TextEncoder().encode(r),stdout:"pipe",stderr:"pipe"}),s=!1,i=setTimeout(()=>{s=!0,u.kill()},a);try{let[c,f,g]=await Promise.all([new Response(u.stdout).text(),new Response(u.stderr).text(),u.exited]);return{exitCode:g,stdout:c,stderr:f,output:c+f,timedOut:s}}finally{clearTimeout(i)}}let l={withInput(u){return r=u.map((s)=>`${s}
|
|
3
|
+
`).join(""),l},withEnv(u){return n={...n,...u},l},withCwd(u){return o=u,l},withTimeout(u){if(!Number.isFinite(u)||u<=0)throw TypeError(`withTimeout expects a positive number of milliseconds, got ${u}`);return a=u,l},then(u,s){return d().then(u,s)}};return l}import{afterEach as ee}from"bun:test";import{events as y}from"@stacksjs/events";var h=null,T=[],A=(t,e)=>{T.push({type:String(t),payload:e})};function Ne(){if(h)return;h=[...y.all.entries()],y.all.clear(),T=[],y.on("*",A)}function Le(){return h!==null}function te(t){if(!h)throw Error('getDispatchedEvents() was called without eventFake(). Nothing is recording, so an empty result would look like "the event did not fire".');return t===void 0?[...T]:T.filter((e)=>e.type===t)}function Ue(t){return te(t).length>0}function re(){if(!h)return;y.off("*",A),y.all.clear();for(let[t,e]of h)y.all.set(t,e);h=null,T=[]}ee(()=>{re()});import{afterEach as ne}from"bun:test";import{CaptureEmailDriver as E,mail as C}from"@stacksjs/email";var b=null;function He(){if(b!==null)return;b=C.fake(),E.clear()}function Ge(){return b!==null}function F(){if(b===null)throw Error('sentEmails() was called without mailFake(). Nothing is capturing, so an empty result would look like "no email was sent".');return[...E.all()]}function Je(){return F().at(-1)}function Qe(t){let e=(r)=>{if(r===void 0||r===null)return!1;return(Array.isArray(r)?r:[r]).some((o)=>(typeof o==="string"?o:o?.address)===t)};return F().filter((r)=>e(r.to)||e(r.cc)||e(r.bcc))}function oe(){if(b===null)return;C.restoreDriver(b),b=null,E.clear()}ne(()=>{oe()});import{setSystemTime as q}from"bun:test";function se(t){let e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))throw TypeError(`Not a valid time: ${JSON.stringify(t)}`);return e}function ie(t=new Date){let e=se(t);return q(e),e}function We(t){return ie(t)}function Ke(){q()}import{spawnOwnedProcess as ae}from"@stacksjs/cli/owned-process";import{existsSync as ue,mkdtempSync as de,rmSync as le,writeFileSync as _}from"fs";import{tmpdir as ce}from"os";import{join as S,resolve as pe}from"path";import D from"process";function fe(t,e={}){let r=e.mode&&e.mode!=="auto"?e.mode:/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(t)?"test":"run";return[D.execPath,...e.config?[`--config=${e.config}`]:[],...e.envFile===!1?["--no-env-file"]:[],...r==="test"?["test"]:[],t,...e.args??[]]}function me(t){let e=t.inheritEnv===!1?{}:{...D.env};for(let[r,n]of Object.entries(t.env??{}))if(n===void 0)delete e[r];else e[r]=n;return Object.fromEntries(Object.entries(e).filter((r)=>r[1]!==void 0))}async function nt(t,e={}){if(!t||typeof t!=="string")throw TypeError("runIsolated needs a file to run");let r=e.timeoutMs??60000;if(!Number.isFinite(r)||r<=0)throw RangeError("timeoutMs must be a positive number of milliseconds");if(e.bunfig!=null&&e.preload)throw TypeError("runIsolated takes bunfig or preload, not both: list the preloads in that bunfig");let n=null,o;if(e.bunfig!=null){if(!e.bunfig)throw TypeError("bunfig must be a path to a bunfig.toml");if(o=pe(e.cwd??D.cwd(),e.bunfig),!ue(o))throw Error(`runIsolated: no bunfig at ${o}`)}if(e.preload){n=de(S(ce(),"stacks-isolated-"));let u=S(n,"noop-preload.ts");_(u,`export {}
|
|
4
|
+
`);let s=JSON.stringify(e.preload.length?e.preload:[u]);o=S(n,"bunfig.toml"),_(o,`preload = ${s}
|
|
5
5
|
|
|
6
6
|
[test]
|
|
7
|
-
preload = ${
|
|
8
|
-
`)}let a=
|
|
7
|
+
preload = ${s}
|
|
8
|
+
`)}let a=fe(t,{...e,config:o}),d=Date.now(),l=!1;try{let u=ae(a,{cwd:e.cwd,env:me(e),stdin:e.stdin!=null?new Blob([e.stdin]):"ignore"}),s=setTimeout(()=>{l=!0,u.stop()},r);try{let[i,c,f]=await Promise.all([u.exited,new Response(u.stdout).text(),new Response(u.stderr).text()]);return{code:l||i.signal?null:i.code,signal:i.signal,stdout:c,stderr:f,timedOut:l,durationMs:Date.now()-d,command:a}}finally{clearTimeout(s),await u.stop()}}finally{if(n)le(n,{recursive:!0,force:!0})}}function ot(t,e){let r=`
|
|
9
9
|
--- stdout ---
|
|
10
10
|
${t.stdout}
|
|
11
11
|
--- stderr ---
|
|
12
|
-
${t.stderr}`;if(t.timedOut)throw Error(`${t.command.slice(1).join(" ")} timed out after ${t.durationMs}ms${r}`);if(t.code!==0)throw Error(`${t.command.slice(1).join(" ")} exited ${t.code??t.signal}${r}`);if(e!=null&&!(typeof e==="string"?t.stdout.includes(e):e.test(t.stdout)))throw Error(`${t.command.slice(1).join(" ")} did not print ${String(e)}${r}`);return t}import v from"process";import{spawnOwnedProcess as
|
|
12
|
+
${t.stderr}`;if(t.timedOut)throw Error(`${t.command.slice(1).join(" ")} timed out after ${t.durationMs}ms${r}`);if(t.code!==0)throw Error(`${t.command.slice(1).join(" ")} exited ${t.code??t.signal}${r}`);if(e!=null&&!(typeof e==="string"?t.stdout.includes(e):e.test(t.stdout)))throw Error(`${t.command.slice(1).join(" ")} did not print ${String(e)}${r}`);return t}import v from"process";import{spawnOwnedProcess as ge}from"@stacksjs/cli/owned-process";var I="stacks:test-service:ready";function ut(t,e){if(!v.send)return!1;let r={type:I,pid:v.pid,info:t};if(e)v.send(r,void 0,void 0,e);else v.send(r);return!0}function dt(t,e={}){let r=e.startupTimeoutMs??60000,n=e.stopGraceMs??2000;for(let[p,m]of Object.entries({startupTimeoutMs:r,stopGraceMs:n}))if(!Number.isFinite(m)||m<=0)throw RangeError(`${p} must be positive and finite`);let o=e.label??"Test service",a=new AbortController,d,l,u,s=new Promise((p,m)=>{d=p,l=m});s.catch(()=>{});let i=ge(t,{cwd:e.cwd,env:e.env,stdin:"ignore",stopGraceMs:n,stdout:e.stdout??"pipe",stderr:e.stderr??"pipe",ipc(p,m){if(!p||typeof p!=="object"||!("type"in p)||!("pid"in p)||p.type!==I||p.pid!==m)return;clearTimeout(u),d("info"in p?p.info:void 0)}}),c,f=()=>{if(c)return c;return clearTimeout(u),l(Error(`${o} stopped before readiness`)),c=i.stop(),c};u=setTimeout(()=>{let p=Error(`${o} readiness timed out after ${r}ms`);l(p),a.abort(p),f().catch(()=>{})},r);let g=i.exited.then(({code:p,signal:m})=>{if(clearTimeout(u),!c){let R=Error(`${o} exited ${p}${m?` (${m})`:""}`);l(R),a.abort(R)}return p},(p)=>{throw clearTimeout(u),l(p),a.abort(p),p});return g.catch(()=>{}),{pid:i.pid,ready:s,signal:a.signal,exited:g,stdout:i.stdout instanceof ReadableStream?i.stdout:null,stderr:i.stderr instanceof ReadableStream?i.stderr:null,stop:f}}import{mkdtempSync as we,rmSync as x}from"fs";import{tmpdir as he}from"os";import{join as N}from"path";import be from"process";var{SQL:L}=globalThis.Bun;var ye=new Set(["localhost","127.0.0.1","[::1]","::1"]);function Te(t={}){return t.url||be.env.STACKS_TEST_POSTGRES_URL||void 0}function Re(t){let e;try{e=new URL(t)}catch{throw Error("A disposable Postgres database needs a postgres:// URL")}if(!["postgres:","postgresql:"].includes(e.protocol))throw Error(`A disposable Postgres database needs a postgres:// URL, got ${e.protocol}`);if(!ye.has(e.hostname))throw Error(`Disposable databases are only created on a local PostgreSQL server (localhost, 127.0.0.1, ::1), not "${e.hostname}"`);return e}function ve(t){return`${(t.toLowerCase().replace(/[^a-z0-9_]/g,"_").replace(/^[^a-z_]+/,"")||"stacks_test").slice(0,38)}_${crypto.randomUUID().replaceAll("-","").slice(0,24)}`}async function Ee(t,e={}){if(t!=="sqlite"&&t!=="postgres")throw Error(`Disposable databases are sqlite or postgres, not "${String(t)}"`);let r=ve(e.prefix??"stacks_test"),n=we(N(he(),`${r.slice(0,20)}-`)),o=!1;if(t==="sqlite"){let a=N(n,`${r}.sqlite`),d=async()=>{if(o)return;o=!0,x(n,{recursive:!0,force:!0})};return{dialect:t,name:r,directory:n,path:a,env:{DB_CONNECTION:"sqlite",DB_DATABASE_PATH:a},drop:d,[Symbol.asyncDispose]:d}}try{let a=Te(e);if(!a)throw Error("A disposable Postgres database needs a server: pass options.url or set STACKS_TEST_POSTGRES_URL");let d=Re(a),l={url:d.href,database:decodeURIComponent(d.pathname.slice(1))||void 0},u=new L(l);try{await u.unsafe(`CREATE DATABASE "${r}"`)}finally{await u.close()}let s=new URL(d.href);s.pathname=`/${r}`;let i=async()=>{if(o)return;o=!0;let c=new L(l);try{await c.unsafe(`DROP DATABASE IF EXISTS "${r}" WITH (FORCE)`)}finally{await c.close(),x(n,{recursive:!0,force:!0})}};return{dialect:t,name:r,directory:n,url:s.href,sqlOptions:{url:s.href,database:r},env:{DB_CONNECTION:"postgres",DB_HOST:d.hostname.replace(/^\[|\]$/g,""),DB_PORT:d.port||"5432",DB_DATABASE:r,DB_USERNAME:decodeURIComponent(d.username),DB_PASSWORD:decodeURIComponent(d.password),PGHOST:d.hostname.replace(/^\[|\]$/g,""),PGPORT:d.port||"5432",PGUSER:decodeURIComponent(d.username),PGPASSWORD:decodeURIComponent(d.password),PGDATABASE:r,POSTGRES_URL:s.href,DATABASE_URL:s.href},drop:i,[Symbol.asyncDispose]:i}}catch(a){throw x(n,{recursive:!0,force:!0}),a}}async function wt(t,e,r={}){let n=await Ee(t,r),o;try{o=await e(n)}catch(a){throw await n.drop().catch(()=>{}),a}return await n.drop(),o}async function bt(t){if(!t.length)return;let{db:e,getDatabaseDialect:r}=await import("@stacksjs/database/runtime"),n=r();if(n!=="sqlite"&&n!=="postgres")throw Error("Atomic test schema setup requires SQLite or PostgreSQL");await e.transaction(async(o)=>{if(n==="postgres")await o.unsafe(t.map((a)=>`${a}
|
|
13
13
|
;`).join(`
|
|
14
|
-
`));else for(let a of t)await
|
|
14
|
+
`));else for(let a of t)await o.unsafe(a)})}export*from"bun:test";export{Pe as actingAs,bt as applyTestSchema,ot as assertIsolatedOk,Re as assertLocalPostgres,W as assertRequestOptions,ke as bootTestEnvironment,Fe as command,Ee as createDisposableDatabase,Te as disposablePostgresUrl,Qe as emailsTo,Ne as eventFake,Le as eventsAreFaked,k as featureTest,ie as freezeTime,te as getDispatchedEvents,Ue as hasDispatchedEvent,Ae as http,z as isFrameworkSuite,fe as isolatedCommand,Je as lastEmail,He as mailFake,Ge as mailIsFaked,ut as notifyTestServiceReady,V as queryString,re as restoreEvents,oe as restoreMail,nt as runIsolated,F as sentEmails,J as setupTestEnvironment,Z as splitCommand,dt as startTestService,We as travelTo,Ke as useRealTime,wt as withDisposableDatabase};
|
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.623",
|
|
6
6
|
"description": "The Stacks way of testing.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -91,20 +91,20 @@
|
|
|
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.
|
|
107
|
-
"@stacksjs/ts-cloud": "^0.16.
|
|
94
|
+
"@stacksjs/auth": "0.75.623",
|
|
95
|
+
"@stacksjs/cache": "0.75.623",
|
|
96
|
+
"@stacksjs/cli": "0.75.623",
|
|
97
|
+
"@stacksjs/config": "0.75.623",
|
|
98
|
+
"@stacksjs/database": "0.75.623",
|
|
99
|
+
"@stacksjs/email": "0.75.623",
|
|
100
|
+
"@stacksjs/events": "0.75.623",
|
|
101
|
+
"@stacksjs/hq": "0.75.623",
|
|
102
|
+
"@stacksjs/path": "0.75.623",
|
|
103
|
+
"@stacksjs/router": "0.75.623",
|
|
104
|
+
"@stacksjs/server": "0.75.623",
|
|
105
|
+
"@stacksjs/storage": "0.75.623",
|
|
106
|
+
"@stacksjs/strings": "0.75.623",
|
|
107
|
+
"@stacksjs/ts-cloud": "^0.16.143",
|
|
108
108
|
"very-happy-dom": "^0.4.1"
|
|
109
109
|
},
|
|
110
110
|
"devDependencies": {
|