@saywright/studio 0.0.0-stage → 0.1.0

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.
Files changed (107) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +5 -0
  3. package/README.md +63 -2
  4. package/bin/saywright.mjs +10 -0
  5. package/dist/THIRD_PARTY_NOTICES.md +2699 -0
  6. package/dist/axe.min.js +12 -0
  7. package/dist/bridge.js +6582 -0
  8. package/dist/cli.mjs +56050 -0
  9. package/dist/client/assets/Calibration-xY4YDLzU.js +1 -0
  10. package/dist/client/assets/Calibration-xY4YDLzU.js.br +0 -0
  11. package/dist/client/assets/Calibration-xY4YDLzU.js.gz +0 -0
  12. package/dist/client/assets/CodeViews-ytEy2pIT.js +3 -0
  13. package/dist/client/assets/CodeViews-ytEy2pIT.js.br +0 -0
  14. package/dist/client/assets/CodeViews-ytEy2pIT.js.gz +0 -0
  15. package/dist/client/assets/CommandPalette-BA3akF-p.js +1 -0
  16. package/dist/client/assets/CommandPalette-BA3akF-p.js.br +0 -0
  17. package/dist/client/assets/CommandPalette-BA3akF-p.js.gz +0 -0
  18. package/dist/client/assets/HelpDialog-C6qmdEwi.js +1 -0
  19. package/dist/client/assets/HelpDialog-C6qmdEwi.js.br +0 -0
  20. package/dist/client/assets/HelpDialog-C6qmdEwi.js.gz +0 -0
  21. package/dist/client/assets/ReportView-Bj9xxLCi.js +4 -0
  22. package/dist/client/assets/ReportView-Bj9xxLCi.js.br +0 -0
  23. package/dist/client/assets/ReportView-Bj9xxLCi.js.gz +0 -0
  24. package/dist/client/assets/SettingsDialog-VrACcdUX.js +1 -0
  25. package/dist/client/assets/SettingsDialog-VrACcdUX.js.br +0 -0
  26. package/dist/client/assets/SettingsDialog-VrACcdUX.js.gz +0 -0
  27. package/dist/client/assets/asr.worker-FcRNDSsJ.js +17 -0
  28. package/dist/client/assets/asr.worker-FcRNDSsJ.js.br +0 -0
  29. package/dist/client/assets/asr.worker-FcRNDSsJ.js.gz +0 -0
  30. package/dist/client/assets/button-B2NFEpCs.js +18 -0
  31. package/dist/client/assets/button-B2NFEpCs.js.br +0 -0
  32. package/dist/client/assets/button-B2NFEpCs.js.gz +0 -0
  33. package/dist/client/assets/camera-BD9K1f5I.js +1 -0
  34. package/dist/client/assets/cn-Wq33h1G4.js +1 -0
  35. package/dist/client/assets/cn-Wq33h1G4.js.br +0 -0
  36. package/dist/client/assets/cn-Wq33h1G4.js.gz +0 -0
  37. package/dist/client/assets/confirm-D1U-bFIL.js +41 -0
  38. package/dist/client/assets/confirm-D1U-bFIL.js.br +0 -0
  39. package/dist/client/assets/confirm-D1U-bFIL.js.gz +0 -0
  40. package/dist/client/assets/footprints-DiYtIryA.js +1 -0
  41. package/dist/client/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  42. package/dist/client/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  43. package/dist/client/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  44. package/dist/client/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  45. package/dist/client/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  46. package/dist/client/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  47. package/dist/client/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  48. package/dist/client/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  49. package/dist/client/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  50. package/dist/client/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  51. package/dist/client/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  52. package/dist/client/assets/index-BakNwOFF.css +2 -0
  53. package/dist/client/assets/index-BakNwOFF.css.br +0 -0
  54. package/dist/client/assets/index-BakNwOFF.css.gz +0 -0
  55. package/dist/client/assets/index-DUAtV_Av.js +18 -0
  56. package/dist/client/assets/index-DUAtV_Av.js.br +0 -0
  57. package/dist/client/assets/index-DUAtV_Av.js.gz +0 -0
  58. package/dist/client/assets/ort-wasm-simd-threaded-DcHrbrbl.wasm +0 -0
  59. package/dist/client/assets/preload-helper-BLdHbfdN.js +1 -0
  60. package/dist/client/assets/preload-helper-BLdHbfdN.js.br +0 -0
  61. package/dist/client/assets/preload-helper-BLdHbfdN.js.gz +0 -0
  62. package/dist/client/assets/refresh-cw-Dobx2YmO.js +1 -0
  63. package/dist/client/assets/tracker.worker-DWwj76VA.js +41 -0
  64. package/dist/client/assets/tracker.worker-DWwj76VA.js.br +0 -0
  65. package/dist/client/assets/tracker.worker-DWwj76VA.js.gz +0 -0
  66. package/dist/client/assets/vision_bundle-ByYCzljp.js +41 -0
  67. package/dist/client/assets/vision_bundle-ByYCzljp.js.br +0 -0
  68. package/dist/client/assets/vision_bundle-ByYCzljp.js.gz +0 -0
  69. package/dist/client/favicon.svg +1 -0
  70. package/dist/client/index.html +27 -0
  71. package/dist/client/index.html.br +0 -0
  72. package/dist/client/index.html.gz +0 -0
  73. package/dist/client/voice-capture-worklet.js +23 -0
  74. package/dist/sample/index.html +13 -0
  75. package/dist/sample/package.json +23 -0
  76. package/dist/sample/playwright.config.ts +20 -0
  77. package/dist/sample/saywright.config.json +68 -0
  78. package/dist/sample/src/App.tsx +32 -0
  79. package/dist/sample/src/components/AddressCard.tsx +16 -0
  80. package/dist/sample/src/components/CouponField.tsx +50 -0
  81. package/dist/sample/src/components/Header.tsx +26 -0
  82. package/dist/sample/src/components/LineItems.tsx +22 -0
  83. package/dist/sample/src/components/OrderSummary.tsx +32 -0
  84. package/dist/sample/src/components/ProductCard.tsx +26 -0
  85. package/dist/sample/src/ds/Badge.tsx +14 -0
  86. package/dist/sample/src/ds/Button.tsx +16 -0
  87. package/dist/sample/src/ds/Card.tsx +17 -0
  88. package/dist/sample/src/ds/Heading.tsx +14 -0
  89. package/dist/sample/src/ds/ProductGrid.tsx +15 -0
  90. package/dist/sample/src/ds/SummaryRow.tsx +18 -0
  91. package/dist/sample/src/ds/TextField.tsx +31 -0
  92. package/dist/sample/src/ds/index.ts +7 -0
  93. package/dist/sample/src/lib/cart.ts +20 -0
  94. package/dist/sample/src/lib/money.ts +7 -0
  95. package/dist/sample/src/lib/pricing.ts +34 -0
  96. package/dist/sample/src/lib/route.ts +17 -0
  97. package/dist/sample/src/main.tsx +10 -0
  98. package/dist/sample/src/pages/Checkout.tsx +37 -0
  99. package/dist/sample/src/pages/Shop.tsx +27 -0
  100. package/dist/sample/src/styles.css +155 -0
  101. package/dist/sample/tests/smoke.spec.ts +7 -0
  102. package/dist/sample/tsconfig.json +37 -0
  103. package/dist/sample/vite.config.ts +8 -0
  104. package/dist/server/node-BgmEDdmn.mjs +23 -0
  105. package/dist/server/node-DuXxFg5I.mjs +2501 -0
  106. package/dist/server/speech-worker.mjs +266 -0
  107. package/package.json +97 -4
@@ -0,0 +1,18 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vision_bundle-ByYCzljp.js","assets/preload-helper-BLdHbfdN.js"])))=>i.map(i=>d[i]);
2
+ import{i as e,o as t,r as n,t as r}from"./cn-Wq33h1G4.js";import{t as i}from"./preload-helper-BLdHbfdN.js";var a=t(e(),1),o=class extends Error{status;code;constructor(e,t,n){super(t),this.status=e,this.code=n}};async function s(e,t,n,r){let i;try{i=await fetch(`/api${t}`,{method:e,headers:n===void 0?void 0:{"Content-Type":`application/json`},body:n===void 0?void 0:JSON.stringify(n),signal:r})}catch(e){throw e.name===`AbortError`?e:new o(0,"The studio server isn’t responding. Is `npm run dev` still running?")}let a;try{a=await i.text()}catch(e){throw e.name===`AbortError`?e:new o(0,`The studio server stopped answering midway. Try again.`)}let s={};if(a)try{s=JSON.parse(a)}catch{if(i.ok)throw new o(i.status,`The studio sent an answer it couldn’t read. Try again.`)}if(!i.ok)throw new o(i.status,s.error??`Request failed (${i.status})`,s.code);return s}var c={get:(e,t)=>s(`GET`,e,void 0,t),post:(e,t={},n)=>s(`POST`,e,t,n),put:(e,t={})=>s(`PUT`,e,t),delete:e=>s(`DELETE`,e)};function l(e,t){let n=null,r=!1,i=null,a=!1,o=()=>{n=new EventSource(`/api/events`),n.onopen=()=>{t?.(a),a=!0};for(let[t,r]of Object.entries(e))n.addEventListener(t,e=>{try{r(JSON.parse(e.data))}catch{}});n.onerror=()=>{n?.close(),r||(i=setTimeout(o,1500))}};return o(),()=>{r=!0,i&&clearTimeout(i),n?.close()}}var u=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},d=(e=>e?u(e):u),f=e=>e;function p(e,t=f){let n=a.useSyncExternalStore(e.subscribe,a.useCallback(()=>t(e.getState()),[e,t]),a.useCallback(()=>t(e.getInitialState()),[e,t]));return a.useDebugValue(n),n}var m=e=>{let t=d(e),n=e=>p(t,e);return Object.assign(n,t),n},h=(e=>e?m(e):m),g=h()(()=>({apps:[],active:null,runs:{},cloneDir:``,launcherPref:!0,launcher:!1,linking:null,opening:null,pending:null,cloneLog:[],loaded:!1})),_=g.setState,v=g.getState;function y(e){_({apps:e.apps,active:e.active,runs:Object.fromEntries(e.runs.map(e=>[e.app,e])),cloneDir:e.cloneDir,launcherPref:e.launcher,loaded:!0})}var b=()=>void 0,x={init(e){b=e,this.refresh()},async refresh(){try{y(await c.get(`/apps`))}catch{}},show(e){this.refresh(),_(e?{launcher:!0,linking:e}:{launcher:!0})},setLinking(e){_({linking:e})},hide(){v().active&&_({launcher:!1})},serverEvent(e){let t=e;t.kind===`run`&&t.run?_({runs:{...v().runs,[t.run.app]:t.run}}):t.kind===`opening`&&t.id?_({opening:{id:t.id,env:t.env??``,step:t.step??`Opening`}}):t.kind===`clone`&&t.line?_({cloneLog:[...v().cloneLog,t.line].slice(-80)}):t.kind===`active`?(_({active:t.id??null,opening:null,launcher:!t.id}),b(),this.refresh()):(t.kind===`linked`||t.kind===`unlinked`)&&this.refresh()},async open(e,t,n){_({opening:{id:e,env:t??``,step:`Opening`},pending:null});try{return y(await c.post(`/apps/${e}/open`,{env:t,decide:n})),_({opening:null,launcher:!1}),b(),!0}catch(n){let r=n instanceof o?n:null;return r?.code===`previews`?(_({opening:null,pending:{id:e,env:t,message:r.message}}),!1):(_({opening:{id:e,env:t??``,step:`Failed`,error:n instanceof Error?n.message:String(n),code:r?.code}}),!1)}},dismissOpening(){_({opening:null,pending:null})},async probeFolder(e){return(await c.post(`/apps/probe`,{folder:e})).probe},async probeUrl(e){return(await c.post(`/apps/probe`,{url:e})).probe},async folders(e){return c.get(`/apps/folders${e?`?path=${encodeURIComponent(e)}`:``}`)},async clone(e,t){return _({cloneLog:[]}),(await c.post(`/apps/clone`,{repo:e,dir:t})).probe},async link(e,t){let n=await c.post(`/apps`,{probe:e,...t,open:!1});return y(n.state),this.open(n.app.id),n.app},async sample(){_({opening:{id:`sample`,env:``,step:`Starting the sample shop`}});try{y(await c.post(`/apps/sample`,{})),_({opening:null,launcher:!1}),b()}catch(e){_({opening:{id:`sample`,env:``,step:`Failed`,error:e instanceof Error?e.message:String(e),code:e instanceof o?e.code:void 0}})}},async install(e){_({opening:{id:e,env:``,step:`Installing dependencies`}});try{return y(await c.post(`/apps/${e}/install`,{})),_({opening:null}),!0}catch(t){return _({opening:{id:e,env:``,step:`Failed`,error:t instanceof Error?t.message:String(t)}}),!1}},async stop(e){y(await c.post(`/apps/${e}/stop`,{}))},async remove(e){y(await c.delete(`/apps/${e}`))},async update(e,t){y((await c.put(`/apps/${e}`,t)).state)},async addEnv(e,t,n){y((await c.post(`/apps/${e}/envs`,{url:t,label:n})).state)},async removeEnv(e,t){y((await c.delete(`/apps/${e}/envs/${t}`)).state)},async setLauncherPref(e){y(await c.put(`/apps/launcher`,{on:e}))},async setCloneDir(e){y(await c.put(`/apps/clone-dir`,{dir:e}))},async close(){y(await c.post(`/apps/close`,{})),_({launcher:!0}),b()}},S=typeof navigator<`u`&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),ee={mod:[`⌘`,`Ctrl`],ctrl:[`⌃`,`Ctrl`],alt:[`⌥`,`Alt`],shift:[`⇧`,`Shift`]},te={enter:`↵`,esc:`Esc`,space:`Space`,up:`↑`,down:`↓`,left:`←`,right:`→`};function ne(e,t=S){return e.split(`+`).map(e=>{let n=e.trim(),r=n.toLowerCase();return ee[r]?ee[r][+!t]:te[r]??(n.length===1?n.toUpperCase():n)})}function re(e,t=S){let n=ne(e,t);return t?n.reduce((e,t,r)=>e+(r&&(t.length>1||n[r-1].length>1)?` `:``)+t,``):n.join(` `)}function ie(e){return e==null?`—`:e<1e3?`${Math.round(e)} ms`:e<6e4?`${(e/1e3).toFixed(+(e<1e4))} s`:`${Math.floor(e/6e4)}m ${Math.round(e%6e4/1e3)}s`}function ae(e,t=Date.now()){let n=Math.max(0,Math.round((t-e)/1e3));if(n<5)return`just now`;if(n<60)return`${n}s ago`;let r=Math.round(n/60);return r<60?`${r}m ago`:`${Math.round(r/60)}h ago`}function oe(e){try{let t=new URL(e),n=`${t.pathname}${t.search}${t.hash}`;return`${t.host}${n===`/`?``:n}`}catch{return e}}function se(e){return e.split(`/`).pop()??e}function ce(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function le(e){return e>0&&e<.01?`<$0.01`:`$${e.toFixed(e>=100?0:2)}`}function ue(e){return e>=1e6?`${(e/1e6).toFixed(e>=1e7?0:1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e))}function de(e,t){if(!e||!t||e===t)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\d+/g,`\\d+`);return n===t||!/\\d\+/.test(n)?e:new RegExp(n).exec(e)?.[0]??e}var fe=`saywright`;function pe(e,t){return t.v<(e.oldest??e.v)?`plugin`:e.v<(t.oldest??t.v)?`studio`:null}function me(e){return!!e&&typeof e==`object`&&e.ns===`saywright`&&typeof e.type==`string`}var he=class{frame=null;origin=`*`;nextReq=1;seq=0;pending=new Map;oneShot=new Map;helloTimer=null;ready=!1;url=``;outdated=null;onReady=null;onProbe=null;onRecorded=null;onNavigated=null;onMouse=null;onKey=null;onSession=null;onMoment=null;onOutdated=null;attach(e,t){this.detach(),this.frame=e,this.origin=new URL(t).origin,window.addEventListener(`message`,this.onMessage);let n=!1;try{n=e.contentWindow?.location.href!==`about:blank`}catch{n=!0}n&&this.sayHello()}sayHello(){this.ready=!1,this.outdated=null,this.helloTimer&&clearInterval(this.helloTimer);let e=()=>this.post({type:`hello`,v:1,oldest:1});e(),this.helloTimer=setInterval(()=>{this.ready||this.outdated?this.helloTimer&&clearInterval(this.helloTimer):e()},400)}detach(){window.removeEventListener(`message`,this.onMessage),this.helloTimer&&clearInterval(this.helloTimer);for(let e of this.pending.values())clearTimeout(e.timer);this.pending.clear(),this.frame=null,this.ready=!1}post(e){let t=this.frame?.contentWindow;if(t)try{t.postMessage({ns:fe,...e},this.origin)}catch{}}onMessage=e=>{if(!this.frame||e.source!==this.frame.contentWindow||e.origin!==this.origin||!me(e.data))return;let t=e.data;switch(t.type){case`ready`:{let e=pe({v:1,oldest:1},{v:Number(t.v)||0,oldest:t.oldest});if(e){this.outdated=e,this.helloTimer&&clearInterval(this.helloTimer),this.onOutdated?.(e);break}this.ready=!0,this.url=t.url,this.wanted&&this.post({type:`session`,on:!0,...this.wanted}),this.onReady?.({url:t.url,title:t.title});break}case`probe`:{let e=this.oneShot.get(t.seq);e?(this.oneShot.delete(t.seq),e(t)):t.seq===this.seq&&this.onProbe?.(t);break}case`reply`:{let e=this.pending.get(t.reqId);e&&(clearTimeout(e.timer),this.pending.delete(t.reqId),e.resolve(t));break}case`recorded`:this.onRecorded?.(t.action);break;case`progress`:{let e=this.pending.get(t.reqId);e?.wait(),e?.progress?.(t.done);break}case`navigated`:this.url=t.url,this.onNavigated?.({url:t.url,title:t.title});break;case`mouse`:this.onMouse?.(t.x===null||t.y===null?null:{x:t.x,y:t.y});break;case`key`:this.onKey?.(t.key,t.down);break;case`session`:this.starting&&t.id===this.starting.id&&(this.starting.done(),this.starting=null),this.onSession?.({id:t.id,events:t.events,issues:t.issues});break;case`moment`:this.onMoment?.(t.reason)}};probe(e,t,n,r,i,a=!1){this.ready&&this.post({type:`probe`,seq:++this.seq,x:e,y:t,radius:n,deep:r,track:i,sticky:a})}probeAt(e,t,n,r){if(!this.ready)return Promise.resolve(null);let i=++this.seq;return new Promise(a=>{let o=setTimeout(()=>{this.oneShot.delete(i),a(null)},600);this.oneShot.set(i,e=>{clearTimeout(o),a(e?.hit??null)}),this.post({type:`probe`,seq:i,x:e,y:t,radius:n,deep:r,track:[]})})}request(e,t=2e3,n){return new Promise(r=>{if(!this.ready)return r({ns:fe,type:`reply`,reqId:0,ok:!1,error:`app not connected`});let i=this.nextReq++,a=()=>{this.pending.delete(i),r({ns:fe,type:`reply`,reqId:i,ok:!1,error:`timeout`})},o={resolve:r,timer:setTimeout(a,t),wait:()=>{clearTimeout(o.timer),o.timer=setTimeout(a,t)},progress:n};this.pending.set(i,o),this.post({...e,reqId:i})})}async reveal(e,t,n){let r=await this.request({type:`reveal`,reqId:0,id:e,src:t,index:n});return r.ok?r.info??null:null}async review(e,t,n){let r=await this.request({type:`review`,reqId:0,experts:e,axe:t},3e4,n);if(!r.ok)throw Error(r.error===`timeout`?`The page took too long to check.`:r.error??`The page couldn’t be checked.`);return r.review??null}async describe(e){let t=await this.request({type:`describe`,reqId:0,id:e});return t.ok?t.info??null:null}async locator(e){let t=await this.request({type:`locator`,reqId:0,id:e});return t.ok&&t.locator&&t.info?{locator:t.locator,info:t.info}:null}async step(e,t){let n=await this.request({type:`step`,reqId:0,id:e,to:t});return n.ok?n.info??null:null}async find(e,t,n=`any`){let r=await this.request({type:`find`,reqId:0,id:e??0,what:t,where:n});return r.ok?r.info??null:null}async replay(e,t,n=!1,r,i=5e3){let a=await this.request({type:`replay`,reqId:0,locator:e,step:t,read:n,like:r},i);return{ok:a.ok,info:a.info??null,text:a.text,error:a.error}}async explore(){let e=await this.request({type:`explore`,reqId:0},4e3);return e.ok?e.snapshot??null:null}goto(e){this.post({type:`goto`,url:e})}async resolve(e,t){let n=await this.request({type:`resolve`,reqId:0,src:e,index:t});return n.ok?n.info??null:null}async click(e,t){let n=await this.request({type:`click`,reqId:0,x:e,y:t});return{ok:n.ok,info:n.info??null}}async type(e,t=!1){let n=await this.request({type:`type`,reqId:0,text:e,submit:t});return{ok:n.ok,error:n.error}}scroll(e,t,n,r){this.post({type:`scroll`,x:e,y:t,dx:n,dy:r})}record(e){this.post({type:`record`,on:e})}trackMouse(e){this.post({type:`mouse`,on:e})}forwardKeys(e){this.post({type:`keys`,on:e})}starting=null;wanted=null;session(e,t,n,r){return this.wanted=e&&t&&n?{id:t,endpoint:n,key:r}:null,this.post({type:`session`,on:e,id:t,endpoint:n,key:r}),!e||!t?Promise.resolve(!0):(this.starting?.done(),new Promise(e=>{let n=setTimeout(()=>{this.starting?.id===t&&(this.starting=null),e(!1)},3e3);this.starting={id:t,done:()=>{clearTimeout(n),e(!0)}}}))}mark(e,t){this.post({type:`mark`,note:e,via:t})}},ge=class extends Error{code;constructor(e,t){super(t),this.code=e}},_e=typeof navigator<`u`&&/Mac/.test(navigator.platform);async function ve(e){if(!window.isSecureContext||!navigator.mediaDevices?.getUserMedia)throw new ge(`insecure`,`Camera access needs http://localhost or https. Open the studio from the URL shown in your terminal.`);try{return await navigator.mediaDevices.getUserMedia({audio:!1,video:{deviceId:e?{exact:e}:void 0,facingMode:e?void 0:`user`,width:{ideal:640},height:{ideal:480},frameRate:{ideal:30,max:60}}})}catch(e){let t=e?.name;throw t===`NotAllowedError`||t===`SecurityError`?new ge(`denied`,_e?`Camera is blocked. Allow it in the address bar, and in System Settings → Privacy & Security → Camera for your browser.`:`Camera is blocked. Allow it from the camera icon in the address bar.`):t===`NotFoundError`||t===`OverconstrainedError`?new ge(`notfound`,`No camera found. Connect one, or use the mouse instead.`):t===`NotReadableError`||t===`AbortError`?new ge(`busy`,`The camera is in use by another app. Close it (Zoom, FaceTime, Teams) and try again.`):new ge(`other`,`Couldn’t start the camera: ${e?.message??t}`)}}async function ye(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`videoinput`)}catch{return[]}}function be(e){e?.getTracks().forEach(e=>e.stop())}function xe(e){return e.replace(/[\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06ED]/g,``).replace(/ـ/g,``).replace(/[أإآٱ]/g,`ا`).replace(/ى/g,`ي`).replace(/ة/g,`ه`).replace(/ؤ/g,`و`).replace(/ئ/g,`ي`).replace(/[\u0660-\u0669]/g,e=>String(e.charCodeAt(0)-1632))}function Se(e){return xe(e.normalize(`NFKC`)).toLowerCase().replace(/[^\p{L}\p{N}\s']/gu,` `).replace(/'(?!\w)|(?<!\w)'/g,` `).replace(/\s+/g,` `).trim()}function Ce(e,t){let n=e.length,r=t.length,i=Array.from({length:r+1},(e,t)=>t);for(let a=1;a<=n;a++){let n=[a];for(let o=1;o<=r;o++)n[o]=Math.min(i[o]+1,n[o-1]+1,i[o-1]+(e[a-1]===t[o-1]?0:1));i=n}return i[r]}function we(e,t){let n=Se(e).split(` `).filter(Boolean),r=Se(t).split(` `).filter(Boolean);return n.length?Ce(n,r)/n.length:+!!r.length}var Te=/^(?:و)?(?:هذا|هذه|هذي|هاذا|هاذي|ده|دي|دا|ديه|دى|ذا|ذلك|ذاك|تلك|هذاك|هذيك|دول|دولا|هدول|هؤلاء|هيدا|هيدي|هاد|هادا|هادي|هنا|هناك|هون|هنيه|هنيك|هيك)$/;function Ee(e){return xe(e.normalize(`NFKC`)).replace(/(\d)\s?[٫,]\s?(\d)/g,`$1.$2`).replace(/(\d)٬(\d)/g,`$1$2`).replace(/[^\p{L}\p{N}\s$.]/gu,` `).replace(/\s+/g,` `).trim()}function De(e){return e.replace(/^(?:و|ف)?(?:بال|لل|ال|بل|كال)(?=..)/,``)}function Oe(e,t){let n=De(e);return t.some(t=>n===t||e===t||t.length>=5&&Math.abs(n.length-t.length)<=1&&Ce([...n],[...t])<=1)}function C(e,t){return e.some(e=>Oe(e,t))}var ke={red:[`احمر`,`حمرا`,`حمراء`,`الحمر`,`احمرا`],green:[`اخضر`,`خضرا`,`خضراء`,`اخضرا`],blue:[`ازرق`,`زرقا`,`زرقاء`,`كحلي`,`ازرقا`],yellow:[`اصفر`,`صفرا`,`صفراء`,`اصفرا`],orange:[`برتقالي`,`برتقاني`,`اورنج`],purple:[`بنفسجي`,`موف`,`ليلكي`],pink:[`وردي`,`بمبي`,`زهري`,`بينك`],black:[`اسود`,`سودا`,`سوداء`,`اسودا`],white:[`ابيض`,`بيضا`,`بيضاء`,`ابيضا`],gray:[`رمادي`,`رصاصي`,`سكني`]},Ae=[`كبر`,`كبره`,`كبرها`,`كبري`,`اكبر`,`كبير`,`كبيره`,`كبيرة`,`تكبير`,`وسع`,`وسعه`,`اوسع`,`طول`,`اطول`,`زود`],je=[`صغر`,`صغره`,`صغرها`,`صغري`,`اصغر`,`صغير`,`صغيره`,`تصغير`,`قلل`,`قصر`,`اقصر`,`ضيق`,`نقص`],Me=[`مسافه`,`مسافات`,`المسافه`,`فراغ`,`بادينج`,`هوامش`,`هامش`,`تباعد`],Ne=`خلي.خليه.خليها.خلّي.اجعل.اجعله.اجعلها.اجعلي.اجعلوه.خلو.خلوه.غير.غيره.غيرها.غيّر.غيري.غيروه.لون.لونه.لونها.حول.حوله.حولها.اعمل.اعمله.اعملها.خليلي.سوي.سويه.خلّيه`.split(`.`),Pe=[`احذف`,`احذفه`,`احذفها`,`احذفي`,`امسح`,`امسحه`,`امسحها`,`امسحي`,`شيل`,`شيله`,`شيلها`,`شيلي`,`اخفي`,`اخفيه`,`اخفيها`,`حذف`,`ازل`,`ازله`,`الغي ده`],Fe=[`انقل`,`انقله`,`انقلها`,`حرك`,`حركه`,`حركها`,`حط`,`حطه`,`حطها`,`ضع`,`ضعه`,`نقل`],Ie=[`فوق`,`اعلي`,`قبل`],Le=[`تحت`,`اسفل`,`بعد`],Re=[[/^(?:تراجع|تراجع عن (?:ده|هذا|ذلك|التغيير)|ارجع|رجع|رجعها|رجعه|ارجعها|الغي التغيير|الغي التعديل|رجعه زي ما كان|ارجع زي ما كان|بلاش التغيير|بلاش ده|undo)$/,`undo`],[/^(?:احتفظ(?: به| بها| بالتغيير)?|احفظ(?:ه|ها| التغيير)?|اعتمد(?:ه|ها)?|تمام|تمام كده|تمام كدا|ممتاز|حلو|حلو كده|كويس|موافق|خليه كده|خليها كده|ابقيه|ابقيها|keep it|keep)$/,`keep it`],[/^(?:الغاء|الغ|الغي|إلغاء|بطل|وقف|توقف|خلاص|لا خلاص|اسكت|سيبك|cancel|stop)$/,`cancel`],[/^(?:(?:ا?نزل|نزل|انزلي)(?: لتحت| تحت| شويه| لأسفل| للاسفل)?|سكرول (?:لتحت|تحت|داون)|scroll down)$/,`scroll down`],[/^(?:(?:ا?طلع|اطلعي|اصعد)(?: لفوق| فوق| شويه| لأعلي| للاعلي)?|سكرول (?:لفوق|فوق|اب)|scroll up)$/,`scroll up`],[/^(?:شغل|جرب|نفذ|اعمل رن ل|ران)(?: ال)?(?:اختبار|تيست|تست|test)$/,`run the test`],[/^(?:اكتب|اعمل|انشئ|ولد|سوي|جهز)(?: لي)? (?:ال)?(?:اختبار|تيست|تست|test)(?: ل(?:ده|هذا|ها|ه))?$/,`generate a test`],[/^(?:اصلح(?:ه|ها)?|صلح(?:ه|ها)?|صلح المشكله|اصلح المشكله|صلح الغلط|اصلح الخطا|fix it)$/,`fix it`],[/^(?:اختار|حدد)(?: ال)?(?:اب|الاب|الحاويه|الكونتينر|اللي فوقه|العنصر الاكبر)$/,`select parent`],[/^(?:(?:اختار|حدد|اختر) )?(?:اللي (?:جواه|جواها|جوه|جوا|داخله|داخلها|بداخله)|العنصر اللي (?:جواه|جوه|جوا|داخله)|الابن|ادخل(?: جواه| جوه| جوا| جواها)?)$/,`select the child`],[/^(?:(?:اختار|حدد|اختر) )?(?:التالي|اللي بعده|اللي بعدها|اللي بعد كده|اللي بعد كدا|الجاي|اللي جنبه)$/,`select next`],[/^(?:(?:اختار|حدد|اختر) )?(?:السابق|اللي قبله|اللي قبلها|اللي قبل كده|اللي قبل كدا)$/,`select previous`],[/^(?:الغي التحديد|الغ التحديد|شيل التحديد|بلاش تحديد|امسح التحديد|الغاء التحديد|مش عايز اختار حاجه)$/,`deselect`],[/^(?:و?(?:ده|دي|هذا|هذه|هذي|ذا|هاد|هيدا) (?:كمان|ايضا|برضه|برضو)|ضيف (?:ده|دي|هذا|هذه)|اضف (?:هذا|هذه|ده|دي)|وده|ودي|وهذا|وهذه)$/,`add this`],[/^(?:امسح(?: الكل| كله)?|نظف|clear)$/,`clear`],[/^(?:مساعده|ساعدني|help)$/,`help`]],ze=[[`تراجع`,`undo`],[`ارجع`,`undo`],[`احتفظ به`,`keep it`],[`احتفظ`,`keep it`],[`احفظ`,`keep it`],[`اعتمد`,`keep it`],[`الغاء`,`cancel`],[`انزل لتحت`,`scroll down`],[`اطلع لفوق`,`scroll up`],[`اصلحه`,`fix it`],[`شغل الاختبار`,`run the test`]],Be=[[[`زر`,`زرار`,`بوتون`,`بتن`],`button`],[[`كارت`,`كرت`,`بطاقه`,`كارد`],`card`],[[`صوره`,`صور`,`ايقونه`,`لوجو`,`شعار`],`image`],[[`عنوان`,`تايتل`,`هيدنج`],`heading`],[[`لينك`,`رابط`],`link`],[[`قائمه`,`قايمه`,`ليسته`,`لسته`,`منيو`],`list`],[[`خانه`,`حقل`,`مربع`,`انبوت`],`field`],[[`نص`,`كلام`,`سطر`,`جمله`],`text`],[[`فورم`,`نموذج`,`استماره`],`form`],[[`جدول`],`table`],[[`هيدر`,`راس الصفحه`],`header`],[[`فوتر`,`تذييل`],`footer`],[[`قسم`,`سكشن`,`جزء`],`section`],[[`سعر`,`السعر`],`price`]];function Ve(e){let t=/^(?:اختار|اختر|حدد|اختاري|حددي) (.+?)(?: (اللي جواه|اللي جوه|جواه|جوه|اللي حواليه|اللي فوقه|حواليه))?$/.exec(e);if(!t)return null;let n=De(t[1]),r=Be.find(([e])=>e.some(e=>De(e)===n||e.length>=4&&Ce([...n],[...De(e)])<=1))?.[1];return r?`select the ${r}${t[2]?/جو/.test(t[2])?` inside`:` outside`:``}`:null}var He=[[/^(?:علم|علّم|ضع علامه|حط علامه|حط عليها علامه|سجل(?: ملاحظه| ده| هنا)?|مارك|mark)(?: هنا| ده| هذا| اللحظه دي)?$/,`mark`]],Ue={صفر:0,واحد:1,واحده:1,اثنين:2,اتنين:2,اثنان:2,ثلاثه:3,تلاته:3,ثلاث:3,تلات:3,اربعه:4,اربع:4,خمسه:5,خمس:5,سته:6,ست:6,سبعه:7,سبع:7,ثمانيه:8,تمانيه:8,ثماني:8,ثمان:8,تمن:8,تسعه:9,تسع:9,عشره:10,عشر:10,حداشر:11,احدعشر:11,اتناشر:12,عشرين:20,عشرون:20,ثلاثين:30,تلاتين:30,ثلاثون:30,اربعين:40,اربعون:40,خمسين:50,خمسون:50,ستين:60,ستون:60,سبعين:70,سبعون:70,ثمانين:80,تمانين:80,ثمانون:80,تسعين:90,تسعون:90,ميه:100,مائه:100,مية:100,مئه:100,ميتين:200,مئتين:200,الف:1e3};function We(e){let t=Ee(e),n=/(\d+(?:[.,]\d+)?)\s*(دولار|\$|جنيه|ريال|درهم|يورو)?/.exec(t);if(n)return{value:Number(n[1].replace(`,`,`.`)),currency:n[2]??null};let r=t.split(` `),i=0,a=0,o=0,s=!1,c=!1,l=null;for(let e of r){let t=e.replace(/^و(?=.)/,``);if(/^(دولار|دولارات|جنيه|جنيهات|ريال|درهم|يورو)$/.test(t)){l=t,i+=o,o=0,c=!0;continue}if(/^(سنت|سنتات|قرش|قروش|هلله|فلس)$/.test(t)){a+=o,o=0;continue}let n=Ue[t];n!==void 0&&(s=!0,n===100||n===1e3?o=(o||1)*n:o+=n)}return s?(c?a+=o:i+=o,{value:i+Math.min(99,a)/100,currency:l}):null}function Ge(e,t){let n=Number.isInteger(e)?String(e):e.toFixed(2);return t&&/دولار|\$/.test(t)?`$${n}`:t?n:`$${n}`}function Ke(e){let t=Ee(e);if(!t||!/[؀-ۿ]/.test(t))return null;for(let[e,n]of Re)if(e.test(t))return{text:n,kind:`control`};for(let[e,n]of He)if(e.test(t))return{text:n,kind:`session`};let n=Ve(t);if(n)return{text:n,kind:`control`};let r=t.split(` `);if(r.length<=2){let e=[...t.replace(/ /g,``)];for(let[t,n]of ze){let r=[...t.replace(/ /g,``)],i=r.length>=7?2:+(r.length>=4);if(Ce(e,r)<=i)return{text:n,kind:`control`}}}let i=r.some(e=>Te.test(e))?`this`:`it`;if(/(?:المفروض|المفروض انه|من المفروض|يفترض|لازم|يجب ان|ينبغي ان|المتوقع)\s/.test(t+` `)||/^(?:يكون|تكون|يبقي|تبقي)\s/.test(t)){let e=We(t);if(e)return{text:`${i} should show ${Ge(e.value,e.currency)}`,kind:`check`}}let a=Object.entries(ke).find(([,e])=>C(r,e))?.[0],o=C(r,Me),s=C(r,Ae),c=C(r,je);return a&&(C(r,Ne)||r.length<=3)?{text:`make ${i} ${a}`,kind:`edit`}:o&&(s||c||C(r,[`زود`,`زوّد`,`قلل`,`كتر`,`اكتر`,`اقل`]))?{text:`${s||C(r,[`زود`,`زوّد`,`كتر`,`اكتر`])?`more`:`less`} space between these`,kind:`edit`}:s&&!c?{text:`make ${i} bigger`,kind:`edit`}:c&&!s?{text:`make ${i} smaller`,kind:`edit`}:C(r,Pe)?{text:`remove ${i}`,kind:`edit`}:C(r,Fe)&&(C(r,Ie)||C(r,Le))?{text:`move this ${C(r,Ie)?`above`:`below`} that`,kind:`edit`}:/(?:اجعل|خلي|خليه|خليها|اعمل)\s+(?:\S+\s+)?(?:زي|مثل|شبه|نفس شكل)\s/.test(t+` `)?{text:`make this look like that`,kind:`edit`}:null}var qe={zero:0,one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12,thirteen:13,fourteen:14,fifteen:15,sixteen:16,seventeen:17,eighteen:18,nineteen:19},Je={twenty:20,thirty:30,forty:40,fifty:50,sixty:60,seventy:70,eighty:80,ninety:90};function Ye(e){let t=0,n=0,r=!1;for(let i of e.toLowerCase().replace(/-/g,` `).split(/\s+/).filter(Boolean))if(!(i===`and`&&r)){if(i in qe)n+=qe[i];else if(i in Je)n+=Je[i];else if(i===`hundred`)n=(n||1)*100;else if(i===`thousand`)t+=(n||1)*1e3,n=0;else if(/^\d+$/.test(i))n+=Number(i);else return null;r=!0}return r?t+n:null}function Xe(e){let t=/^(.+?)\s+(?:dollars?|bucks)(?:\s+(?:and\s+)?(.+?)(?:\s+cents?)?)?$/i.exec(e.trim());if(!t)return null;let n=Ye(t[1]);if(n===null)return null;if(!t[2])return`$${n}`;let r=Ye(t[2]);return r===null||r>99?null:`$${n}.${String(r).padStart(2,`0`)}`}function Ze(e){return e.replace(/[٠-٩]/g,e=>String(e.charCodeAt(0)-1632)).replace(/[۰-۹]/g,e=>String(e.charCodeAt(0)-1776)).replace(/(\d)\s?٫\s?(\d)/g,`$1.$2`).replace(/(\d)٬(\d)/g,`$1$2`)}var Qe=`(?:US\\$|[$€£¥₹]|E£)`,$e=`(?:USD|EUR|GBP|EGP|SAR|AED|dollars?|bucks|euros?|pounds?|دولار(?:ات)?|جنيه(?:ات)?|ريال(?:ات)?|درهم|يورو)`,et=`\\d{1,3}(?:,\\d{3})+(?:\\.\\d+)?|\\d+(?:[.,]\\d+)?`,tt=RegExp(`(${Qe})\\s?(${et})|(${et})\\s?(?:(${Qe})(?!\\s?\\d)|(${$e})(?!\\p{L}))`,`giu`);function nt(e){return Number(/^\d+,\d{1,2}$/.test(e)?e.replace(`,`,`.`):e.replace(/,/g,``))}function rt(e){let t=Ze(e),n=[];for(let e of t.matchAll(tt))n.push({value:nt(e[2]??e[3]),currency:e[1]??e[4]??e[5],index:e.index??0});return n}function it(e,t){let n=Number.isInteger(e)?String(e):e.toFixed(2),r=t.toLowerCase();return/^(?:us\$|\$|usd|dollars?|bucks|دولار(?:ات)?)$/.test(r)?`$${n}`:/^(?:€|eur|euros?|يورو)$/.test(r)?`€${n}`:/^(?:£|gbp|pounds?)$/.test(r)?`£${n}`:/^(?:e£|egp|جنيه(?:ات)?)$/.test(r)?`${n} EGP`:/^\p{L}/u.test(t)?`${n} ${t}`:`${t}${n}`}var at=/\b(?:should|must|needs? to|ought to|(?:is|are) supposed to|has to|have to)\s+(?:be|say|show|read|display|equal|contain|have|include|cost|come to)\b|\bexpected\b/gi,ot=/(?:من المفروض|المفروض|يفترض|لازم|يجب ان|يجب أن|ينبغي ان|ينبغي أن|المتوقع)/g;function st(e){let t=e.replace(/(?:[.!?](?!\d)|,?\s+(?:but|instead|and not|not)\b|\s+(?:مش|وليس|بدل|بس)\s).*$/is,``).trim(),n=rt(t)[0];if(n)return it(n.value,n.currency);let r=/(?:^|\s)(\d+\.\d{2})$/.exec(Ze(t));if(r)return r[1];let i=Xe(t.replace(/^(?:be|say|show|read|display|equal|contain|have|include|cost|come to)\s+/i,``).replace(/[.!?,]+$/,``));if(i)return i;if(/[؀-ۿ]/.test(t)){let e=We(t);if(e&&e.currency)return it(e.value,e.currency)}let a=/["“«]([^"”»]{1,80})["”»]/.exec(e);return a?a[1].trim():null}function ct(e){let t=e.trim();if(!t)return null;let n=[...t.matchAll(at),...t.matchAll(ot)].sort((e,t)=>(t.index??0)-(e.index??0));for(let e of n){let n=(e.index??0)+e[0].length,r=st(t.slice(n));if(r)return{expected:r,at:lt(t,e.index??0)/t.length}}return null}function lt(e,t){let n=0;for(let r of e.slice(0,t).matchAll(/[.!?؟]\s+/g))n=(r.index??0)+r[0].length;return n}function ut(e,t){return Math.round(e.start+(e.end-e.start)*t.at)}function dt(e,t){let n=rt(t)[0]?.value??(ft.test(Ze(t))?Number(Ze(t).trim()):null);if(n===null)return pt(e).includes(pt(t));let r=rt(e);return(r.length?r.map(e=>e.value):[...Ze(e).matchAll(/\d+(?:\.\d+)?/g)].map(e=>Number(e[0]))).some(e=>Math.abs(e-n)<.005)}var ft=/^\s*\d+\.\d{2}\s*$/,pt=e=>e.toLowerCase().replace(/[\s,]/g,``);function mt(e){return e.toLowerCase().replace(/[’']/g,`'`).replace(/[^a-z0-9'$.\s-]/g,` `).replace(/\.(?=\s|$)/g,` `).replace(/\s+/g,` `).trim().replace(/^(ok|okay|hey|um|uh|so|and|now|please|alright|all right)\s+/,``).replace(/\s+(please|thanks|thank you|now)$/,``).trim()}var ht=`(?:card|button|link|image|picture|photo|icon|logo|heading|title|header|footer|form|list|item|row|field|input|menu|navbar|nav|section|table|price|label|text|paragraph|dialog|modal|sidebar|banner|badge|avatar|tab|panel|box|cell|column|chart|summary|total)s?`,gt=[[/^(keep|keep (it|that|this|them|both|all|these|those|the changes?)|looks (good|great)|ship it|accept( it| that)?|approve( it)?|perfect|that's (good|great|it)|yes|yeah|yep|yes keep( it)?|lgtm)$/,{kind:`keep`}],[/^(undo|undo (it|that|this|the change)|revert( it| that)?|go back|discard( it| that)?|nope|no|reject( it| that)?|take (it|that) back|put it back)$/,{kind:`undo`}],[/^(cancel|stop|never ?mind|forget (it|that)|abort)$/,{kind:`cancel`}],[/^((select )?(the )?parent|go up( a level| one level)?|(go |one )?(level )?up one level|select (the )?(container|wrapper)|(go |select )?outside( it| this)?|zoom out)$/,{kind:`parent`}],[/^((select |go )?(inside|in)( it| this| one level)?|go down( a level| one level)|one level down|(select |pick )?(the )?(child|first child|inner (one|element|part)|one inside|thing inside)|zoom in)$/,{kind:`nav`,to:`child`}],[/^((select |pick |go to )?(the )?next( one| sibling| item| element| card| row)?)$/,{kind:`nav`,to:`next`}],[/^((select |pick |go to )?(the )?(previous|prev|one before)( one| sibling| item| element| card| row)?)$/,{kind:`nav`,to:`prev`}],[/^(clear|clear (the )?(pins|selection|all|everything)|deselect( all| everything| it| this| that)?|unselect( it| this| that| all)?|unpin( all| everything)?|select nothing)$/,{kind:`clear`}],[/^(start recording|record( a bug| this)?|(switch to |go to )?(record|write( a)? test) mode)$/,{kind:`mode`,mode:`record`}],[/^((stop recording)|(switch to |go to )?edit mode|edit)$/,{kind:`mode`,mode:`edit`}],[/^((switch to |go to )?use mode|use the app|let me use (it|the app)|interact)$/,{kind:`mode`,mode:`use`}],[/^((generate|make|write|create|save)( me)?( a| the)? (test|spec|playwright test)|turn (this|that|it) into a test)$/,{kind:`generate`}],[/^((run|rerun|re-run|try)( the| that| this| my)? (test|spec)( again)?|run it( again)?|test it)$/,{kind:`run`}],[/^(fix (it|this|that|the bug|this bug|that bug|the test|the failure)( please)?)$/,{kind:`fix`}],[/^((click|press|tap|hit)( on)?( (this|that|it|here))?)$/,{kind:`click`}],[/^scroll (up|down)( a bit| more)?$/,e=>({kind:`scroll`,dir:e[1]})],[/^(scroll|go) to (the )?(top|bottom)$/,e=>({kind:`scroll`,dir:e[3]})],[/^(reload|refresh)( the)?( app| page)?$/,{kind:`reload`}],[/^(help|what can i (say|do)|show (me )?(the )?(help|shortcuts|gestures|commands))$/,{kind:`help`}],[/^((open|show)( (this|that|it))? in (the |my )?(editor|code|vs ?code|cursor)|show (me )?the code( for (this|that|it))?|go to (the )?code)$/,{kind:`open`}],[/^select (this|that|it)$/,{kind:`select`}],[/^((pin|add) (this|that|it)( too| as well| also| to (the )?selection)?|(select )?(this|that) too|(and|also) (this|that)( one)?|(this|that) as well)$/,{kind:`add`}],[/^(?:select|pick|choose|grab|highlight) (?:the )?(?!(?:this|that|it|all|everything|nothing|none)$)([a-z][a-z -]{1,24}?)(?: (inside it|inside this|inside|in it|in this|around it|around this|outside it|outside))?(?: instead)?$/,_t],[RegExp(`^the ((?:[a-z]+ )?${ht})(?: (inside it|inside|in it|around it|outside|instead))?$`),_t],[RegExp(`^(?:the )?(${ht}) (inside)$`),_t]];function _t(e){let t=!e[2]||e[2]===`instead`?`any`:/^(inside|in )/.test(e[2])?`in`:`out`;return{kind:`find`,what:e[1].trim(),where:t}}function vt(e,t){let n=/^\s*type\s+(.+?)(?:\s+and\s+(?:press\s+|hit\s+)?(enter|submit|return))?[.!]?\s*$/i.exec(e);if(n)return{kind:`type`,text:n[1].replace(/^["“'‘]|["”'’]$/g,``),submit:!!n[2]};let r=mt(e);if(!r)return null;for(let[e,n]of gt){let i=e.exec(r);if(!i)continue;let a=typeof n==`function`?n(i):n;return a.kind===`fix`&&!t.hasFailingTest?null:a}return null}function yt(e){let t=/^(?:(?:but|and|so)\s+)?(?:(this|that|it|the [\w\s-]{1,30}?)\s+)?(?:should|must|needs to|ought to|is supposed to|has to)\s+(?:be|say|show|read|display|equal|contain|have|include)\s+(.+)$/i.exec(e.trim());if(!t)return null;let n=t[2].replace(/\s+(?:but|instead|and not|not)\b.*$/i,``).replace(/[.!?]+$/,``).trim();n=n.replace(/^["“'‘]|["”'’]$/g,``).trim();let r=/^(\d+(?:[.,]\d{1,2})?)\s*(?:dollars|bucks|usd)$/i.exec(n);return n=r?`$${r[1]}`:Xe(n)??n,n?{subject:t[1]?.toLowerCase()??null,expected:n}:null}function bt(e,t){let n=new Map(t.timeline.map(e=>[e.id,e])),r=new Set;for(let i of e.evidence){let e=n.get(i);if(e)r.add(e);else{let e=t.issues.find(e=>e.id===i);for(let t of e?.evidence??[]){let e=n.get(t);e&&r.add(e)}}}return Array.from(r).sort((e,t)=>e.t-t.t)}function xt(e,t){let n=Array.from(new Set(t.filter(e=>e.kind===`speech`).map(e=>`“${e.text}”`))),r=Array.from(new Set(t.filter(e=>e.kind!==`speech`&&e.kind!==`shot`).map(e=>e.text)));return[`What happened: ${e.what}`,e.expected?`Expected: ${e.expected}`:``,e.shown&&e.shown!==e.location?`Showed at: ${e.shown}`:``,e.location?`Likely cause: ${e.location}`:``,e.fix?`Suggested fix: ${e.fix}`:``,n.length?`The tester said: ${n.join(` `)}`:``,r.length?`Recorded: ${r.slice(0,5).join(`; `)}`:``].filter(Boolean)}var St=class{samples=[];push(e,t){let n=this.samples[this.samples.length-1];if(n&&n.t>=e)return;this.samples.push({t:e,el:t});let r=e-2e4;for(;this.samples.length&&this.samples[0].t<r;)this.samples.shift()}clear(){this.samples=[]}at(e){for(let t=this.samples.length-1;t>=0;t--)if(this.samples[t].t<=e)return this.samples[t].el;return null}dwellWinner(e,t){let n=new Map;for(let r=0;r<this.samples.length;r++){let i=this.samples[r],a=r+1<this.samples.length?this.samples[r+1].t:t,o=Math.max(i.t,e),s=Math.min(a,t);if(s<=o||!i.el)continue;let c=n.get(i.el.id)??{el:i.el,ms:0};c.ms+=s-o,n.set(i.el.id,c)}let r=null;for(let e of n.values())(!r||e.ms>r.ms)&&(r=e);return r?.el??null}},Ct=/^(this|that|these|those|here|there|it)$/i,wt=/^(that|those|there|ذلك|ذاك|تلك|هذاك|هذيك|هناك|هنيك)$/i,Tt={lagMs:380,windowMs:650},Et=e=>/[\u0600-\u06FF]/.test(e)?xe(e).replace(/[^\u0600-\u06FF]/g,``).replace(/^و(?=..)/,``):e.toLowerCase().replace(/[^a-z']/g,``);function Dt(e,t,n){let r=[],i=n.pins.slice();return e.forEach((e,a)=>{let o=Et(e.text);if(!Ct.test(o)&&!Te.test(o))return;if(o===`it`&&r.length){r.push({...r[r.length-1],word:o,index:a,t:e.t});return}if(i.length){r.push({word:o,index:a,t:e.t,el:i.shift(),via:`pin`});return}let s=e.t-n.lagMs,c=t.dwellWinner(s-n.windowMs,s+150)??t.at(s),l=c?`pointing`:`unresolved`;!c&&!r.length&&n.selection&&(c=n.selection,l=`selection`),c&&wt.test(o)&&r.some(e=>e.el?.id===c.id&&!wt.test(e.word))&&(c=null,l=`unresolved`),r.push({word:o,index:a,t:e.t,el:c,via:l})}),r}function Ot(e,t,n){return e.length?e:t?[t]:n?[n]:[]}var kt=class{y=null;filter(e,t){return this.y=this.y===null?e:t*e+(1-t)*this.y,this.y}last(){return this.y}reset(){this.y=null}},At=(e,t)=>1/(1+1/(2*Math.PI*e)/t),jt=class{minCutoff;beta;dCutoff;x=new kt;dx=new kt;t=null;constructor(e=1,t=.01,n=1){this.minCutoff=e,this.beta=t,this.dCutoff=n}filter(e,t){let n=this.t===null?1/30:Math.max(.001,(t-this.t)/1e3);this.t=t;let r=this.x.last(),i=r===null?0:(e-r)/n,a=this.dx.filter(i,At(this.dCutoff,n)),o=this.minCutoff+this.beta*Math.abs(a);return this.x.filter(e,At(o,n))}reset(){this.x.reset(),this.dx.reset(),this.t=null}},Mt=class{fx;fy;constructor(e,t){this.fx=new jt(e,t),this.fy=new jt(e,t)}set(e,t){this.fx.minCutoff=this.fy.minCutoff=e,this.fx.beta=this.fy.beta=t}filter(e,t,n){return{x:this.fx.filter(e,n),y:this.fy.filter(t,n)}}reset(){this.fx.reset(),this.fy.reset()}};function Nt(e){let t=Math.max(0,Math.min(1,e));return{minCutoff:3.2-2.75*t,beta:.012-.0085*t}}var Pt=[[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]],Ft=[[0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[0,17],[17,18],[18,19],[19,20]];function It(e,t,n){return Math.hypot((e.x-t.x)*n,e.y-t.y,(e.z-t.z)*n)}function Lt(e,t,n){return[(e.x-t.x)*n,e.y-t.y,(e.z-t.z)*n]}function Rt(e,t){let n=Math.hypot(...e),r=Math.hypot(...t);return!n||!r?0:(e[0]*t[0]+e[1]*t[1]+e[2]*t[2])/(n*r)}var zt=e=>Math.max(0,Math.min(1,e));function Bt(e,t){return(It(e[0],e[9],t)+It(e[5],e[17],t)*1.25)/2}function Vt(e,t,n){let[r,i,,a]=t,o=It(e[0],e[a],n)/Math.max(1e-6,It(e[0],e[i],n)),s=Rt(Lt(e[i],e[r],n),Lt(e[a],e[i],n));return zt((o-1)/.32)*.55+zt((s+.1)/.9)*.45}function Ht(e,t){let n=(e,t)=>Math.acos(Math.max(-1,Math.min(1,Rt(e,t))))*180/Math.PI,[r,i,a,o,s]=[e[0],e[5],e[6],e[7],e[8]];return n(Lt(i,r,t),Lt(a,i,t))+n(Lt(a,i,t),Lt(o,a,t))+n(Lt(o,a,t),Lt(s,o,t))}var Ut=150;function Wt(e){return e.indexFlex<Ut&&e.thumbMiddle>.4}function Gt(e,t){let n=Bt(e,t),r=Pt.map(n=>Vt(e,n,t)),i=(e[4].x-e[2].x)*t,a=e[4].y-e[2].y,o=Math.hypot(i,a)||1;return{fingers:r,indexFlex:Ht(e,t),thumbMiddle:It(e[4],e[10],t)/n,thumbOut:It(e[4],e[5],t)/n,thumbDir:{x:i/o,y:a/o},pinch:It(e[4],e[8],t)/n,scale:n}}var Kt=.62,qt=.42;function Jt(e){let[t,n,r,i]=e.fingers,a=e=>e<qt,o=e=>e>Kt,s=a(t)&&a(n)&&a(r)&&a(i),c=e.thumbOut>.5,l=e.pinch<.45&&Wt(e);return!l&&s&&c&&e.thumbDir.y<-.7?`thumbUp`:!l&&s&&c&&e.thumbDir.y>.7?`thumbDown`:o(t)&&o(n)&&o(r)&&o(i)?`open`:o(t)&&o(n)&&a(r)&&a(i)?`victory`:o(t)&&a(n)&&a(r)?`point`:s&&!l&&e.indexFlex>=Ut?`fist`:`other`}var Yt={hand:`any`,box:{x0:.18,y0:.14,x1:.82,y1:.74},steadiness:.55,pinchOn:.3,pinchOff:.44,palmHoldMs:700,thumbHoldMs:380,talkHoldMs:320,pinchHoldMs:650,palmEnabled:!0,thumbsEnabled:!0,talkEnabled:!0},Xt=260,Zt=110,Qt=900,$t=.045,en=.5,tn=180,nn=.6,rn=1200,an=.07,on=class{settings;viewport;state={present:!1,x:0,y:0,pose:`other`,pinchAmount:0,pinching:!1,pinchHold:0,dragging:!1,holdKind:null,holdProgress:0,clutched:!1,hand:null,landmarks:null,lastSeen:0};filter;history=[];fingers=[];held=null;lastOpen=-1/0;lastWrist=null;candidate={pose:`other`,since:0};stablePose=`other`;poseSince=0;holdFired=!1;pinchFrames=0;releaseFrames=0;pinch=null;prevCursor=null;speed=0;constructor(e,t){this.settings=e,this.viewport=t;let n=Nt(e.steadiness);this.filter=new Mt(n.minCutoff,n.beta)}configure(e){this.settings={...this.settings,...e};let t=Nt(this.settings.steadiness);this.filter.set(t.minCutoff,t.beta)}toScreen(e){let{w:t,h:n}=this.viewport(),r=this.settings.box,i=(1-e.x-r.x0)/Math.max(.05,r.x1-r.x0),a=(e.y-r.y0)/Math.max(.05,r.y1-r.y0);return{x:Math.max(0,Math.min(t,i*t)),y:Math.max(0,Math.min(n,a*n))}}pickHand(e){if(!e.length)return null;let t=e=>e.handedness===`Left`?`right`:`left`,n=e;if(this.settings.hand!==`any`){let r=e.filter(e=>t(e)===this.settings.hand);r.length&&(n=r)}if(this.lastWrist){let e=null,t=1/0;for(let r of n){let n=Math.hypot(r.landmarks[0].x-this.lastWrist.x,r.landmarks[0].y-this.lastWrist.y);n<t&&(t=n,e=r)}if(e&&t<.25)return e}return n.reduce((e,t)=>t.landmarks[8].y<e.landmarks[8].y?t:e)}holdKindFor(e){let t=this.settings;return e===`open`?t.palmEnabled?`palm`:null:e===`thumbUp`||e===`thumbDown`?t.thumbsEnabled?e:null:e===`victory`&&t.talkEnabled?`victory`:null}lookback(e){for(let t=this.history.length-1;t>=0;t--)if(this.history[t].t<=e)return this.history[t];return null}aim(e,t,n,r){let i=n.x-r.x,a=n.y-r.y,o=this.fingers.find(t=>t.t>=e-120);for(this.fingers.push({t:e,d:t,ox:i,oy:a});this.fingers.length&&this.fingers[0].t<e-700;)this.fingers.shift();if(!this.held){let n=this.fingers[0];for(let e of this.fingers)e.d>=n.d&&(n=e);t<n.d-an&&t<.95&&(this.held={ox:n.ox,oy:n.oy,at:t,since:e})}else if(!this.state.pinching){let n=!!o&&t<o.d-.01;(t>this.held.at+.02||t>=nn&&!n&&e-this.held.since>250)&&(this.held=null)}let s=this.held??{ox:i,oy:a};return{x:r.x+s.ox,y:r.y+s.oy}}scrollDistance(){let{w:e,h:t}=this.viewport();return Math.max(40,$t*Math.hypot(e,t))}endPinch(e,t){let n=this.pinch;n&&(t?e.push(this.state.dragging?{type:`dragEnd`,x:this.state.x,y:this.state.y}:{type:`pinchCancel`}):this.state.dragging?e.push({type:`dragEnd`,x:this.state.x,y:this.state.y}):e.push({type:`tap`,x:n.anchorX,y:n.anchorY,held:n.held}),this.pinch=null,this.state.pinching=!1,this.state.pinchHold=0,this.state.dragging=!1)}update(e){let t=[],n=this.state,r=e.t,i=this.pickHand(e.hands);if(!i)return n.present&&r-n.lastSeen>Xt&&(this.endPinch(t,!0),n.present=!1,n.landmarks=null,n.holdKind=null,n.holdProgress=0,n.clutched&&(n.clutched=!1,t.push({type:`clutch`,on:!1})),this.lastWrist=null,this.history=[],this.fingers=[],this.held=null,this.filter.reset(),this.prevCursor=null,t.push({type:`lost`})),t;let a=i.landmarks,o=Gt(a,e.aspect),s=Jt(o),c=n.present;if(n.present=!0,n.lastSeen=r,n.landmarks=a,n.hand=i.handedness===`Left`?`right`:`left`,this.lastWrist={x:a[0].x,y:a[0].y},c||t.push({type:`found`}),s!==this.candidate.pose&&(this.candidate={pose:s,since:r}),this.candidate.pose!==this.stablePose&&r-this.candidate.since>=Zt&&(this.stablePose=this.candidate.pose,this.poseSince=r,this.holdFired=!1,this.stablePose===`fist`||this.stablePose===`thumbUp`||this.stablePose===`thumbDown`)){let e=this.lookback(r-Zt-60);e&&(n.x=e.x,n.y=e.y)}let l=Wt(o),{pinchOn:u,pinchOff:d}=this.settings;o.pinch>=nn&&(this.lastOpen=r);let f=r-this.lastOpen<=rn;n.pinching?this.releaseFrames=o.pinch>d||!l?this.releaseFrames+1:0:this.pinchFrames=l&&f&&o.pinch<u?this.pinchFrames+1:0;let p=d*1.9;n.pinchAmount=Math.max(0,Math.min(1,(p-o.pinch)/(p-u)));let m=this.toScreen(a[5]),h=this.aim(r,o.pinch,this.toScreen(a[8]),m),g=this.stablePose===`fist`&&!n.pinching,_=!n.pinching&&(this.stablePose===`thumbUp`||this.stablePose===`thumbDown`);if(g!==n.clutched&&(n.clutched=g,t.push({type:`clutch`,on:g})),!n.pinching&&this.pinchFrames>=2){let e={x:n.x,y:n.y};this.pinch={t:r,anchorX:e.x,anchorY:e.y,kx:m.x,ky:m.y,offX:0,offY:0,moved:0,held:!1},n.pinching=!0,this.releaseFrames=0,t.push({type:`pinchStart`,x:e.x,y:e.y})}else n.pinching&&this.releaseFrames>=2&&(this.endPinch(t,!l&&o.pinch<=d),this.pinchFrames=0,this.filter.reset());if(n.pinching&&this.pinch){let e=this.pinch,i=this.scrollDistance();if(e.moved=Math.max(e.moved,Math.hypot(m.x-e.kx,m.y-e.ky)),!n.dragging&&e.moved>i&&(n.dragging=!0,n.pinchHold=0,e.offX=e.anchorX-e.kx,e.offY=e.anchorY-e.ky,t.push({type:`dragStart`,x:e.anchorX,y:e.anchorY})),!n.dragging&&!e.held){let a=e.moved<=i*en,o=this.settings.pinchHoldMs;n.pinchHold=a?Math.max(0,Math.min(1,(r-e.t-tn)/Math.max(1,o-tn))):0,a&&r-e.t>=o&&(e.held=!0,n.pinchHold=1,t.push({type:`hold`,x:e.anchorX,y:e.anchorY}))}if(n.dragging){let i=this.filter.filter(m.x+e.offX,m.y+e.offY,r),a=i.x-n.x,o=i.y-n.y;n.x=i.x,n.y=i.y,(a||o)&&t.push({type:`drag`,x:n.x,y:n.y,dx:a,dy:o})}else this.filter.filter(e.anchorX,e.anchorY,r)}else if(!g&&!_){let e=this.filter.filter(h.x,h.y,r);n.x=e.x,n.y=e.y}if(this.prevCursor){let e=Math.max(1,r-this.prevCursor.t)/1e3,t=Math.hypot(h.x-this.prevCursor.x,h.y-this.prevCursor.y)/e;this.speed=this.speed*.7+t*.3}for(this.prevCursor={t:r,x:h.x,y:h.y},this.history.push({t:r,x:n.x,y:n.y});this.history.length&&this.history[0].t<r-400;)this.history.shift();let v=n.pinching?null:this.holdKindFor(this.stablePose);if(v&&this.speed>Qt&&!this.holdFired&&(this.poseSince=r),n.holdKind=v,v){let e=v===`palm`?this.settings.palmHoldMs:v===`victory`?this.settings.talkHoldMs:this.settings.thumbHoldMs;n.holdProgress=this.holdFired?1:Math.min(1,(r-this.poseSince)/e),!this.holdFired&&n.holdProgress>=1&&(this.holdFired=!0,t.push({type:v}))}else n.holdProgress=0;return n.pose=n.pinching?`pinch`:this.stablePose,t}};function sn(e){return e.pins.length?e.pins:e.selection?[e.selection]:[]}function cn(e,t){let n=new Set,r=e.filter(e=>!n.has(e.id)&&(n.add(e.id),!0)).slice(-8);return{selection:t&&r.find(e=>e.id===t.id)||r[r.length-1]||null,pins:r.length>1?r:[]}}function ln(e,t){return e.some(e=>e.id===t.id)?e.filter(e=>e.id!==t.id):[...e,t]}function un(e,t){return e?t.some(t=>t.id===e.id)?t.length===1?{tap:`deselect`,hold:`none`}:{tap:`only`,hold:`remove`}:{tap:`select`,hold:t.length?`add`:`none`}:{tap:t.length?`clear`:`none`,hold:`none`}}function dn(e,t){let{tap:n}=un(t,sn(e));return n===`select`||n===`only`?cn([t]):n===`deselect`||n===`clear`?cn([]):e}function fn(e,t){if(!t)return e;let n=sn(e),r=ln(n,t);return cn(r,r.length>n.length?t:e.selection)}function pn(e,t,n){return cn(sn(e).map(e=>e.id===t.id?n:e),n)}function mn(e){let t=[e.url,e.dialog??``,e.text,...e.controls.map(e=>`${e.role}|${e.name}|${e.field?`${e.field.value}|${e.field.checked??``}`:``}|${e.disabled}`)],n=2166136261;for(let e of t.join(`
3
+ `))n^=e.codePointAt(0),n=Math.imul(n,16777619);return(n>>>0).toString(36)}var hn=/\b(delete|remove account|destroy|erase|deactivate|close (?:my )?account|log ?out|sign ?out|unsubscribe|pay|purchase|buy now|place (?:the |my )?order|confirm (?:order|payment|purchase)|send|transfer|withdraw|publish|deploy|reset all)\b|حذف|احذف|إلغاء الاشتراك|تسجيل الخروج|خروج|ادفع|دفع|شراء|اشتر|إرسال|أرسل|تحويل|نشر/i,gn=e=>hn.test(e);function _n(e,t){let n=t?`“${t.name||t.role}”`:``;switch(e.kind){case`click`:return`Clicked ${n}`;case`fill`:return`Typed “${e.value??``}” into ${n}`;case`select`:return`Chose “${e.value??``}” in ${n}`;case`check`:return`${e.value===`off`?`Unticked`:`Ticked`} ${n}`;case`press`:return t?`Pressed ${e.value||`Enter`} in ${n}`:`Pressed ${e.value||`Enter`}`;case`scroll`:return`Scrolled down`;case`back`:return`Went back`;case`goto`:return`Opened ${e.value??`/`}`;case`done`:return`Finished`}}var vn=e=>new Promise(t=>setTimeout(t,e)),yn=3,bn=class{host;running=!1;stopped=!1;constructor(e){this.host=e}stop(){this.stopped=!0}async connected(e){let t=performance.now()+e;for(;!this.host.connected();){if(performance.now()>t||this.stopped)return!1;await vn(100)}return!0}async look(){for(let e=0;e<4&&!this.stopped;e++){if(await this.connected(5e3)){let e=await this.host.bridge.explore();if(e)return e}await vn(500)}return null}async act(e,t,n,r){let i=e.control?t.controls[e.control-1]:void 0,a=new URL(t.url).origin;switch(e.kind){case`click`:case`fill`:case`select`:case`check`:case`press`:{if(e.kind===`press`&&!i){let t=await this.host.bridge.replay(`page.locator('body')`,{kind:`press`,key:e.value||`Enter`},!1,void 0,4e3);return t.ok?{ok:!0}:{ok:!1,error:t.error??`failed`}}if(!i)return{ok:!1,error:`not on the page`};if(!r.allowRisky&&gn(i.name))return{ok:!1,error:`not allowed`};let t=await this.host.bridge.replay(i.locator,void 0,!1,void 0,2500);if(!t.ok||!t.info)return{ok:!1,error:t.error??`missing`};this.host.point(t.info,!1),await vn(400);let n=e.kind===`click`?{kind:`click`}:e.kind===`press`?{kind:`press`,key:e.value||`Enter`}:e.kind===`check`?{kind:`fill`,checked:e.value!==`off`}:{kind:`fill`,value:e.value??``},a=await this.host.bridge.replay(i.locator,n,!1,void 0,4e3);return this.host.point(t.info,!0),a.ok?{ok:!0}:{ok:!1,error:a.error??`failed`}}case`scroll`:{let[e,n]=t.viewport;return this.host.bridge.scroll(e/2,n/2,0,Math.round(n*.8)),{ok:!0}}case`back`:return n?(this.host.bridge.goto(n),{ok:!0}):{ok:!1,error:`no page before this one`};case`goto`:{let n=new URL(e.value||`/`,t.url);return n.origin===a?(this.host.bridge.goto(n.href),{ok:!0}):{ok:!1,error:`outside the app`}}case`done`:return{ok:!0}}}async run(e){if(this.running)return;this.running=!0,this.stopped=!1;let t={phase:`starting`,goal:e.goal,step:0,total:e.maxSteps,description:`Starting a test session`,found:0};this.host.show({...t});let n=null,r=null,i=[],a=[],o=[],s=0,l=Date.now(),u=!1;try{await c.post(`/autopilot/ready`,{});let u=await c.post(`/sessions`,{name:(e.goal?`Autopilot: ${e.goal}`:`Autopilot`).slice(0,120),appUrl:this.host.appUrl(),source:`autopilot`,lang:`en`,replace:!0});if(n=u.session.id,!await this.host.bridge.session(!0,n,location.origin,u.key))throw Error(`not-recording`);r=this.host.enterUse();for(let r=1;r<=e.maxSteps&&!this.stopped;r++){Object.assign(t,{phase:`thinking`,step:r,description:r===1?`Reading the page`:t.description}),this.host.show({...t});let u=await this.look();if(!u)throw Error(`Your app stopped answering: is it still running?`);o[o.length-1]!==u.url&&o.push(u.url);let{turn:d}=await c.post(`/autopilot/turn`,{session:n,goal:e.goal,step:r,maxSteps:e.maxSteps,allowRisky:e.allowRisky,since:l,snapshot:u,history:i,reported:a});if(a.push(...d.findings.map(e=>e.title)),Object.assign(t,{phase:`acting`,description:d.thought,found:a.length}),this.host.show({...t}),d.action.kind===`done`||this.stopped)break;let f=this.host.connections();l=Date.now();let p=d.action.control?u.controls[d.action.control-1]:void 0,m=await this.act(d.action,u,o[o.length-2]??null,e);await vn(900),this.host.connections()!==f&&await this.connected(1e4);let h=m.error===`not allowed`?`Skipped ${p?`“${p.name}”`:`a control`} (not allowed)`:_n(d.action,p);if(i.push({n:r,did:h,ok:m.ok,...m.error?{error:m.error}:{},url:this.host.appUrl()||u.url,page:mn(u)}),s=m.ok?0:s+1,s>=yn){this.host.notify(`Autopilot stopped: its last steps didn’t work.`);break}}Object.assign(t,{phase:`finishing`,description:`Writing the report`}),this.host.show({...t}),this.host.point(null,!1),await vn(1e3)}catch(e){u=!0;let t=e instanceof Error?e.message:String(e);this.host.notify(t===`not-recording`?`Autopilot couldn’t start: your app didn’t start recording.`:`Autopilot ${n&&i.length?`stopped`:`couldn’t start`}: ${t}`)}finally{let e=u&&!i.length;n&&(await this.host.bridge.session(!1),await c.post(`/sessions/${n}/stop`,{}).catch(()=>void 0),e&&await c.delete(`/sessions/${n}`).catch(()=>void 0)),r?.(),this.host.show(null),this.host.point(null,!1),this.running=!1,n&&!e&&this.host.openReport(n)}}},xn=e=>e.locator?.startsWith(`page.locator('[data-ds-src=`)?{tag:e.tag,name:e.name,text:e.text,...e.shape?{shape:e.shape}:{}}:void 0,Sn=e=>new Promise(t=>setTimeout(t,e));function Cn(e,t){if(!e||!t?.locator)return null;let n=ct(e.text);return n?{expected:n.expected,locator:t.locator,like:xn(t),t:ut(e,n),el:t}:null}function wn(e){let t=e.analysis;if(!t)return[];let n=[];for(let e of t.issues){if(e.kind!==`said`)continue;let r=Cn(t.transcript.find(t=>t.start===e.t),e.el);r&&n.push({issue:e.id,...r})}for(let r of e.report?.findings??[]){let e=Tn(r,t);e&&n.push({finding:r.id,...e})}return n}function Tn(e,t){let n=bt(e,t);for(let e of n){let n=e.kind===`speech`?t.transcript.find(t=>t.start===e.t):void 0,r=Cn(n,n?.el);if(r)return r}let r=Dn(n,t).find(e=>e.locator),i=r?En(e,r):null;return r?.locator&&i?{expected:i,locator:r.locator,like:xn(r),t:Math.max(...n.map(e=>e.t)),el:r}:null}function En(e,t){let n=ct(e.quote??``);if(n)return n.expected;let r=e.expected??``,i=rt(r),a=(t.label||t.text).toLowerCase().match(/\p{L}{3,}/gu)??[],o=i.length===1?i[0]:i.find(e=>a.some(t=>r.toLowerCase().slice(Math.max(0,e.index-24),e.index).includes(t)));return o?it(o.value,o.currency):null}function Dn(e,t){let n=[];for(let r of e){let e=r.kind===`speech`?t.transcript.find(e=>e.start===r.t):null,i=r.issue?t.issues.find(e=>e.id===r.issue):null,a=e?.el??i?.el;a&&!n.some(e=>e.src===a.src&&e.label===a.label)&&n.push(a)}return n}var On=class{host;running=null;stopped=!1;constructor(e){this.host=e}stop(){this.stopped=!0}async connected(e){let t=performance.now()+e;for(;!this.host.connected();){if(performance.now()>t)return!1;await Sn(100)}return!0}async locate(e,t,n=6e3){let r=performance.now()+n,i=`missing`;for(;;){if(await this.connected(5e3)){let n=await this.host.bridge.replay(e,void 0,!1,t,1500);if(n.ok&&n.info)return{info:n.info};if(i=n.error??i,i===`unreadable`)return{info:null,error:i}}else i=`disconnected`;if(performance.now()>r||this.stopped)return{info:null,error:i};await Sn(250)}}async read(e){let t=performance.now()+1500;for(;;){let n=await this.connected(3e3)?await this.host.bridge.replay(e.locator,void 0,!0,e.like):null,r=n?.ok?n.text??``:null,i=r!==null&&dt(r,e.expected);if(i||performance.now()>t||this.stopped)return{actual:r,ok:i};await Sn(250)}}async run(e){let t=e.analysis;if(!t||this.running)return;this.running=e.meta.id,this.stopped=!1;let n=t.steps.filter(e=>e.kind!==`navigate`&&!!e.locator),r=wn(e).sort((e,t)=>e.t-t.t),i=[],a={id:e.meta.id,name:e.meta.name,phase:`starting`,step:0,total:n.length,description:`Opening the page the session started on`,target:null};this.host.show({...a});let o=null,s=null,l=0,u;try{let d=t.steps.find(e=>e.kind===`navigate`)?.url??t.pages[0]?.url??e.meta.appUrl,f=new URL(this.host.appUrl()||d),p=new URL(d,f),m=this.host.connections();this.host.bridge.goto(`${f.origin}${p.pathname}${p.search}${p.hash}`);let h=performance.now()+15e3;for(;!(this.host.connections()>m&&this.host.connected());){if(performance.now()>h)throw Error(`Your app didn’t load again: is it still running?`);if(this.stopped)throw Error(`stopped`);await Sn(100)}await Sn(700);let{session:g,key:_}=await c.post(`/sessions`,{name:`Replay of ${e.meta.name}`.slice(0,120),appUrl:this.host.appUrl(),source:`replay`,replayOf:e.meta.id,lang:e.meta.lang});if(o=g.id,!await this.host.bridge.session(!0,o,location.origin,_))throw Error(`not-recording`);s=this.host.enterUse();let v=0,y=async e=>{for(;v<r.length&&r[v].t<=e;){let e=r[v++],{actual:t,ok:n}=i.find((t,n)=>r[n].locator===e.locator&&r[n].t===e.t&&t.expected===e.expected)??await this.read(e);i.push({finding:e.finding,issue:e.issue,expected:e.expected,actual:t,ok:n})}};for(let e=0;e<n.length;e++){if(this.stopped){u={i:e,t:n[e].t,description:n[e].description,descriptionAr:n[e].descriptionAr,reason:`stopped`};break}let t=n[e];await y(t.t),Object.assign(a,{phase:`playing`,step:e+1,description:t.description,target:null}),this.host.show({...a});let r=await this.locate(t.locator,t.like);if(!r.info){u={i:e,t:t.t,description:t.description,descriptionAr:t.descriptionAr,reason:r.error??`missing`};break}a.target=r.info,this.host.show({...a}),this.host.point(r.info,!1),await Sn(450);let i=await this.host.bridge.replay(t.locator,{kind:t.kind,value:t.value,key:t.key,checked:t.checked},!1,t.like);if(!i.ok){u={i:e,t:t.t,description:t.description,descriptionAr:t.descriptionAr,reason:i.error??`failed`};break}this.host.point(r.info,!0),l++,a.target=null,this.host.show({...a});let o=n[e+1]?n[e+1].t-t.t:1200;await Sn(Math.max(500,Math.min(1800,o)))}u||await y(1/0),Object.assign(a,{phase:`finishing`,description:`Comparing with the session`,target:null}),this.host.show({...a}),this.host.point(null,!1),await Sn(1200)}catch(e){let t=e instanceof Error?e.message:String(e),r=n[l];!u&&r&&(u={i:l,t:r.t,description:r.description,descriptionAr:r.descriptionAr,reason:t===`stopped`||t===`not-recording`?t:`error`}),t!==`stopped`&&this.host.notify(t===`not-recording`?`The replay couldn’t run: your app didn’t start recording it.`:`The replay couldn’t run: ${t}`)}finally{if(o){await this.host.bridge.session(!1),await c.post(`/sessions/${o}/stop`,{}).catch(()=>void 0);let t={steps:{total:n.length,done:l,failed:u},checks:i};await c.put(`/sessions/${e.meta.id}/verify`,{replay:o,outcome:t}).catch(()=>void 0)}s?.(),this.host.show(null),this.host.point(null,!1),this.running=null,o&&this.host.openReport(e.meta.id)}}},kn=4e3,An=0,jn=class{deps;current=null;queue=[];constructor(e){this.deps=e}get busy(){return!!this.current}has(e){return this.current?.job.kind===e||this.queue.some(t=>t.job.kind===e)}ask(e){return this.current&&this.queue.length>=3?null:new Promise(t=>{let n={id:`r${++An}-${Date.now().toString(36)}`,job:e,done:t,stopped:!1};if(!this.current)return void this.begin(n,!0);this.queue.push(n),this.publish()})}stop(){let e=this.current;if(!e)return null;let t=this.queue.splice(0);for(let e of t)e.done();return this.publish(),e.stopped||(e.stopped=!0,this.deps.stopping(e.id),this.deps.cancel(e.id),setTimeout(()=>this.current===e&&this.release(e),kn)),t.length}async begin(e,t){this.current=e,this.deps.started({id:e.id,text:e.job.text,kind:e.job.kind,step:e.job.step,startedAt:Date.now()},t);try{await e.job.run(e.id,()=>e.stopped)}catch(t){e.stopped||this.deps.fail(t)}finally{e.done(),this.current===e&&this.release(e)}}release(e){this.deps.ended(e.id),this.current=null;let t=this.queue.shift();this.publish(),t&&this.begin(t,!1)}publish(){this.deps.waiting(this.queue.map(e=>({id:e.id,text:e.job.text})))}},Mn=`odml.pa.googleapis.com`;function Nn(e){try{return new URL(typeof e==`string`?e:e instanceof URL?e.href:e.url,globalThis.location?.href).hostname}catch{return``}}function Pn(e){let t=e.fetch,n=(n,r)=>Nn(n)===Mn?Promise.reject(TypeError(`MediaPipe’s usage log is off`)):t.call(e,n,r);return e.fetch=n,()=>{e.fetch===n&&(e.fetch=t)}}var Fn=`/models/hand_landmarker.task`,In=`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@1.1.0/wasm`,Ln=`https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task`;async function Rn(){try{let e=await fetch(Fn,{method:`HEAD`});if(e.ok&&Number(e.headers.get(`content-length`)??`1`)>1e6)return Fn}catch{}return Ln}function zn(){try{let e=document.createElement(`canvas`).getContext(`webgl2`);if(!e)return!0;let t=e.getExtension(`WEBGL_debug_renderer_info`);return/swiftshader|llvmpipe|softpipe|software|basic render/i.test(String(t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER)))}catch{return!0}}var Bn=3e3,Vn=class{landmarker=null;unblock=null;worker=null;inFlight=0;where=null;detectMs=0;video=null;running=!1;lastVideoTime=-1;frames=[];delegate=`GPU`;fps=0;onFrame=null;numHands=1;async init(){if(this.landmarker||this.worker)return;let e=await Rn();if(typeof Worker<`u`&&typeof VideoFrame<`u`&&typeof OffscreenCanvas<`u`)try{await this.initWorker(e),this.where=`worker`;return}catch(e){console.warn(`[saywright] hand tracking couldn’t run in a worker; running it on the page`,e),this.worker?.terminate(),this.worker=null}await this.initPage(e),this.where=`page`}initWorker(e){let t=new Worker(new URL(`/assets/tracker.worker-DWwj76VA.js`,``+import.meta.url),{type:`module`});return this.worker=t,new Promise((n,r)=>{let i=setTimeout(()=>r(Error(`the model took too long to load`)),45e3);t.onmessage=e=>{let a=e.data;a.type===`ready`?(clearTimeout(i),this.delegate=a.delegate,t.onmessage=e=>this.onResult(e.data),n()):a.type===`failed`&&(clearTimeout(i),r(Error(a.message)))},t.onerror=e=>{clearTimeout(i),r(e.error??Error(e.message||`worker error`))},t.postMessage({type:`init`,model:new URL(e,location.href).href,wasm:new URL(In,location.href).href,numHands:this.numHands})})}onResult(e){e.type===`delegate`&&(this.delegate=e.delegate),e.type===`result`&&(this.inFlight=0,e.ms!=null&&(this.detectMs=this.detectMs?this.detectMs*.9+e.ms*.1:e.ms),e.error&&console.warn(`[saywright] hand tracking frame failed`,e.error),this.running&&(this.count(e.t),this.onFrame?.({t:e.t,hands:e.hands,aspect:e.aspect})))}count(e){for(this.frames.push(e);this.frames.length&&this.frames[0]<e-1e3;)this.frames.shift();this.fps=this.frames.length}async initPage(e){let{FilesetResolver:t,HandLandmarker:n}=await i(async()=>{let{FilesetResolver:e,HandLandmarker:t}=await import(`./vision_bundle-ByYCzljp.js`);return{FilesetResolver:e,HandLandmarker:t}},__vite__mapDeps([0,1]));this.unblock??=Pn(window);let r=await t.forVisionTasks(In),a=t=>({baseOptions:{modelAssetPath:e,delegate:t},runningMode:`VIDEO`,numHands:this.numHands,minHandDetectionConfidence:.6,minHandPresenceConfidence:.6,minTrackingConfidence:.5}),o=zn()?`CPU`:`GPU`;try{this.landmarker=await n.createFromOptions(r,a(o)),this.delegate=o}catch{this.landmarker=await n.createFromOptions(r,a(`CPU`)),this.delegate=`CPU`}}async setNumHands(e){e!==this.numHands&&(this.numHands=e,this.worker?.postMessage({type:`numHands`,n:e}),await this.landmarker?.setOptions({numHands:e}).catch(()=>void 0))}start(e){this.video=e,!this.running&&(this.running=!0,this.schedule())}stop(){this.running=!1}dispose(){this.stop(),this.landmarker?.close(),this.landmarker=null,this.unblock?.(),this.unblock=null,this.worker?.postMessage({type:`close`}),this.worker?.terminate(),this.worker=null,this.inFlight=0}schedule(){if(!this.running)return;let e=this.video;e?.requestVideoFrameCallback?e.requestVideoFrameCallback(this.tick):requestAnimationFrame(this.tick)}send(e){let t=performance.now();if(this.inFlight&&t-this.inFlight<Bn)return;let n;try{n=new VideoFrame(e,{timestamp:Math.round(t*1e3)})}catch{return}this.lastVideoTime=e.currentTime,this.inFlight=t,this.worker.postMessage({type:`frame`,image:n,t,aspect:e.videoWidth/e.videoHeight},[n])}tick=()=>{if(!this.running)return;let e=this.video;if(e&&this.worker&&e.readyState>=2&&e.currentTime!==this.lastVideoTime&&e.videoWidth>0)this.send(e);else if(e&&this.landmarker&&e.readyState>=2&&e.currentTime!==this.lastVideoTime&&e.videoWidth>0){this.lastVideoTime=e.currentTime;let t=performance.now();try{let n=this.landmarker.detectForVideo(e,t),r=n.landmarks.map((e,t)=>({landmarks:e,handedness:n.handedness[t]?.[0]?.categoryName===`Left`?`Left`:`Right`,score:n.handedness[t]?.[0]?.score??0}));this.detectMs=this.detectMs?this.detectMs*.9+(performance.now()-t)*.1:performance.now()-t,this.count(t),this.onFrame?.({t,hands:r,aspect:e.videoWidth/e.videoHeight})}catch(e){console.warn(`[saywright] hand tracking frame failed`,e)}}this.schedule()}},Hn=[],Un=new Set,Wn=new Set([`SCRIPT`,`STYLE`,`LINK`,`TEMPLATE`]),Gn=new WeakSet;function Kn(e){Gn.add(e)}function qn(e){return e.defaultPrevented&&!Gn.has(e)}function Jn(){return Hn.length>0}function Yn(){return Hn[Hn.length-1]??null}function Xn(e){return Hn.includes(e)||Hn.push(e),Zn(),()=>{let t=Hn.indexOf(e);t>=0&&Hn.splice(t,1),Zn()}}function Zn(){let e=Yn(),t=new Set;for(let n=e;n&&n!==document.body;n=n.parentElement)for(let e of n.parentElement?.children??[])e!==n&&!Wn.has(e.tagName)&&!e.hasAttribute(`data-layer-backdrop`)&&t.add(e);for(let e of Un)t.has(e)||(e.removeAttribute(`inert`),Un.delete(e));for(let e of t)e.hasAttribute(`inert`)||(e.setAttribute(`inert`,``),Un.add(e))}var Qn=`a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex], [contenteditable="true"]`;function $n(e){return[...e.querySelectorAll(Qn)].filter(e=>e.tabIndex>=0&&!e.closest(`[inert]`)&&e.getClientRects().length>0)}function er(e,t){let n=$n(t),r=document.activeElement;if(!n.length){e.preventDefault(),t.focus();return}let i=n[0],a=n[n.length-1],o=!!r&&t.contains(r);e.shiftKey&&(!o||r===i)?(e.preventDefault(),a.focus()):!e.shiftKey&&(!o||r===a)&&(e.preventDefault(),i.focus())}var tr=16e3,nr=tr/2,rr=`class C extends AudioWorkletProcessor{constructor(){super();this.b=new Float32Array(512);this.n=0}process(i){const c=i[0]&&i[0][0];if(c){for(let k=0;k<c.length;k++){this.b[this.n++]=c[k];if(this.n===512){this.port.postMessage({time:currentTime+(k+1)/sampleRate,data:this.b.slice(0)});this.n=0}}}return true}}registerProcessor('saywright-session-mic',C)`,ir=class{onChunk;onSpeechStart;ctx=null;stream=null;node=null;buf=new Int16Array(nr);fill=0;bufT=0;paused=!1;lastPerf=0;level=0;lastVoice=0;lastSound=0;startedAt=0;noise=.004;streak=0;constructor(e,t){this.onChunk=e,this.onSpeechStart=t}get open(){return!!this.node}async start(e){if(this.node)return;this.stream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1,...e?{deviceId:{exact:e}}:{}}});let t=new AudioContext({sampleRate:tr});this.ctx=t;let n=URL.createObjectURL(new Blob([rr],{type:`text/javascript`}));try{await t.audioWorklet.addModule(n)}finally{URL.revokeObjectURL(n)}let r=t.createMediaStreamSource(this.stream),i=new AudioWorkletNode(t,`saywright-session-mic`);i.port.onmessage=e=>{this.ctx&&this.ingest(e.data.data,this.toWall(e.data.time))};let a=t.createGain();a.gain.value=0,r.connect(i).connect(a).connect(t.destination),this.node=i,this.startedAt=Date.now(),t.state===`suspended`&&await t.resume().catch(()=>void 0)}toWall(e){let t=this.ctx,n=t.getOutputTimestamp?.(),r;return r=n&&n.contextTime!==void 0&&n.performanceTime!==void 0&&n.performanceTime>0?n.performanceTime+(e-n.contextTime)*1e3:performance.now()-(t.currentTime-e)*1e3,r=Math.max(r,this.lastPerf),this.lastPerf=r,performance.timeOrigin+r}ingest(e,t){let n=0;for(let t=0;t<e.length;t++)n+=e[t]*e[t];let r=Math.sqrt(n/e.length);if(this.level=Math.max(r*6,this.level*.85),r>2e-5&&(this.lastSound=t),this.noise=r<this.noise?this.noise*.9+r*.1:this.noise*.999+r*.001,r>Math.max(.01,this.noise*3)?(this.streak++,this.streak===3?(t-this.lastVoice>1500&&this.onSpeechStart?.(t),this.lastVoice=t):this.streak>3&&(this.lastVoice=t)):this.streak=0,this.paused)return;let i=t-e.length/tr*1e3,a=0;for(;a<e.length;){this.fill===0&&(this.bufT=i+a/tr*1e3);let t=Math.min(nr-this.fill,e.length-a);for(let n=0;n<t;n++){let t=Math.max(-1,Math.min(1,e[a+n]));this.buf[this.fill+n]=t<0?t*32768:t*32767}this.fill+=t,a+=t,this.fill===nr&&this.flush()}}flush(){this.fill&&=(this.onChunk({t:Math.round(this.bufT),pcm:this.buf.slice(0,this.fill)}),0)}discard(){this.fill=0}setPaused(e){e&&this.flush(),this.paused=e}async stop(){this.flush(),this.node&&(this.node.port.onmessage=null),this.node?.disconnect(),this.node=null,this.stream?.getTracks().forEach(e=>e.stop()),this.stream=null,await this.ctx?.close().catch(()=>void 0),this.ctx=null,this.level=0}};function ar(){for(let e of[`video/webm;codecs=vp9`,`video/webm;codecs=vp8`,`video/webm`])if(typeof MediaRecorder<`u`&&MediaRecorder.isTypeSupported(e))return e;return``}var or=class{onVideo;onShot;stream=null;track=null;recorder=null;video=null;canvas=null;lastShot=0;shotCount=0;stopped=null;mime=``;startedAt=0;onEnded=null;constructor(e,t){this.onVideo=e,this.onShot=t}get active(){return!!this.track&&this.track.readyState===`live`}async start(e){let t=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:{ideal:12,max:24},width:{max:1920},height:{max:1200}},audio:!1,preferCurrentTab:!0,selfBrowserSurface:`include`,surfaceSwitching:`exclude`,monitorTypeSurfaces:`exclude`});this.stream=t;let n=t.getVideoTracks()[0];this.track=n,n.addEventListener(`ended`,()=>{this.stop(),this.onEnded?.()});let r=globalThis.CropTarget;if(e.crop&&r&&n.cropTo)try{await n.cropTo(await r.fromElement(e.crop))}catch{}let i=document.createElement(`video`);i.muted=!0,i.playsInline=!0,i.srcObject=t,await i.play().catch(()=>void 0),this.video=i}record(e){let t=this.stream;if(t&&!this.recorder&&(this.startedAt=Date.now(),this.mime=ar(),e&&this.mime)){let e=new MediaRecorder(t,{mimeType:this.mime,videoBitsPerSecond:12e5});e.ondataavailable=e=>{e.data.size&&this.onVideo(e.data,this.mime,this.startedAt)},this.stopped=new Promise(t=>e.addEventListener(`stop`,()=>t(),{once:!0})),e.start(1e3),this.recorder=e}}shoot(e,t=!1){let n=this.video;if(!n||!this.active||!n.videoWidth)return;let r=Date.now();if(!t&&(r-this.lastShot<2500||this.shotCount>=150))return;this.lastShot=r,this.shotCount++;let i=Math.min(1,1280/n.videoWidth),a=Math.round(n.videoWidth*i),o=Math.round(n.videoHeight*i),s=this.canvas??=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);c&&(c.drawImage(n,0,0,a,o),s.toBlob(t=>t&&this.onShot({t:r,reason:e,jpeg:t,w:a,h:o}),`image/jpeg`,.8))}async stop(){this.recorder&&this.recorder.state!==`inactive`&&(this.recorder.stop(),await this.stopped),this.recorder=null,this.stream?.getTracks().forEach(e=>e.stop()),this.stream=null,this.track=null,this.video&&(this.video.srcObject=null),this.video=null}},sr=`saywright.session.audio`,cr=3e4;function lr(e){let t=new Uint8Array(e),n=``;for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(n)}function ur(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}var dr={events:0,clicks:0,errors:0,failedRequests:0,frustration:0,marks:0,speech:0,shots:0},fr={id:null,status:`idle`,stage:``,startedAt:0,counts:dr,audioSeconds:0,mic:`off`,screen:`off`,paused:!1,captions:[],lastIssue:null,error:null,backlog:0},pr=class{onChange;limit;queue=[];busy=!1;failures=0;bytes=0;dropped=0;constructor(e,t=1/0){this.onChange=e,this.limit=t}get size(){return this.queue.length}sizeOf(e){return e instanceof Blob?e.size:e.byteLength}add(e,t,n=!1){let r=this.sizeOf(t);!n&&this.bytes+r>this.limit?(this.dropped++,this.onChange()):(this.bytes+=r,n?this.queue.unshift({url:e,body:t}):this.queue.push({url:e,body:t}),this.onChange(),this.pump())}async pump(){if(!this.busy){for(this.busy=!0;this.queue.length;){let e=this.queue[0];try{let t=await fetch(e.url,{method:`POST`,body:e.body,headers:{"Content-Type":`text/plain`},credentials:`omit`});if(await t.arrayBuffer().catch(()=>void 0),!t.ok&&t.status!==409&&t.status!==404)throw Error(String(t.status));this.queue.splice(this.queue.indexOf(e),1),this.bytes-=this.sizeOf(e.body),this.failures=0,this.onChange()}catch{this.failures++,await new Promise(e=>setTimeout(e,Math.min(8e3,500*2**this.failures)))}}this.busy=!1}}async drain(e){let t=Date.now()+e;for(;this.queue.length&&Date.now()<t;)await new Promise(e=>setTimeout(e,100))}},mr=class{state={...fr};mic=null;screen=null;audio=new pr(()=>this.backlog(),64e6);video=new pr(()=>this.backlog(),96e6);es=null;endpoint=``;key=``;listeners=new Set;periodic=null;lastActivity=0;external=!1;useExternalEvents(){this.external=!0}subscribe(e){return this.listeners.add(e),e(this.state),()=>this.listeners.delete(e)}set(e){this.state={...this.state,...e};for(let e of this.listeners)e(this.state)}backlog(){let e=this.audio.size+this.video.size,t=this.audio.dropped+this.video.dropped;(e!==this.state.backlog||t!==(this.state.lost??0))&&this.set({backlog:e,lost:t})}url(e,t={}){let n=new URLSearchParams(Object.entries({...t,...this.key?{k:this.key}:{}}).map(([e,t])=>[e,String(t)])).toString();return`${this.endpoint}/api/sessions/${encodeURIComponent(this.state.id??``)}${e}${n?`?${n}`:``}`}attach(e,t,n,r=``){this.endpoint=e.replace(/\/$/,``),this.key=r,this.set({...fr,id:t,status:`recording`,startedAt:n}),this.restorePending(),this.listen(),this.watchUnload()}async resumeMic(e){if(this.mic||this.state.status!==`recording`)return;let t=this.makeMic();this.set({mic:`starting`});try{await t.start(e),this.mic=t,this.set({mic:`on`})}catch(e){this.set({mic:e?.name===`NotAllowedError`?`denied`:`error`})}}async resumeScreen(e){if(this.screen||this.state.status!==`recording`)return;let t=this.makeScreen();try{await t.start({crop:e.crop}),t.record(e.video),t.onEnded=()=>this.set({screen:`off`}),this.screen=t,this.set({screen:`on`})}catch{this.set({screen:`denied`})}}makeMic(){return new ir(e=>this.state.id&&this.audio.add(this.url(`/audio`,{t:e.t}),e.pcm.buffer.slice(e.pcm.byteOffset,e.pcm.byteOffset+e.pcm.byteLength)),()=>this.moment(`speech`))}videoChunks=0;makeScreen(){return new or((e,t,n)=>this.state.id&&this.video.add(this.url(`/video`,{mime:t,startedAt:n,n:this.videoChunks++}),e),e=>this.uploadShot(e.t,e.reason,e.jpeg,e.w,e.h))}unloadHooked=!1;watchUnload(){this.unloadHooked||(this.unloadHooked=!0,addEventListener(`pagehide`,()=>{if(this.state.status!==`recording`)return;this.mic?.flush();let e=[],t=3e6;for(let n of this.audio.queue){if(!e.length)try{if(navigator.sendBeacon(n.url,new Blob([n.body],{type:`text/plain`})))continue}catch{}n.body instanceof Blob||n.body.byteLength>t||(t-=n.body.byteLength,e.push({url:n.url,b64:lr(n.body)}))}try{e.length&&sessionStorage.setItem(sr,JSON.stringify({id:this.state.id,items:e}))}catch{}}))}restorePending(){let e=null;try{e=JSON.parse(sessionStorage.getItem(sr)??`null`),sessionStorage.removeItem(sr)}catch{return}if(e?.items&&e.id===this.state.id)for(let t of e.items.reverse())this.audio.add(t.url,ur(t.b64),!0)}go=!1;cancelled=!1;wake=null;startNow(){this.state.status===`starting`&&(this.go=!0,this.wake?.())}cancelStart(){this.state.status!==`starting`||this.state.id||(this.cancelled=!0,this.wake?.())}stillStarting(e){return this.state.status===`starting`&&this.state.id===e}async waitFor(e,t){let n=e.then(()=>`done`,()=>`failed`),r=Date.now()+t;for(;;){if(this.cancelled)return`cancelled`;let e=r-Date.now();if(e<=0)return`timeout`;let t,i=await Promise.race([n,new Promise(n=>{t=setTimeout(()=>n(null),e),this.wake=()=>n(null)})]);if(clearTimeout(t),this.wake=null,i)return i}}async warmSpeech(e){try{return(await(await fetch(`${this.endpoint}/api/speech/warm?mode=${e}&wait=1`,{method:`POST`,credentials:`omit`,signal:AbortSignal.timeout(9e4)})).json()).narration===`live`?`ok`:`unavailable`}catch{return`unavailable`}}async notStarted(e){if(await this.release(),e===null)return this.set({...fr}),null;throw this.set({status:`failed`,countdown:null,mic:`off`,error:e}),Error(e)}async release(){let e=this.mic,t=this.screen;this.mic=null,this.screen=null,await Promise.race([Promise.all([e?.stop(),t?.stop()].map(e=>e?.catch(()=>void 0))),new Promise(e=>setTimeout(e,4e3))])}async start(e){if(this.state.status===`recording`||this.state.status===`starting`||this.state.status===`stopping`)throw Error(`Already recording`);this.endpoint=e.endpoint.replace(/\/$/,``),this.go=!1,this.cancelled=!1;let t=Math.max(0,Math.round(e.countdown??0)),n={left:t,total:t,mic:e.mic?`opening`:`off`,screen:`off`,speech:e.mic?`loading`:`off`,app:`ok`,waiting:null,goLabel:`Start now`};this.set({...fr,status:`starting`,countdown:t?n:null});let r=null;if(e.screen){if(!navigator.mediaDevices?.getDisplayMedia)r=`unsupported`;else{let t=this.makeScreen(),n=t.start({crop:e.crop}),i=await this.waitFor(n,cr);if(i===`done`)t.onEnded=()=>this.set({screen:`off`}),this.screen=t;else if(n.then(()=>t.stop(),()=>t.stop()),i===`failed`)r=`denied`;else if(i===`cancelled`)return this.notStarted(null);else return this.notStarted(`Sharing the screen didn’t start within ${cr/1e3} seconds. Start again, or turn off “Record the screen”.`)}}let i=null,a=!1,o=e.mic?this.makeMic():null;o&&(this.mic=o,this.set({mic:`starting`}),o.start(e.micDeviceId).then(()=>{a=!0,this.mic===o&&this.set({mic:`on`}),this.wake?.()},e=>{i=e?.name===`NotAllowedError`?`blocked`:`failed`,this.mic===o&&(this.mic=null,this.set({mic:i===`blocked`?`denied`:`error`})),this.wake?.()}));let s=e.mic?`loading`:`off`;if(e.mic&&t&&this.warmSpeech(e.lang).then(e=>{s=e,this.wake?.()}),t){let n=Date.now()+t*1e3,c=()=>{let c=o?i??(a?o.lastSound>o.startedAt?`ok`:Date.now()-o.startedAt>1500?`quiet`:`checking`:`opening`):`off`,l=!e.appReady||e.appReady()?`ok`:`waiting`,u=Math.max(0,Math.ceil((n-Date.now())/1e3)),d=u>0?null:c===`opening`?`Allow the microphone in your browser…`:c===`checking`?`Listening to the microphone…`:c===`quiet`?`No sound from the microphone: check it isn’t muted.`:c===`blocked`?`The microphone is blocked: allow it from the address bar, or record without your voice.`:c===`failed`?`The microphone couldn’t be opened: is one connected?`:l===`waiting`?`Waiting for your app to connect…`:s===`loading`?`Loading the speech model…`:null,f=c===`opening`||c===`blocked`||c===`failed`?`Record without voice`:d?`Start anyway`:`Start now`;return{left:u,total:t,mic:c,screen:e.screen?this.screen?`ok`:r??`denied`:`off`,speech:s,app:l,waiting:d,goLabel:f}};for(;;){let e=c();if(this.set({countdown:e}),this.cancelled)return this.notStarted(null);if(this.go||e.left===0&&!e.waiting)break;await new Promise(e=>{let t=setTimeout(e,200);this.wake=()=>{clearTimeout(t),e()}}),this.wake=null}}let c;try{c=await fetch(`${this.endpoint}/api/sessions`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e.name,appUrl:e.appUrl,source:e.source,lang:e.lang,replace:e.replace}),credentials:`omit`,signal:AbortSignal.timeout(2e4)})}catch{throw await this.release(),this.set({status:`failed`,countdown:null,mic:`off`,error:"The studio isn’t reachable. Is `npm run dev` running?"}),Error(this.state.error)}let l=await c.json().catch(()=>({}));if(!c.ok||!l.session)throw await this.release(),this.set({status:`failed`,countdown:null,mic:`off`,error:l.error??`Couldn’t start (${c.status})`,busy:l.code===`busy`}),Error(this.state.error);let u=l.session.id;if(this.cancelled)return fetch(`${this.endpoint}/api/sessions/${encodeURIComponent(u)}/stop${l.key?`?k=${encodeURIComponent(l.key)}`:``}`,{method:`POST`,headers:{"Content-Type":`text/plain`},body:`{}`,credentials:`omit`}).catch(()=>void 0),this.notStarted(null);this.key=l.key??``,this.mic?.discard(),this.set({id:u,countdown:null}),this.screen?.record(e.video);try{await e.onCreated?.(u,this.key)}catch(e){console.warn(`[saywright] starting the app’s recorder:`,e)}return this.stillStarting(u)&&(this.set({status:`recording`,startedAt:l.session.startedAt,screen:this.screen?`on`:r===`unsupported`?`unsupported`:r?`denied`:`off`}),this.listen(),this.watchUnload(),this.moment(`start`,!0),this.periodic=setInterval(()=>{Date.now()-this.lastActivity>2e4&&this.moment(`periodic`)},5e3)),u}moment(e,t=!1){this.lastActivity=Date.now(),this.screen&&this.state.status===`recording`&&!this.state.paused&&setTimeout(()=>this.screen?.shoot(e,t),e===`speech`||e===`start`?0:450)}uploadShot(e,t,n,r,i){this.state.id&&fetch(this.url(`/shots`,{t:e,reason:t,w:r,h:i}),{method:`POST`,body:n,headers:{"Content-Type":`text/plain`},credentials:`omit`}).then(e=>e.arrayBuffer()).catch(()=>void 0)}async mark(e=``,t=`button`){this.state.id&&this.state.status===`recording`&&(this.moment(`mark`,!0),await fetch(this.url(`/mark`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({note:e,via:t,t:Date.now()}),credentials:`omit`}).catch(()=>void 0))}setPaused(e){this.mic?.setPaused(e),this.set({paused:e})}get micLevel(){return this.mic?.level??0}voiceStatus(e=Date.now()){let t=this.state,n=this.mic;if(t.mic===`denied`)return{state:`blocked`,text:`Mic blocked`,hint:`The browser blocked the microphone: allow it from the icon in the address bar.`,tone:`bad`};if(t.mic===`error`)return{state:`unavailable`,text:`No microphone`,hint:`The microphone couldn’t be opened: none is connected, or another app is using it.`,tone:`bad`};if(t.mic===`starting`)return{state:`starting`,text:`Starting the mic…`,hint:`Opening the microphone.`,tone:`quiet`};if(t.mic!==`on`||!n)return{state:`off`,text:`Voice off`,hint:`Your voice isn’t being recorded in this session.`,tone:`quiet`};if(t.paused)return{state:`paused`,text:`Paused`,hint:`Your voice isn’t being recorded until you resume.`,tone:`quiet`};if(e-n.lastVoice<450)return{state:`speaking`,text:`Hearing you`,hint:`Your voice is coming through.`,tone:`ok`};let r=t.heardAt??0;if(r&&r>=n.lastVoice-500&&e-r<2500)return{state:`heard`,text:`Got it`,hint:`Your last sentence was transcribed: it shows next to this.`,tone:`ok`};if(e-Math.max(n.lastSound,n.startedAt)>3e3)return{state:`silent`,text:`No sound from the mic`,hint:`The microphone sends silence: check it isn’t muted (a switch or key on it), or pick another one in the studio’s Settings → Voice.`,tone:`warn`};let i=e-n.lastVoice;return t.narration===`off`?{state:`untranscribed`,text:`Recording, not transcribing`,hint:`Your voice is recorded, but the studio can’t transcribe it on this computer: install a speech model in Settings → Voice, then transcribe it from the report.`,tone:`warn`}:t.narration===`loading`&&n.lastVoice>n.startedAt?{state:`loading`,text:`Loading the speech model…`,hint:`What you say is kept and transcribed as soon as the model has loaded.`,tone:`quiet`}:n.lastVoice>r&&i<8e3?{state:`transcribing`,text:`Writing it down…`,hint:`Transcribing what you just said.`,tone:`quiet`}:{state:`listening`,text:`Listening`,hint:`Say what you notice; each sentence appears here once it is transcribed.`,tone:`quiet`}}async stop(){if(this.state.status===`starting`&&!this.state.id)return this.cancelStart();if(!this.state.id||this.state.status!==`recording`&&this.state.status!==`starting`)return;let e=Date.now();this.set({status:`stopping`}),this.periodic&&clearInterval(this.periodic),this.periodic=null,this.screen?.shoot(`end`,!0),await new Promise(e=>setTimeout(e,150));let t=e=>Promise.race([e?.catch(()=>void 0),new Promise(e=>setTimeout(e,4e3))]);await t(this.mic?.stop()),this.mic=null,await t(this.screen?.stop()),this.screen=null,await Promise.all([this.audio.drain(15e3),this.video.drain(15e3)]);for(let t=0;;t++)try{await fetch(this.url(`/stop`),{method:`POST`,headers:{"Content-Type":`text/plain`},body:JSON.stringify({endedAt:e}),credentials:`omit`,signal:AbortSignal.timeout(15e3)}),this.set({status:`processing`,stage:`Finishing the transcript`,mic:`off`,screen:`off`});return}catch{if(t<2)await new Promise(e=>setTimeout(e,1e3));else return this.set({status:`failed`,error:`Couldn’t reach the studio to stop the session.`,mic:`off`,screen:`off`})}}stoppedElsewhere(){this.periodic&&clearInterval(this.periodic),this.periodic=null,this.mic?.stop(),this.mic=null,this.screen?.stop(),this.screen=null}listen(){if(this.external)return;this.es?.close();let e=new EventSource(this.url(`/live`));this.es=e,e.addEventListener(`session`,e=>{try{this.handle(JSON.parse(e.data))}catch{}})}handle(e){if(e&&e.id===this.state.id){if(e.kind===`counts`)this.set({counts:{...dr,...e.counts},audioSeconds:Number(e.audioSeconds??0),...e.narration?{narration:e.narration}:{}});else if(e.kind===`speech`){let t=e.segment;this.set({captions:[...this.state.captions,{t:t.start,text:t.text}].slice(-3),heardAt:Date.now()})}else if(e.kind===`issue`)this.set({lastIssue:{t:Number(e.t),text:String(e.text)}}),this.moment(`issue`);else if(e.kind===`status`){let t=e.status;t===`processing`&&(this.state.status===`recording`||this.state.status===`stopping`)&&this.stoppedElsewhere(),(t===`processing`||t===`ready`||t===`failed`)&&this.set({status:t,stage:String(e.stage??``),error:e.error??null}),(t===`ready`||t===`failed`)&&this.es&&(this.es.close(),this.es=null)}}}reset(){this.es?.close(),this.es=null,this.set({...fr})}},hr=`saywright.session.prefs`,gr=`saywright.report.lang`;function _r(){try{let e=localStorage.getItem(gr);return e===`en`||e===`ar`?e:null}catch{return null}}function vr(){let e={lang:navigator.language?.startsWith(`ar`)?`ar`:`auto`,mic:!0,screen:!0,video:!0,countdown:3};try{return{...e,...JSON.parse(localStorage.getItem(hr)??`{}`)}}catch{return e}}var yr=h()(()=>({live:fr,list:[],open:null,detail:null,detailError:null,reportLang:_r(),setup:!1,speech:null,prefs:vr()})),w=yr.setState,T=yr.getState;function br(e){return{src:e.src,name:e.name,tag:e.tag,role:e.role,label:e.label.replace(/^[^·]*·\s*/,``).slice(0,60),text:e.text,rect:[Math.round(e.rect.x),Math.round(e.rect.y),Math.round(e.rect.w),Math.round(e.rect.h)]}}var xr=500,E=new class{client=new mr;host=null;outbox=[];flushTimer=null;pointing=null;lookups=new Set;restoreMode=null;seq=0;key;awaiting=new Map;poll=null;constructor(){this.client.useExternalEvents(),this.client.subscribe(e=>{let t=T().live;w({live:e}),t.status!==e.status&&(e.status===`ready`||e.status===`failed`)&&this.refreshList(),this.syncPoll()})}syncPoll(){T().live.status===`processing`||this.awaiting.size?this.poll??=setInterval(()=>void this.resync(),4e3):this.poll&&=(clearInterval(this.poll),null)}init(e){this.host=e,this.refreshList(),this.refreshSpeech();let t=/^\/report\/([\w-]+)/.exec(location.pathname);t&&this.openReport(t[1]),c.get(`/sessions/active`).then(({session:e,key:t})=>{e&&e.source===`studio`&&T().live.status===`idle`&&(this.key=t,this.client.attach(location.origin,e.id,e.startedAt),this.host?.bridgeSession(!0,e.id,location.origin,t),this.restoreMode=this.host?.enterUse()??null)})}serverEvent(e,t){if(e===`speech`)w({speech:t});else if(e===`session`){let e=t;this.client.handle(e),e.kind===`status`?(this.refreshList(),T().open===e.id&&this.loadDetail(e.id),(e.status===`ready`||e.status===`failed`)&&this.announce(e.id,e.status)):e.kind===`report`&&T().open===e.id&&this.loadDetail(e.id)}}async resync(){await this.refreshList();let e=T().live,t=e.id?T().list.find(t=>t.id===e.id):void 0;t&&e.status===`processing`&&t.status!==`processing`&&this.client.handle({kind:`status`,id:t.id,status:t.status,stage:t.stage,error:t.error});for(let e of this.awaiting.keys()){let t=T().list.find(t=>t.id===e);(!t||t.status===`ready`||t.status===`failed`)&&this.announce(e,t?.status??`failed`)}}announce(e,t){let n=this.awaiting.get(e);n!==void 0&&(this.awaiting.delete(e),this.syncPoll(),T().open!==e&&this.host?.notify(t===`ready`?`Report ready: ${n}`:`The report for “${n}” couldn’t be written`,[{label:`Open`,run:()=>this.openReport(e),primary:!0}]))}setPrefs(e){let t={...T().prefs,...e};localStorage.setItem(hr,JSON.stringify(t)),w({prefs:t})}get recording(){let e=T().live.status;return e===`recording`||e===`starting`||e===`stopping`}async start(e,t=!1){if(!this.host||this.recording)return;let n=T().prefs;w({setup:!1});let r=T().live,i=r.status===`ready`||r.status===`failed`;r.id&&(r.status===`processing`||i)&&this.awaiting.set(r.id,T().list.find(e=>e.id===r.id)?.name||`the last session`),this.syncPoll();try{let r=this.host;await this.client.start({endpoint:location.origin,name:e,lang:n.lang,appUrl:r.appUrl(),source:`studio`,mic:n.mic,screen:n.screen,video:n.video&&n.screen,crop:r.frame(),replace:t,countdown:n.countdown,appReady:()=>r.appConnected(),onCreated:async(e,t)=>{this.seq=0,this.key=t,this.restoreMode=r.enterUse(),await r.bridgeSession(!0,e,location.origin,t)}})}catch{w({setup:!0})}r.id&&i&&this.announce(r.id,r.status)}startNow(){this.client.startNow()}cancelStart(){this.client.cancelStart()}async stop(){if(this.recording){if(T().live.status===`starting`&&!T().live.id)return this.cancelStart();this.flushPointing(),await this.flush(),this.host?.bridgeSession(!1),this.restoreMode?.(),this.restoreMode=null,await this.client.stop()}}mark(e=``,t=`key`){T().live.status===`recording`&&(this.host?.bridgeMark(e,t),this.client.moment(`mark`,!0))}moment(e){this.client.moment(e)}pointed(e,t){if(T().live.status!==`recording`)return;let n=Date.now();if(this.pointing&&e&&this.pointing.el.id===e.id||(this.flushPointing(n),!e))return;let r={el:e,since:n,via:t,timer:setTimeout(()=>r.locator=this.locate(e),xr)};this.pointing=r}locate(e){return this.host?this.host.locate(e.id).catch(()=>null):Promise.resolve(null)}flushPointing(e=Date.now()){let t=this.pointing;if(!t)return;this.pointing=null,clearTimeout(t.timer);let n=e-t.since;if(n<xr)return;let r=br(t.el),i=(t.locator??this.locate(t.el)).then(e=>{e&&Object.assign(r,{locator:e.code,description:e.description,...e.within?{within:e.within}:{}})});this.lookups.add(i),i.finally(()=>this.lookups.delete(i)),this.queue({type:`point`,el:r,ms:n,via:t.via,t:t.since})}command(e,t,n){T().live.status===`recording`&&this.queue({type:`command`,text:e.slice(0,300),input:t,result:n.slice(0,120),t:Date.now()})}queue(e){this.outbox.push(e),this.flushTimer||=setTimeout(()=>void this.flush(),1500)}async flush(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null,this.lookups.size&&await Promise.race([Promise.all(this.lookups),new Promise(e=>setTimeout(e,1e3))]);let e=T().live.id;if(!e||!this.outbox.length)return;let t=this.outbox.splice(0).map(e=>({...e,seq:++this.seq}));await c.post(`/sessions/${e}/studio-events`,{events:t}).catch(()=>void 0)}async refreshList(){let{sessions:e}=await c.get(`/sessions`).catch(()=>({sessions:[]}));w({list:e})}async refreshSpeech(){let e=await c.get(`/speech/status`).catch(()=>null);e&&w({speech:e})}warmSpeech(e){c.post(`/speech/warm?mode=`+e,{}).catch(()=>void 0)}async installSpeech(e){let t=await c.post(`/speech/install`,{id:e}).catch(()=>null);t&&w({speech:t})}openReport(e){let t=T().live;t.id===e&&(t.status===`ready`||t.status===`failed`)&&this.client.reset(),this.awaiting.delete(e),this.syncPoll(),w({open:e,detail:null,detailError:null}),location.pathname!==`/report/${e}`&&history.pushState(null,``,`/report/${e}`),this.loadDetail(e)}closeReport(){w({open:null,detail:null,detailError:null}),location.pathname.startsWith(`/report/`)&&history.pushState(null,``,`/`)}async loadDetail(e){try{let t=await c.get(`/sessions/${e}`);T().open===e&&w({detail:t,detailError:null})}catch(t){T().open===e&&w({detailError:t instanceof Error?t.message:String(t)})}}setReportLang(e){try{localStorage.setItem(gr,e)}catch{}w({reportLang:e})}async setSkipped(e,t){let n=T().detail;n?.meta.id===e&&w({detail:{...n,decisions:{...n.decisions,skipped:t}}}),await c.put(`/sessions/${e}/decisions`,{skipped:t})}async correctSentence(e,t,n){await c.put(`/sessions/${e}/transcript/${t}`,{text:n}),await this.loadDetail(e)}async retranslate(e){await c.post(`/sessions/${e}/translate`,{}),await this.loadDetail(e)}async regenerate(e,t=!0){await c.post(`/sessions/${e}/report`,{ai:t}),await this.loadDetail(e)}async retranscribe(e,t){await c.post(`/sessions/${e}/transcribe`,{lang:t}),await this.loadDetail(e)}async rename(e,t){await c.put(`/sessions/${e}`,{name:t}),await this.refreshList(),T().open===e&&await this.loadDetail(e)}async remove(e){await fetch(`/api/sessions/${e}`,{method:`DELETE`}),T().open===e&&this.closeReport(),await this.refreshList()}bridgeSaid(e){let t=T().live;t.status===`recording`&&t.id&&e!==t.id&&this.host?.bridgeSession(!0,t.id,location.origin,this.key)}};window.addEventListener(`popstate`,()=>{let e=/^\/report\/([\w-]+)/.exec(location.pathname);e?T().open!==e[1]&&E.openReport(e[1]):T().open&&w({open:null,detail:null})});function Sr(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var Cr=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return Cr(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return Cr(t)(e)}}}},wr=(e,t)=>(n,r,i)=>{let a={storage:Sr(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,l=new Set,u=a.storage;if(!u)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let d=()=>{let e=a.partialize({...r()});return u.setItem(a.name,{state:e,version:a.version})},f=i.setState;i.setState=(e,t)=>(f(e,t),d());let p=e((...e)=>(n(...e),d()),r,i);i.getInitialState=()=>p;let m,h=()=>{if(!u)return;let e=++s;o=!1,c.forEach(e=>e(r()??p));let t=a.onRehydrateStorage?.call(a,r()??p)||void 0;return Cr(u.getItem.bind(u))(a.name).then(e=>{if(e){if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state]}return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(m=a.merge(o,r()??p),n(m,!0),i)return d()}).then(()=>{e===s&&(t?.(r(),void 0),m=r(),o=!0,l.forEach(e=>e(m)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(u=e.storage)},clearStorage:()=>{++s,u?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>h(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(l.add(e),()=>{l.delete(e)})},a.skipHydration||h(),m||p},Tr={theme:`system`,onboarded:!1,camera:{enabled:!1,deviceId:null,skeleton:!0,pip:`small`,corner:`bl`,legend:!0},engine:Yt,aimAssist:28,dwellSelect:!1,voice:{lang:navigator.language?.startsWith(`en`)?navigator.language:`en-US`,autoStopMs:1300,sounds:!0,engine:`auto`,review:!1},ui:{panelOpen:!0,panelTab:`changes`,device:`fill`,commitOnKeep:!1},labs:{hand:!1}};function Er(e){let t=.22+Math.max(0,Math.min(1,e))*.18;return{pinchOn:+t.toFixed(3),pinchOff:+(t+.14).toFixed(3)}}function Dr(e){return Math.max(0,Math.min(1,(e-.22)/.18))}var Or=h()(wr(e=>({...Tr,set:t=>e(t),setCamera:t=>e(e=>({camera:{...e.camera,...t}})),setEngine:t=>e(e=>({engine:{...e.engine,...t}})),setVoice:t=>e(e=>({voice:{...e.voice,...t}})),setUi:t=>e(e=>({ui:{...e.ui,...t}})),setLabs:t=>e(e=>({labs:{...e.labs,...t}})),reset:()=>e({...Tr,onboarded:!0})}),{name:`saywright.settings`,version:2,migrate:(e,t)=>{let n=e??{};return t<2&&n.engine&&delete n.engine.dragThresholdPx,n},partialize:({set:e,setCamera:t,setEngine:n,setVoice:r,setUi:i,setLabs:a,reset:o,...s})=>s,merge:(e,t)=>{let n=e??{};return{...t,...n,camera:{...t.camera,...n.camera},engine:{...t.engine,...n.engine,box:{...t.engine.box,...n.engine?.box}},voice:{...t.voice,...n.voice},ui:{...t.ui,...n.ui},labs:{...t.labs,...n.labs}}}}));function kr(e){let t=e===`dark`||e===`system`&&matchMedia(`(prefers-color-scheme: dark)`).matches;document.documentElement.classList.toggle(`dark`,t)}var Ar=()=>Or(e=>e.labs.hand),jr=()=>Or.getState().labs.hand,Mr=null,Nr=!0;function Pr(e){Nr=e}function D(e,t,n,r,i=`sine`,a){if(!Mr)return;let o=Mr.currentTime+t,s=Mr.createOscillator(),c=Mr.createGain();s.type=i,s.frequency.setValueAtTime(e,o),a&&s.frequency.exponentialRampToValueAtTime(a,o+n),c.gain.setValueAtTime(0,o),c.gain.linearRampToValueAtTime(r,o+.008),c.gain.exponentialRampToValueAtTime(1e-4,o+n),s.connect(c).connect(Mr.destination),s.start(o),s.stop(o+n+.02)}function O(e){if(Nr){try{Mr??=new AudioContext,Mr.state===`suspended`&&Mr.resume()}catch{return}switch(e){case`listen`:D(660,0,.09,.05,`sine`,990);break;case`send`:D(990,0,.08,.04,`sine`,740);break;case`tap`:D(1800,0,.03,.025,`triangle`);break;case`pick`:D(1320,0,.04,.03,`triangle`),D(1760,.05,.05,.03,`triangle`);break;case`keep`:D(784,0,.12,.045),D(1175,.07,.16,.04);break;case`undo`:D(523,0,.14,.045,`sine`,392);break;case`error`:D(220,0,.18,.05,`triangle`,180)}}}var Fr={startUrl:null,steps:[],expectations:[],spec:null,run:null,running:!1,installing:!1,installLog:[],verifying:!1},Ir=h()(()=>({mode:`edit`,status:null,statusError:null,app:{connected:!1,url:``,title:``,reloadKey:0},pointer:null,hover:null,snapped:!1,selection:null,pins:[],previewTargets:[],replay:null,autopilot:null,camera:{status:`off`,error:null,fps:0,delegate:null},hand:{present:!1,pose:`other`,holdKind:null,clutched:!1,dragging:!1,hand:null},voice:{supported:!0,state:`idle`,trigger:null,words:[],bindings:[],error:null,last:null,model:`idle`,modelError:``},draft:null,island:{kind:`idle`},request:null,waiting:[],changes:[],inspect:null,inspectLoading:!1,recorder:Fr,summary:null,overlay:null,settingsTab:`general`,history:[],focusInput:0,onboardingStep:0,calibrateReturn:null})),k=Ir.setState,A=Ir.getState,Lr=e=>e.changes.filter(e=>e.status===`preview`);function Rr(e,t){return e===t?!0:!e||!t?!1:e.id===t.id&&e.rect.x===t.rect.x&&e.rect.y===t.rect.y&&e.rect.w===t.rect.w&&e.rect.h===t.rect.h&&e.src===t.src&&e.text===t.text}var zr=new Set(`a an the this that these those it its to into as be is are was make makes made turn change set use using with please can you could would just look looks like more less bit little lot much way really so and also now then on in of for here there me my our your some kind sort`.split(` `)),Br=/\b(?:everywhere|wherever|throughout|all of (?:them|these|those)|(?:all|every|each) (?:the )?(?:one|ones|instances?|occurrences?|places?|pages?|screens?|buttons?|links?|labels?|copies)|across the (?:app|site|page|pages|project))\b/i,Vr=RegExp(`\\s+(?:${Br.source})(?:\\s+(?:it|they)\\s+(?:appears?|shows?|is|are)(?:\\s+used)?)?[.!]*$`,`i`),Hr=/^(?:please|thanks|thank you|instead|now|for me)?[.!]*$/i,Ur=/\uE000(\d+)\uE000/g;function Wr(e){return e.replace(/^[\s"“'‘]+|[\s"”'’.!?]+$/g,``)}function Gr(e){let t=[];return{masked:e.replace(/"([^"]*)"|“([^”]*)”|«([^»]*)»|(?<![\p{L}\p{N}])'([^']*)'(?![\p{L}\p{N}])|(?<![\p{L}\p{N}])‘([^’]*)’(?![\p{L}\p{N}])/gu,(...e)=>(t.push(String(e.slice(1,6).find(e=>e!==void 0)??``)),`\uE000${t.length-1}\uE000`)),values:t}}function Kr(e,t){let n=/^\s*\uE000(\d+)\uE000(.*)$/s.exec(e);if(n){let e=t[Number(n[1])].trim(),r=n[2].replace(Ur,(e,n)=>t[Number(n)]).trim();return Br.test(r)?{value:e,everywhere:!0}:Hr.test(r)?{value:e,everywhere:!1}:null}let r=Wr(e.replace(Ur,(e,n)=>`"${t[Number(n)]}"`)),i=Vr.exec(r);return i&&(r=r.slice(0,i.index).trim()),{value:r,everywhere:!!i}}var qr=e=>` `+e.toLowerCase().replace(/[“”"‘’']/g,``).replace(/[^a-z0-9\s-]/g,` `).replace(/\s+/g,` `).trim()+` `;function Jr(e){let t=e.trim(),{masked:n,values:r}=Gr(t),i=qr(t),a=qr(n.replace(Ur,` `));if(/\b(look|looks|style|styled)\s+(just\s+|exactly\s+)?like\b|\bsame (style|look|size|styling) as\b|\bmatch(es)?\b/.test(a))return{kind:`copy`,adjust:/\b(smaller|tinier|less)\b/.test(a)?-1:+!!/\b(bigger|larger)\b/.test(a)};let o=/\b(move|put|place|drag)\b.*\b(above|below|before|after|under|over|beneath|underneath)\b/.exec(a);if(o)return{kind:`move`,where:/^(below|after|under|beneath|underneath)$/.test(o[2])?`below`:`above`};if(/\b(remove|delete|get rid of|drop|hide)\b/.test(a))return{kind:`remove`};let s=/\b(?:rename|relabel|call)\b.*?\b(?:to|as)\b\s+(.+)$/is.exec(n)??/\b(?:change|set|update|make)\s+(?:the\s+)?(?:text|label|copy|title|wording|words?)\b.*?\b(?:to|into)\b\s+(.+)$/is.exec(n)??/\b(?:make\s+(?:this|that|it)\s+)?(?:say|read)s?\s+(.+)$/is.exec(n);if(s){let e=Kr(s[1],r);if(!e)return null;let t=e.everywhere||Br.test(n.slice(0,s.index+s[0].length-s[1].length).replace(Ur,` `));if(e.value)return{kind:`text`,value:e.value[0].toUpperCase()+e.value.slice(1),...t?{everywhere:!0}:{}}}let c=/\b(bigger|larger|huge|grow|taller|wider|increase)\b/.test(i),l=/\b(smaller|tiny|tinier|shrink|shorter|narrower|decrease|compact)\b/.test(i),u=/\b(padding|spacing|space|gap|gaps|room|airy|tighter|looser|roomier)\b/.test(i);if(c||l||/\b(more|less) (padding|spacing|space|room)\b/.test(i)||/\b(tighter|roomier|looser)\b/.test(i))return{kind:`step`,dir:c||/\b(more|looser|roomier)\b/.test(i)?1:-1,amount:/\b(much|a lot|way|lots|huge|tiny)\b/.test(i)?2:1,focus:u?`spacing`:`size`};if(/\b(make|turn|set|change|switch|use|give)\b/.test(i)||i.trim().split(` `).length<=3){let e=i.trim().split(` `).filter(e=>e&&!zr.has(e));if(e.length&&e.length<=4)return{kind:`set`,terms:e}}return null}var Yr=[`Keep it.`,`Keep.`,`Looks good.`,`Undo.`,`Undo that.`,`Go back.`,`Cancel.`,`Stop.`,`Never mind.`,`Fix it.`,`Run the test.`,`Generate a test.`,`Scroll down.`,`Scroll up.`,`Select parent.`,`Clear.`,`Help.`,`Click this.`],Xr=e=>e.toLowerCase().replace(/[^a-z0-9$.' ]/g,` `).replace(/\.(?=\s|$)/g,` `).split(/\s+/).filter(Boolean),Zr=(e,t)=>Xr(e).join(` `)===Xr(t).join(` `),Qr=new Set([`you`,`thank you`,`thanks`,`thank you very much`,`thanks for watching`,`bye`,`bye bye`,`hmm`,`mm`,`mhm`,`uh`,`um`,`oh`,`ah`,`huh`,`the`,`a`,`i`]),$r=-1.2,ei=-.8,ti=.8,ni=-2.8,ri=-3.5,ii=.4;function ai(e,t=0,n=!1){let r=Xr(e);return!r.length||Qr.has(r.join(` `))||r.length>=4&&new Set(r).size/r.length<.5?!1:t>=(n?ei:$r)}function oi(e,t){let n=Xr(e).map(li),r=Xr(t).map(li);if(!n.length||r.length<=n.length)return!1;let i=n.join(` `);return r.slice(r.length-n.length).join(` `)===i||r.slice(0,n.length).join(` `)===i}var si=new Set(`red orange amber yellow lime green emerald teal cyan blue indigo violet purple pink rose gray grey black white dark light primary secondary tertiary ghost outline outlined solid subtle soft link danger destructive success warning error info neutral muted accent bold italic underline small medium large tiny huge sm md lg xl rounded round square pill full wide narrow centered center left right disabled hidden visible`.split(` `)),ci=new Set([...si,...`bigger smaller larger wider taller shorter tighter looser more less rename remove delete hide move change make undo keep cancel stop scroll select parent reload help click padding spacing space gap text label title button above below test fix pin this that`.split(` `)]);function li(e){let t=e.toLowerCase().replace(/[^a-z]/g,``);t=t.replace(/^kn/,`n`).replace(/^wr/,`r`).replace(/ph/g,`f`).replace(/gh/g,``).replace(/ck/g,`k`).replace(/q/g,`k`).replace(/x/g,`ks`).replace(/c(?=[eiy])/g,`s`).replace(/c/g,`k`);let n=/^[aeiouy]/.test(t)?`a`:``;return t=t.replace(/[aeiouyhw]/g,``).replace(/b/g,`p`).replace(/d/g,`t`).replace(/[gj]/g,`k`).replace(/v/g,`f`).replace(/z/g,`s`).replace(/(.)\1+/g,`$1`),n+t}var ui=new Map;for(let e of ci)e.length>=3&&ui.set(li(e),[...ui.get(li(e))??[],e]);function di(e){let t=e.trim().split(/\s+/);if(t.length>1&&!/^(make|turn|set|change)$/i.test(t[0]))return[];let n=/^([^A-Za-z']*)([A-Za-z']+)(.*)$/.exec(t[t.length-1]);return!n||n[2].length<3||ci.has(n[2].toLowerCase())?[]:(ui.get(li(n[2]))??[]).map(e=>{let r=n[2][0]===n[2][0].toUpperCase()?e[0].toUpperCase()+e.slice(1):e;return[...t.slice(0,-1),n[1]+r+n[3]].join(` `)})}function fi(e){let t=e.trim();if(!t)return!1;if(vt(t,{hasFailingTest:!0})||yt(t)||/^(why|what|where|when|how|can|could|is|are|does|do|should|which|who)\b/i.test(t))return!0;let n=Jr(t);return n?n.kind!==`set`||n.terms.some(e=>si.has(e)):!1}var pi=e=>{let t=vt(e,{hasFailingTest:!0});return t?`${t.kind}${`dir`in t?t.dir:``}`:``};function mi(e,t){let n=e=>li(Xr(e).join(``));return Xr(e).length<=3&&n(e).length>=2&&n(e)===n(t)}function hi(e,t,n){let r=e.filter(e=>t[e.text]!==void 0).sort((e,n)=>t[n.text]-t[e.text]),i=r[0];if(!i)return null;let a=n.some(e=>mi(e.text,i.text));if(t[i.text]<(a?ri:ni))return null;let o=r.find(e=>pi(e.text)!==pi(i.text));return o&&t[i.text]-t[o.text]<ii?null:i}function gi(e,t){let n=e.filter(e=>e.text.trim());if(!n.length)return null;let r=n.find(e=>e.source===`browser`&&e.rank===0)??null;if(!t){let e=n.filter(e=>e.source===`browser`);return e.find(e=>fi(e.text))??e[0]??null}let i=hi(n.filter(e=>e.source===`command`),t,n.filter(e=>e.source===`browser`||e.source===`device`));if(i)return i;let a=e=>e.source===`browser`?e.rank===0?1:.3:e.source===`device`&&r&&oi(r.text,e.text)?1.2:0,o=null,s=-1/0;for(let e of n){let n=t[e.text];if(n===void 0||e.source===`command`)continue;let r=n;if(e.source===`variant`){let i=e.from?t[e.from.text]:void 0;if(!e.from||i===void 0||n<i-ti||!fi(e.text))continue;r+=a(e.from)}else r+=a(e);fi(e.text)&&(r+=1),r>s&&(s=r,o=e)}return o??r}function _i(e,t,n){let r=e.trim().split(/\s+/).filter(Boolean);if(!r.length)return[];let i=r.reduce((e,t)=>e+t.length,0)+r.length-1,a=Math.max(1,n-t),o=0;return r.map(e=>{let n=(o+e.length/2)/Math.max(1,i);return o+=e.length+1,{text:e,t:t+n*a}})}function vi(e,t,n){let r=e.filter(e=>e.trim()),i=t.trim();if(!r.length&&!i)return null;if(!r.length)return{text:i,source:`device`};if(!i||n(r[0]))return{text:r[0],source:`browser`};if(n(i))return{text:i,source:`device`};let a=r.find(e=>n(e));if(a)return{text:a,source:`browser`};let o=yi(r[0]),s=yi(i);return s.length>=o.length+2&&o.length&&o.every((e,t)=>bi(e,s[s.length-o.length+t]))?{text:i,source:`device`}:{text:r[0],source:`browser`}}function yi(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,` `).split(/\s+/).filter(Boolean)}function bi(e,t){if(!t)return!1;if(e===t)return!0;let n=e=>e.replace(/[أإآٱ]/g,`ا`).replace(/ة/g,`ه`).replace(/ى/g,`ي`);return n(e)===n(t)}var xi=16e3,Si=45e3,Ci=12e4,wi=3,Ti=220,Ei=220,Di=128,Oi=class{ctx=null;stream=null;node=null;chunks=[];opening=null;closeTimer=null;noise=.004;lastT=0;streak=0;level=0;lastVoice=0;error=null;get open(){return!!this.node}start(){return this.touch(),this.node?Promise.resolve(!0):(this.opening??=this.openMic().finally(()=>this.opening=null),this.opening)}async openMic(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1}});let e=new AudioContext({sampleRate:xi,latencyHint:`interactive`});this.ctx=e,await e.audioWorklet.addModule(`/voice-capture-worklet.js`);let t=e.createMediaStreamSource(this.stream),n=new AudioWorkletNode(e,`saywright-capture`);n.port.onmessage=e=>this.ingest(e.data.data,this.toPerf(e.data.time));let r=e.createGain();return r.gain.value=0,t.connect(n).connect(r).connect(e.destination),e.state===`suspended`&&await e.resume().catch(()=>void 0),this.node=n,this.error=null,!0}catch(e){let t=e?.name;return this.error=t===`NotAllowedError`?`Microphone is blocked. Allow it in the address bar (and on macOS in System Settings → Privacy & Security → Microphone).`:t===`NotFoundError`?`No microphone found.`:`Microphone unavailable: ${e?.message??e}`,this.close(),!1}}toPerf(e){let t=this.ctx,n=performance.now();if(t?.getOutputTimestamp){let r=t.getOutputTimestamp();r.contextTime!==void 0&&r.performanceTime&&(n=r.performanceTime+(e-r.contextTime)*1e3)}return n=Math.max(n,this.lastT+1),this.lastT=n,n}ingest(e,t){let n=0;for(let t=0;t<e.length;t++)n+=e[t]*e[t];let r=Math.sqrt(n/e.length);for(this.chunks.push({t,data:e,rms:r});this.chunks.length&&this.chunks[0].t<t-Si;)this.chunks.shift();this.noise=r<this.noise?this.noise*.9+r*.1:this.noise*.998+r*.002,this.streak=r>this.threshold()?this.streak+1:0,this.streak>=wi&&(this.lastVoice=t);let i=Math.min(1,r*9);this.level=i>this.level?this.level*.35+i*.65:this.level*.75+i*.25}threshold(){return Math.max(.008,this.noise*3.2)}sample(){return this.node||(this.level*=.85),this.level}slice(e,t){let n=[];for(let r of this.chunks){let i=r.t-r.data.length/xi*1e3;if(r.t<=e||i>=t)continue;let a=Math.max(0,Math.round((e-i)/1e3*xi)),o=Math.min(r.data.length,Math.round((t-i)/1e3*xi));o>a&&n.push(r.data.subarray(a,o))}let r=new Float32Array(n.reduce((e,t)=>e+t.length,0)),i=0;for(let e of n)r.set(e,i),i+=e.length;return r}peak(e,t){let n=0;for(let r of this.chunks)r.t>=e&&r.t<=t+50&&r.rms>n&&(n=r.rms);return n}voiced(e,t,n=e){let r=this.threshold(),i=[],a=null,o=0;this.chunks.forEach((n,s)=>{if(n.t<e||n.t>t+50)return;if(n.rms<=r){o=0;return}o++;let c=n.t-n.data.length/xi*1e3;a&&c-a.end<=Ti?(a.end=n.t,a.last=s):(a={start:c,end:n.t,sustained:!1,first:s,last:s},i.push(a)),o>=wi&&(a.sustained=!0)});let s=i.filter(e=>e.sustained&&e.end>=n-Ei);if(!s.length)return null;let c=s[0],l=s[s.length-1];return{start:this.edge(c.first,r,`start`)??c.start,end:this.edge(l.last,r,`end`)??l.end}}edge(e,t,n){let r=null;for(let i of n===`start`?[e-1,e]:[e,e+1]){let e=this.chunks[i];if(!e)continue;let a=e.t-e.data.length/xi*1e3;for(let i=0;i+Di<=e.data.length;i+=Di){let o=0;for(let t=i;t<i+Di;t++)o+=e.data[t]*e.data[t];if(!(Math.sqrt(o/Di)<=t)){if(n===`start`)return a+i/xi*1e3;r=a+(i+Di)/xi*1e3}}}return r}touch(){this.closeTimer&&clearTimeout(this.closeTimer),this.closeTimer=setTimeout(()=>this.close(),Ci)}close(){this.closeTimer&&clearTimeout(this.closeTimer),this.closeTimer=null,this.node?.port.close(),this.node=null,this.stream?.getTracks().forEach(e=>e.stop()),this.stream=null,this.ctx?.close().catch(()=>void 0),this.ctx=null,this.chunks=[],this.level=0}},ki=class{langs=new Set;async transcribe(e,t,n){let r=new Int16Array(e.length);for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));r[t]=n<0?n*32768:n*32767}try{let e=await fetch(`/api/speech/transcribe?lang=${t}`,{method:`POST`,body:r.buffer,headers:{"Content-Type":`application/octet-stream`},signal:n});return e.ok?await e.json():null}catch{return null}}};function Ai(){let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}var ji={"not-allowed":`Microphone is blocked. Allow it in the address bar (and on macOS in System Settings → Privacy & Security → Microphone).`,"service-not-allowed":`Speech recognition is turned off in this browser. Use Chrome, or type instead.`,"audio-capture":`No microphone found.`,network:`The browser’s speech service can’t be reached (it needs the internet).`,"language-not-supported":`That language isn’t supported for speech here.`},Mi=e=>e.replace(/\s+/g,` `).trim(),Ni=class{static supported(){return typeof window<`u`&&!!Ai()}lang=`en-US`;onWords=null;onFinal=null;onError=null;onAudioStart=null;rec=null;words=[];finals=``;current=``;lastAlts=[];lastPrefix=``;want=!1;finishTimer=null;done=!0;state=`idle`;setState(e){this.state=e}start(){let e=Ai();return e?(this.state!==`idle`&&this.cancel(),this.words=[],this.finals=``,this.current=``,this.lastAlts=[],this.lastPrefix=``,this.want=!0,this.done=!1,this.spawn(e),this.setState(`listening`),!0):(this.onError?.(`unsupported`,`This browser has no speech recognition. Use Chrome, or type your command.`),!1)}spawn(e){let t=new e;t.lang=this.lang,t.continuous=!0,t.interimResults=!0,t.maxAlternatives=5,t.onresult=e=>this.handleResult(e),t.onaudiostart=()=>this.onAudioStart?.(),t.onerror=e=>{e.error!==`aborted`&&e.error!==`no-speech`&&(this.want=!1,this.onError?.(e.error,ji[e.error]??`Speech recognition error: ${e.error}`))},t.onend=()=>{if(this.rec===t){if(this.want){this.finals=this.text(),this.current=``;try{this.spawn(e);return}catch{}}this.finish()}},this.rec=t;try{t.start()}catch{}}text(){return Mi(`${this.finals} ${this.current}`)}handleResult(e){let t=``,n=-1;for(let r=0;r<e.results.length;r++)t+=` `+e.results[r][0].transcript,e.results[r].isFinal&&(n=r);if(this.current=t,n>=0){let t=this.finals;for(let r=0;r<n;r++)t+=` `+e.results[r][0].transcript;let r=e.results[n],i=[];for(let e=0;e<r.length;e++)r[e]?.transcript&&i.push(Mi(r[e].transcript));this.lastPrefix=Mi(t),this.lastAlts=i}let r=this.text(),i=performance.now(),a=r?r.split(` `):[];this.words=a.map((e,t)=>({text:e,t:this.words[t]?.t??i})),this.onWords?.(this.words)}stop(){if(this.state===`listening`){this.want=!1,this.setState(`finishing`);try{this.rec?.stop()}catch{}this.finishTimer=setTimeout(()=>this.finish(),1600)}}cancel(){this.want=!1,this.done=!0,this.finishTimer&&clearTimeout(this.finishTimer);try{this.rec?.abort()}catch{}this.rec=null,this.setState(`idle`)}finish(){if(this.finishTimer&&clearTimeout(this.finishTimer),this.finishTimer=null,this.rec=null,this.done)return;this.done=!0;let e=this.text(),t=[e];for(let e of this.lastAlts.slice(1)){let n=Mi(`${this.lastPrefix} ${e}`);n&&!t.includes(n)&&t.push(n)}this.setState(`idle`),this.onFinal?.(e,this.words,e?t:[])}},Pi=600,Fi=350,Ii=1700,Li=6e3,Ri=2500,zi=`/models/moonshine/tiny`,Bi=`The on-device speech model isn’t downloaded.`,Vi={text:``,words:[],alternatives:[]},Hi=(e,t)=>Promise.race([e,new Promise(e=>setTimeout(()=>e(null),t))]),Ui=class{state=`idle`;reason=``;onChange=null;worker=null;loading=null;seq=0;waiting=new Map;busy=!1;load(){return this.state===`ready`?Promise.resolve(!0):this.state===`unavailable`?Promise.resolve(!1):(this.loading??=this.boot(),this.loading)}setState(e,t=``){this.state=e,this.reason=t,this.onChange?.(e,t)}async boot(){this.setState(`loading`);let e=``;try{let t=await fetch(`${zi}/encoder_model.onnx`,{method:`HEAD`});if(!t.ok||/text\/html/.test(t.headers.get(`content-type`)??``))throw Error(Bi);let n=new Worker(new URL(`/assets/asr.worker-FcRNDSsJ.js`,``+import.meta.url),{type:`module`});if(this.worker=n,!await new Promise(t=>{let r=setTimeout(()=>t(!1),3e4);n.onmessage=n=>{let i=n.data;if(i.type===`loaded`)clearTimeout(r),t(!0);else if(i.type===`error`&&!i.id)e=i.message??``,clearTimeout(r),t(!1);else if(i.id){let e=this.waiting.get(i.id);this.waiting.delete(i.id),e?.(i)}},n.onerror=n=>{e=n.message,clearTimeout(r),t(!1)},n.postMessage({type:`load`,base:new URL(zi,location.origin).href,wasmPaths:void 0})}))throw Error(e||`The speech model didn’t start in time.`);return n.onerror=()=>this.fail(`The on-device speech model stopped working. Reload the studio to restart it.`),this.setState(`ready`),!0}catch(e){return this.fail(e instanceof Error?e.message:String(e)),!1}}fail(e){this.dispose();for(let e of this.waiting.values())e({type:`error`});this.waiting.clear(),this.setState(`unavailable`,e)}call(e,t,n=[]){if(!this.worker||this.state!==`ready`)return Promise.resolve(null);let r=++this.seq;return new Promise(i=>{let a=setTimeout(()=>{this.waiting.delete(r),i(null)},t);this.waiting.set(r,e=>{clearTimeout(a),i(e.type===`error`?null:e)}),this.worker.postMessage({...e,id:r},n)})}async partial(e){if(this.busy)return null;this.busy=!0;try{return(await this.call({type:`partial`,audio:e},4e3,[e.buffer]))?.text??null}finally{this.busy=!1}}final(e,t){return this.call({type:`final`,key:e,audio:t},1e4,[t.buffer])}async score(e,t,n=!1){return(await this.call({type:`score`,key:e,candidates:t,prune:n},5e3))?.scores??null}retry(){return this.state===`unavailable`&&(this.loading=null,this.state=`idle`),this.load()}dispose(){this.worker?.terminate(),this.worker=null}},Wi=class e{engine=`auto`;lang=`en-US`;autoStopMs=1300;onState=null;onWords=null;onFinal=null;onError=null;onNothing=null;capture=new Oi;asr=new Ui;server=new ki;debug=null;web=new Ni;state=`idle`;seq=0;gen=0;current=null;lastReleased=null;pending=0;webOwner=null;webBrokenAt=-1/0;constructor(){this.web.onWords=e=>{let t=this.webOwner;t&&(t.webWords=e,t===this.current&&this.onWords?.(e,!1))},this.web.onAudioStart=()=>{this.webOwner&&this.webOwner===this.current&&this.goLive(this.webOwner)},this.web.onFinal=(e,t,n)=>{let r=this.webOwner;this.webOwner=null,r?.resolveWeb?.({text:e,words:t,alternatives:n}),setTimeout(()=>{let e=this.current;e&&e.useWeb&&!e.webStarted&&!this.webOwner&&this.runWeb(e)},0)},this.web.onError=(e,t)=>{(e===`network`||e===`service-not-allowed`)&&(this.webBrokenAt=performance.now());let n=this.webOwner;this.webOwner=null,n?.resolveWeb?.(Vi),n&&(n.useWeb=!1,n.webError=t,n.useDevice&&this.asr.state!==`unavailable`||n.useServer?n===this.current&&this.capture.open&&this.goLive(n):(this.onError?.(e,t),this.drop(n)))}}static browserSupported(){return Ni.supported()}get deviceOn(){return!this.arabic&&(this.engine===`device`||this.engine===`auto`&&/^en\b/i.test(this.lang))}get arabic(){return/^ar\b/i.test(this.lang)}get serverOn(){return this.arabic&&this.engine!==`browser`&&this.server.langs.has(`ar`)}get supported(){let t=typeof navigator<`u`&&!!navigator.mediaDevices?.getUserMedia;return this.engine===`device`?t&&(!this.arabic||this.serverOn):e.browserSupported()||(this.deviceOn||this.serverOn)&&t}level(){return this.capture.sample()}warmUp(){this.deviceOn&&this.asr.load()}sync(){let e=this.current?this.current.live?`listening`:`starting`:this.pending?`finishing`:`idle`;e!==this.state&&(this.state=e,this.onState?.(e))}async start(t={}){if(this.current)return!0;let n=performance.now(),r={id:++this.seq,pressAt:n,liveAt:0,releasedAt:0,endCap:1/0,handsFree:!!t.handsFree,live:!1,useDevice:this.deviceOn,useServer:this.serverOn,useWeb:this.engine!==`device`&&e.browserSupported()&&!(this.engine===`auto`&&(this.deviceOn||this.serverOn)&&n-this.webBrokenAt<6e4),webStarted:!1,webStopped:!1,web:null,resolveWeb:null,webWords:[],webError:null,timers:[]},i=this.lastReleased;i&&n<i.releasedAt+Fi&&(i.endCap=n,this.endWeb(i)),this.current=r,this.sync();let a=this.capture.start();r.useDevice&&this.asr.load(),r.useWeb&&(r.web=new Promise(e=>r.resolveWeb=e),this.webOwner||this.runWeb(r));let o=await a;return this.current===r?!o&&!r.useWeb?(this.onError?.(`audio-capture`,this.capture.error??`No microphone available.`),this.drop(r),!1):(o&&(r.useDevice||r.useServer)||!r.useWeb?this.goLive(r):r.timers.push(setTimeout(()=>this.goLive(r),1500)),r.useDevice&&!r.useWeb&&this.startPartials(r),this.watchSilence(r),!0):r.releasedAt>0}runWeb(e){this.web.lang=this.lang,this.webOwner=e,e.webStarted=!0,this.web.start()||(this.webOwner=null,e.useWeb=!1,e.resolveWeb?.(Vi),e===this.current&&(this.capture.open||e.useDevice)&&this.goLive(e))}endWeb(e){this.webOwner!==e||e.webStopped||(e.webStopped=!0,this.web.stop())}goLive(e){this.current!==e||e.live||(e.live=!0,e.liveAt=performance.now(),this.sync())}stop(){let e=this.current;if(!e)return;e.releasedAt=performance.now(),e.timers.forEach(clearTimeout),e.timers=[],this.current=null,this.lastReleased=e,this.pending++,this.sync();let t=this.gen;setTimeout(()=>void this.finish(e,t),Fi)}setHandsFree(e){this.current&&(this.current.handsFree=e)}cancel(){this.gen++;let e=this.current;e&&this.drop(e),this.webOwner&&(this.webOwner.resolveWeb?.(Vi),this.webOwner=null,this.web.cancel()),this.pending=0,this.sync()}drop(e){e.timers.forEach(clearTimeout),e.timers=[],this.webOwner===e&&(this.webOwner=null,this.web.cancel()),e.resolveWeb?.(Vi),this.current===e&&(this.current=null),this.sync()}startPartials(e){e.timers.push(setInterval(async()=>{if(this.current!==e||!e.live||this.asr.state!==`ready`)return;let t=e.pressAt-Pi,n=performance.now(),r=this.capture.voiced(t,n,e.pressAt);if(!r)return;let i=await this.asr.partial(this.capture.slice(Math.max(t,r.start-250),n));i&&this.current===e&&ai(i)&&this.onWords?.(_i(i,r.start,r.end),!0)},700))}watchSilence(e){e.timers.push(setInterval(()=>{if(this.current!==e||!e.live||!e.handsFree)return;let t=performance.now(),n=e.webWords.at(-1)?.t??0,r=this.capture.open?this.capture.lastVoice:0,i=Math.max(n,r),a=i>e.pressAt;a&&t-i>this.autoStopMs?this.stop():!a&&t-e.liveAt>8e3&&(this.drop(e),this.onNothing?.())},100))}modelReady(e){return this.asr.state===`ready`?Promise.resolve(!0):Hi(this.asr.load(),e).then(e=>e===!0)}async finish(e,t){try{if(t!==this.gen)return;let n=e.pressAt-Pi,r=Math.min(e.releasedAt+Fi,e.endCap);this.endWeb(e),this.capture.touch();let i=this.capture.open?this.capture.voiced(n,r,e.pressAt):null;if(e.useServer)return await this.finishOnServer(e,t,n,r,i);let a=i?i.end-i.start:0,o=e.useDevice&&!!i&&this.asr.state!==`unavailable`,s=()=>{let t=this.capture.slice(Math.max(n,i.start-250),Math.min(r,i.end+300));return t.length<3200?Promise.resolve(null):this.modelReady(e.useWeb?4e3:3e4).then(n=>n?this.asr.final(e.id,t):null)},c=o&&(!e.useWeb||a<=Li)?s():null,l=e.web&&e.webStarted?await Hi(e.web,Ri)??Vi:Vi;!c&&o&&!l.alternatives.length&&(c=s());let u=c?await c:null;if(t!==this.gen)return;let d=l.alternatives.map((e,t)=>({text:e,source:`browser`,rank:t})),f=null,p=!!u&&d.length>0&&Zr(d[0].text,u.text);if(u&&!p){u.text&&ai(u.text,u.score,!d.length&&e.webStarted)&&d.push({text:u.text,source:`device`,rank:0}),f={},d.some(e=>e.source===`device`)&&(f[u.text]=u.score);let n=[];for(let e of d)if(!fi(e.text))for(let t of di(e.text))!d.some(e=>e.text===t)&&!n.some(e=>e.text===t)&&n.push({text:t,source:`variant`,rank:0,from:e});let r=[...l.alternatives,...n.map(e=>e.text)],i=r.length?await this.asr.score(e.id,r):{};if(t!==this.gen)return;i?(Object.assign(f,i),d.push(...n)):f=null;let o=f&&gi(d,f);if(f&&a<Ii&&!(o&&fi(o.text))){let n=await this.asr.score(e.id,Yr,!0);if(t!==this.gen)return;for(let[e,t]of Object.entries(n??{}))d.some(t=>t.text===e)||(d.push({text:e,source:`command`,rank:0}),f[e]=t)}}let m=p?d[0]:gi(d,f);this.debug={candidates:d.map(({from:e,...t})=>({...t,...e?{from:{...e,from:void 0}}:{}})),scores:f,chosen:m?.text??null};let h={start:i?.start??e.pressAt,end:i?.end??r},g={span:h,browser:l.alternatives,browserError:e.webError,device:u?.text??``,loudness:this.capture.peak(n,r),ms:Math.round(performance.now()-e.releasedAt)};if(!m){this.onFinal?.({text:``,words:[],aligned:!1,source:`browser`,...g});return}let _=!i&&m.source===`browser`&&m.rank===0&&l.words.length>0,v=_?l.words:_i(m.text,h.start,h.end);this.onFinal?.({text:m.text,words:v,aligned:!_,source:m.source,...g})}finally{t===this.gen&&(this.pending=Math.max(0,this.pending-1)),this.sync()}}async finishOnServer(e,t,n,r,i){let a=i?this.capture.slice(Math.max(n,i.start-250),Math.min(r,i.end+300)):null,o=a&&a.length>=3200?this.server.transcribe(a,`ar`):Promise.resolve(null),s=e.web&&e.webStarted?await Hi(e.web,Ri)??Vi:Vi,c=await Hi(o,15e3)??null;if(t!==this.gen)return;let l=vi(s.alternatives,c?.text??``,e=>!!Ke(e)||fi(e));this.debug={candidates:[...s.alternatives.map((e,t)=>({text:e,source:`browser`,rank:t})),...c?.text?[{text:c.text,source:`device`,rank:0}]:[]],scores:null,chosen:l?.text??null};let u={start:i?.start??e.pressAt,end:i?.end??r},d={span:u,browser:s.alternatives,browserError:e.webError,device:c?.text??``,loudness:this.capture.peak(n,r),ms:Math.round(performance.now()-e.releasedAt)};l?this.onFinal?.({text:l.text,words:_i(l.text,u.start,u.end),aligned:!0,source:l.source,...d}):this.onFinal?.({text:``,words:[],aligned:!1,source:`browser`,...d})}},Gi={anthropic:[{id:`claude-opus-5-5`,label:`Claude Opus 5.5`,tier:`top`,vision:!0,tools:!0,price:{input:4,output:20,cacheRead:.2,cacheWrite:5},note:`Best results`},{id:`claude-sonnet-5-5`,label:`Claude Sonnet 5.5`,tier:`balanced`,vision:!0,tools:!0,price:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},note:`Fast and capable`},{id:`claude-haiku-5-5`,label:`Claude Haiku 5.5`,tier:`fast`,vision:!0,tools:!0,price:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,longAbove:1e5,long:{input:.5,output:2.5,cacheRead:.05,cacheWrite:.625}},note:`Fastest, lightest`},{id:`claude-fable-5-1`,label:`Claude Fable 5.1`,tier:`top`,vision:!0,tools:!0,price:{input:10,output:50,cacheRead:.25,cacheWrite:12.5},note:`Most capable, priciest`}],openai:[{id:`gpt-6.1-sol`,label:`GPT-6.1 Sol`,tier:`top`,vision:!0,tools:!0,price:{input:2,output:10,cacheRead:.1},note:`Best value at the top`},{id:`gpt-6-astra`,label:`GPT-6 Astra`,tier:`top`,vision:!0,tools:!0,price:{input:10,output:50,cacheRead:1},note:`Most capable, priciest`},{id:`gpt-5.4-mini`,label:`GPT-5.4 mini`,tier:`balanced`,vision:!0,tools:!0,price:{input:.75,output:4.5,cacheRead:.075}},{id:`gpt-6-luna`,label:`GPT-6 Luna`,tier:`fast`,vision:!0,tools:!0,price:{input:.1,output:.5,cacheRead:.01},note:`Fastest, lightest`}],gemini:[{id:`gemini-4-argon`,label:`Gemini 4 Argon`,tier:`top`,vision:!0,tools:!0,price:{input:2,output:10,cacheRead:.1},note:`Best results`},{id:`gemini-3.8-flash`,label:`Gemini 3.8 Flash`,tier:`balanced`,vision:!0,tools:!0,price:{input:.75,output:3.75,cacheRead:.075}},{id:`gemini-3.5-flash-lite`,label:`Gemini 3.5 Flash-Lite`,tier:`fast`,vision:!0,tools:!0,price:{input:.3,output:2.5,cacheRead:.03}},{id:`gemini-3.1-flash-lite`,label:`Gemini 3.1 Flash-Lite`,tier:`fast`,vision:!0,tools:!0,price:{input:.25,output:1.5,cacheRead:.025},note:`Cheapest`}],"claude-code":[{id:`opus`,label:`Opus (latest)`,tier:`top`,vision:!0,tools:!0,price:{input:4,output:20,cacheRead:.2,cacheWrite:5}},{id:`sonnet`,label:`Sonnet (latest)`,tier:`balanced`,vision:!0,tools:!0,price:{input:2,output:10,cacheRead:.1,cacheWrite:2.5}},{id:`haiku`,label:`Haiku (latest)`,tier:`fast`,vision:!0,tools:!0,price:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125}}],codex:[{id:`gpt-6.1-sol`,label:`GPT-6.1 Sol`,tier:`top`,vision:!0,tools:!0,price:{input:2,output:10,cacheRead:.1}},{id:`gpt-5.4-mini`,label:`GPT-5.4 mini`,tier:`balanced`,vision:!0,tools:!0,price:{input:.75,output:4.5,cacheRead:.075}}],"gemini-cli":[{id:`gemini-4-argon`,label:`Gemini 4 Argon`,tier:`top`,vision:!0,tools:!0,price:{input:2,output:10,cacheRead:.1}},{id:`gemini-3.8-flash`,label:`Gemini 3.8 Flash`,tier:`balanced`,vision:!0,tools:!0,price:{input:.75,output:3.75,cacheRead:.075}}]},Ki={"deepseek-chat":{input:.28,output:.42,cacheRead:.028},"deepseek-v4-flash":{input:.3,output:1.2,cacheRead:.006},"deepseek-v4-pro":{input:1.32,output:3.96,cacheRead:.044},"openai/gpt-oss-120b":{input:.15,output:.6,cacheRead:.075},"qwen/qwen3.8-27b":{input:.8,output:4},"mistral-medium-latest":{input:1.5,output:7.5,cacheRead:.15},"mistral-large-latest":{input:.5,output:1.5,cacheRead:.05},"devstral-latest":{input:.4,output:2,cacheRead:.04},"codestral-latest":{input:.3,output:.9,cacheRead:.03},"grok-code-fast-1":{input:1,output:2,cacheRead:.2}},qi=[{id:`openrouter`,label:`OpenRouter`,baseUrl:`https://openrouter.ai/api/v1`,keyUrl:`https://openrouter.ai/keys`,note:`One key for hundreds of models from every major lab. Reports the exact cost of each call.`},{id:`ollama`,label:`Ollama`,baseUrl:`http://localhost:11434/v1`,keyUrl:null,local:!0,note:`Models running on this computer. Free and private; changes need a model that can call tools.`},{id:`lmstudio`,label:`LM Studio`,baseUrl:`http://localhost:1234/v1`,keyUrl:null,local:!0,note:`Models running on this computer through LM Studio’s local server.`},{id:`groq`,label:`Groq`,baseUrl:`https://api.groq.com/openai/v1`,keyUrl:`https://console.groq.com/keys`,models:[{id:`openai/gpt-oss-120b`,label:`gpt-oss-120b`,tier:`balanced`,tools:!0,price:Ki[`openai/gpt-oss-120b`]}],note:`Very fast open models.`},{id:`deepseek`,label:`DeepSeek`,baseUrl:`https://api.deepseek.com/v1`,keyUrl:`https://platform.deepseek.com/api_keys`,models:[{id:`deepseek-v4-pro`,label:`DeepSeek V4 Pro`,tier:`top`,tools:!0,price:Ki[`deepseek-v4-pro`]},{id:`deepseek-v4-flash`,label:`DeepSeek V4 Flash`,tier:`fast`,tools:!0,vision:!0,price:Ki[`deepseek-v4-flash`]}]},{id:`mistral`,label:`Mistral`,baseUrl:`https://api.mistral.ai/v1`,keyUrl:`https://console.mistral.ai/api-keys`,models:[{id:`devstral-latest`,label:`Devstral`,tier:`balanced`,tools:!0,price:Ki[`devstral-latest`]},{id:`mistral-medium-latest`,label:`Mistral Medium`,tier:`top`,tools:!0,vision:!0,price:Ki[`mistral-medium-latest`]}]},{id:`xai`,label:`xAI`,baseUrl:`https://api.x.ai/v1`,keyUrl:`https://console.x.ai`,models:[{id:`grok-code-fast-1`,label:`Grok Code Fast`,tier:`fast`,tools:!0,vision:!0,price:Ki[`grok-code-fast-1`]}]},{id:`custom`,label:`Other (OpenAI-compatible)`,baseUrl:``,keyUrl:null,note:`Any server that speaks the OpenAI Chat Completions API.`}];function Ji(e){if(!e)return`AI`;for(let t of Object.values(Gi)){let n=t?.find(t=>t.id===e||e.startsWith(`${t.id}-`)||e.endsWith(`/${t.id}`));if(n&&!/latest|default/i.test(n.label))return n.label}let t=/claude-(\w+)-(\d+)-(\d+)/.exec(e);return t?`Claude ${t[1][0].toUpperCase()}${t[1].slice(1)} ${t[2]}.${t[3]}`:e}function Yi(e){switch(e?.connection){case`anthropic`:case`claude-code`:return`Claude`;case`openai`:case`codex`:return`GPT`;case`gemini`:case`gemini-cli`:return`Gemini`;default:return`AI`}}function Xi(){return Yi(Ir(e=>e.status?.ai.who))}var j=()=>Or.getState(),Zi=`[data-hand], button, a[href], input, textarea, select, summary, label[for], [role="button"], [role="tab"], [role="switch"], [role="menuitem"], [role="menuitemradio"], [role="option"], [role="radio"], [role="slider"], [role="checkbox"], [contenteditable="true"]`,Qi=e=>e instanceof HTMLElement&&!!e.closest(`button, select, [role="switch"], [role="tab"], [role="combobox"], [role="option"], [role="slider"], [role="radio"]`),$i=e=>e instanceof HTMLElement&&(e.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(e.tagName))&&!e.readOnly,ea=50,ta=380,na=e=>[e.selection?.id,...e.pins.map(e=>e.id),...e.previewTargets.map(e=>e.el.id)].join(),ra=class{bridge=new he;tracker=new Vn;engine;voice=new Wi;track=new St;replayer=new On({bridge:this.bridge,connected:()=>A().app.connected,connections:()=>this.appLoads,appUrl:()=>A().app.url||A().status?.target.url||``,enterUse:()=>this.useWhilePlaying(),show:e=>k({replay:e}),point:(e,t)=>this.guideTo(e,t),openReport:e=>E.openReport(e),notify:e=>this.notify(e,`warn`)});autopilot=new bn({bridge:this.bridge,connected:()=>A().app.connected,connections:()=>this.appLoads,appUrl:()=>A().app.url||A().status?.target.url||``,enterUse:()=>this.useWhilePlaying(),show:e=>k({autopilot:e}),point:(e,t)=>this.guideTo(e,t),openReport:e=>E.openReport(e),notify:e=>this.notify(e,`warn`)});guide=null;useWhilePlaying(){let e=A().mode;return e!==`use`&&this.setMode(`use`),()=>{A().mode===`use`&&e!==`use`&&this.setMode(e)}}guideTo(e,t){this.wake();let n=this.geom();if(!e||!n){this.guide=null;return}let r=n.left+(e.rect.x+e.rect.w/2)*n.scale,i=n.top+(e.rect.y+e.rect.h/2)*n.scale;t&&this.ripples.push({x:r,y:i,t:performance.now(),kind:`replay`}),this.guide={x:r,y:i,fromX:this.guide?.x??r-60,fromY:this.guide?.y??i+80,at:performance.now()}}appLoads=0;cursor={x:0,y:0,alpha:0,overApp:!1};ripples=[];stream=null;calibrating=!1;dryRun=null;frameListeners=new Set;streamListeners=new Set;started=!1;frame=null;overlay=null;canvas=null;scale=1;mouse=null;appMouse=null;handTarget=null;video=null;cameraRun=0;raf=0;later=null;lastTick=0;frames=0;clearedProbe=!1;lastProbe=null;trackedAt=0;painted=!1;dragging=null;spaceDownAt=0;spaceConsumed=!1;noticeTimer=null;drafted=null;lastMouseAt=0;resolving=new Set;colors={};cleanups=[];constructor(){this.engine=new on(j().engine,()=>({w:window.innerWidth,h:window.innerHeight}))}start(){if(this.started)return;this.started=!0;let e=j();kr(e.theme),Pr(e.voice.sounds),this.readColors(),this.applyVoiceSettings();let t=setTimeout(()=>this.voice.warmUp(),2500);this.cleanups.push(()=>clearTimeout(t)),this.cleanups.push(Or.subscribe((e,t)=>{e.engine!==t.engine&&(this.engine.configure(e.engine),this.tracker.setNumHands(e.engine.hand===`any`?1:2)),e.theme!==t.theme&&(kr(e.theme),requestAnimationFrame(()=>this.readColors())),e.voice.sounds!==t.voice.sounds&&Pr(e.voice.sounds),e.voice!==t.voice&&(this.applyVoiceSettings(),(e.voice.engine!==t.voice.engine||e.voice.lang!==t.voice.lang)&&this.voice.warmUp())}));let n=matchMedia(`(prefers-color-scheme: dark)`),r=()=>{j().theme===`system`&&(kr(`system`),requestAnimationFrame(()=>this.readColors()))};n.addEventListener(`change`,r),this.cleanups.push(()=>n.removeEventListener(`change`,r)),this.wireVoice(),this.wireBridge(),this.cleanups.push(l({progress:e=>{let t=e,n=A().request;n&&n.id===t.requestId&&n.step!==`Stopping`&&k({request:{...n,step:t.step,detail:t.detail}})},install:e=>{let t=e.line,n=A().recorder;k({recorder:{...n,installLog:[...n.installLog,t].slice(-200)}})},speech:e=>E.serverEvent(`speech`,e),session:e=>E.serverEvent(`session`,e),apps:e=>x.serverEvent(e),usage:e=>{let t=A().status;t&&k({status:{...t,ai:{...t.ai,usage:e}}})},change:e=>{let{change:t,via:n}=e;this.upsertChange(t),this.refreshAfterEdit(),O(`send`),this.notify(`${n} proposed a change: ${t.title}. Keep or undo it.`,`info`)}},e=>{e&&(E.resync(),this.refreshStatus(),this.refreshChanges())}));let i=e=>{let t=this.voice.server.langs;t.clear(),e&&e.runtime!==`missing`&&e.runtime!==`failed`&&(e.active.ar&&t.add(`ar`),e.active.en&&t.add(`en`))};this.cleanups.push(yr.subscribe((e,t)=>e.speech!==t.speech&&i(e.speech))),E.init({frame:()=>this.frame,appConnected:()=>A().app.connected,appUrl:()=>A().app.url||A().status?.target.url||``,bridgeSession:(e,t,n,r)=>this.bridge.session(e,t,n,r),bridgeMark:(e,t)=>this.bridge.mark(e,t),enterUse:()=>{let e=A().mode;return e!==`use`&&this.setMode(`use`),()=>{A().mode===`use`&&e!==`use`&&this.setMode(e)}},notify:(e,t)=>this.notify(e,`ok`,t),locate:async e=>(await this.bridge.locator(e))?.locator??null}),this.cleanups.push(Ir.subscribe((e,t)=>e.selection!==t.selection||e.pins!==t.pins||e.app.url!==t.app.url?this.pushContext():void 0));let a=e=>this.onKeyDown(e),o=e=>this.onKeyUp(e),s=()=>this.releaseTalk();window.addEventListener(`keydown`,a),window.addEventListener(`keyup`,o),window.addEventListener(`blur`,s),this.cleanups.push(()=>{window.removeEventListener(`keydown`,a),window.removeEventListener(`keyup`,o),window.removeEventListener(`blur`,s)}),x.init(()=>this.appSwitched()),this.refreshStatus(),this.refreshChanges().then(()=>this.announceWaiting()),this.cleanups.push(Ir.subscribe((e,t)=>{((e.selection!==t.selection||e.pins!==t.pins||e.previewTargets!==t.previewTargets)&&na(e)!==na(t)||e.camera.status!==t.camera.status)&&this.wake()})),this.wake(),e.camera.enabled&&e.onboarded&&e.labs.hand&&this.startCamera(),this.cleanups.push(Or.subscribe((e,t)=>e.labs.hand!==t.labs.hand&&!e.labs.hand&&A().camera.status!==`off`&&this.stopCamera(!1)))}dispose(){this.started=!1,this.rest();for(let e of this.cleanups.splice(0))e();this.stopCamera(!1),this.bridge.detach()}readColors(){let e=getComputedStyle(document.documentElement);for(let t of[`human`,`ai`,`ok`,`bad`,`fg`,`fg-2`,`inverse`,`glass`])this.colors[t]=e.getPropertyValue(`--${t}`).trim()}attachFrame(e,t){!e||!t?(this.bridge.detach(),this.frame=null):(this.frame=e,this.bridge.attach(e,t))}frameLoaded(){k({app:{...A().app,connected:!1}}),this.bridge.sayHello()}attachOverlay(e){this.overlay=e}attachCanvas(e){this.canvas=e,this.painted=!1,e&&(e.style.visibility=`hidden`),this.wake()}setScale(e){this.scale=e||1}geom(){if(!this.frame)return null;let e=this.frame.getBoundingClientRect();return e.width?{left:e.left,top:e.top,scale:this.scale,w:e.width,h:e.height}:null}toApp(e,t){let n=this.geom();return n?{x:(e-n.left)/n.scale,y:(t-n.top)/n.scale}:null}wireBridge(){let e=this.bridge;e.onReady=({url:t,title:n})=>{this.appLoads++,k({app:{...A().app,connected:!0,url:t,title:n,outdated:void 0}});let r=A().mode;e.trackMouse(r!==`edit`),e.record(r===`record`),e.forwardKeys(!0),this.reresolveAll()},e.onOutdated=e=>k({app:{...A().app,connected:!1,outdated:e}}),e.onNavigated=({url:e,title:t})=>k({app:{...A().app,url:e,title:t}}),e.onProbe=e=>{let t=A();(!Rr(t.hover,e.hit)||t.snapped!==e.snapped)&&k({hover:e.hit,snapped:e.snapped}),t.hover?.id!==e.hit?.id&&E.pointed(e.hit,t.pointer===`hand`?`hand`:`mouse`);let n=this.engine.state.pose,r=t.pointer!==`hand`||n===`point`||n===`pinch`;this.track.push(performance.now(),r?e.hit:null),this.applyTracked(e.tracked)},e.onMouse=e=>{this.appMouse=e,this.wake(),e&&(this.lastMouseAt=performance.now())},e.onRecorded=e=>{if(A().mode!==`record`)return;let t=A().recorder;k({recorder:{...t,steps:[...t.steps,{kind:e.kind,locator:e.locator,description:e.description,value:`value`in e?e.value:void 0,key:`key`in e?e.key:void 0}]}})},e.onKey=(e,t)=>{e===`Space`?t?this.pressTalk():this.releaseTalk():e===`Escape`&&t?this.stop(`key`):e===`Mark`&&t&&E.mark(``,`shortcut`)},e.onSession=e=>E.bridgeSaid(e.id),e.onMoment=e=>E.moment(e)}trackedIds(){let e=A(),t=new Set;e.selection&&t.add(e.selection.id);for(let n of e.pins)t.add(n.id);for(let n of e.previewTargets)t.add(n.el.id);return[...t]}applyTracked(e){let t=A(),n=t=>{if(!(String(t.id)in e))return t;let n=e[t.id];return n?n.x===t.rect.x&&n.y===t.rect.y&&n.w===t.rect.w&&n.h===t.rect.h?t:{...t,rect:n}:`gone`},r=!1,i={};if(t.selection){let e=n(t.selection);e===`gone`?this.resolveLater(t.selection):e!==t.selection&&(i.selection=e,r=!0)}let a=t.pins.map(e=>{let t=n(e);return t===`gone`?(this.resolveLater(e),e):(t!==e&&(r=!0),t)});r&&(i.pins=a);let o=!1,s=t.previewTargets.map(e=>{let t=n(e.el);return t===`gone`?(this.resolveLater(e.el),e):(t!==e.el&&(o=!0),t===e.el?e:{...e,el:t})});o&&(i.previewTargets=s),(r||o)&&k(i)}resolveLater(e){this.resolving.has(e.id)||(this.resolving.add(e.id),setTimeout(async()=>{let t=e.src?await this.bridge.resolve(e.src,e.index):null;this.replaceEl(e.id,t),setTimeout(()=>this.resolving.delete(e.id),400)},120))}replaceEl(e,t){let n=A();k({selection:n.selection?.id===e?t:n.selection,pins:n.pins.flatMap(n=>n.id===e?t?[t]:[]:[n]),previewTargets:n.previewTargets.flatMap(n=>n.el.id===e?t?[{...n,el:t}]:[]:[n])}),n.selection?.id===e&&t?.src&&t.src!==n.selection.src&&this.loadInspect(t)}async reresolveAll(){let e=A(),t=async e=>e.src?await this.bridge.resolve(e.src,e.index):null;k({selection:e.selection?await t(e.selection):null,pins:(await Promise.all(e.pins.map(t))).filter(e=>!!e),previewTargets:(await Promise.all(e.previewTargets.map(async e=>({...e,el:await t(e.el)})))).filter(e=>!!e.el),hover:null})}refreshAfterEdit(){let e=A();e.status?.app?.framework===`static`&&e.app.url&&this.bridge.goto(e.app.url);for(let e of[300,900,2e3])setTimeout(()=>void this.refreshTargets(),e)}async refreshTargets(){let e=A(),t=async e=>await this.bridge.describe(e.id)??(e.src?await this.bridge.resolve(e.src,e.index):null),n=e.selection?await t(e.selection):null,r=(await Promise.all(e.pins.map(t))).filter(e=>!!e),i=(await Promise.all(e.previewTargets.map(async e=>({...e,el:await t(e.el)})))).filter(e=>!!e.el),a=A();k({selection:a.selection?.id===e.selection?.id?n:a.selection,pins:a.pins===e.pins?r:a.pins,previewTargets:a.previewTargets===e.previewTargets?i:a.previewTargets});let o=A().selection;o&&this.loadInspect(o,!0)}wake=()=>{!this.raf&&this.started&&(this.later&&clearTimeout(this.later),this.later=null,this.raf=requestAnimationFrame(this.loop))};rest(){cancelAnimationFrame(this.raf),this.raf=0,this.later&&clearTimeout(this.later),this.later=null}loop=e=>{this.raf=0;let t=Math.min(64,e-(this.lastTick||e));this.lastTick=e,this.frames++;let n=this.engine.state,r=A().camera.status===`on`&&n.present&&!this.calibrating;if(r){this.cursor.alpha<=.01&&(this.cursor.x=n.x,this.cursor.y=n.y);let e=1-Math.exp(-t/18);this.cursor.x+=(n.x-this.cursor.x)*e,this.cursor.y+=(n.y-this.cursor.y)*e,this.cursor.alpha=Math.min(1,this.cursor.alpha+t/120)}else this.cursor.alpha=Math.max(0,this.cursor.alpha-t/220);let i=this.pointer(r),a=i?i.source:null;A().pointer!==a&&k({pointer:a}),this.updateDwell(e,r);let o=this.trackedIds(),s=this.geom(),c=!1;if(i&&i.inApp&&s){let t=(i.x-s.left)/s.scale,n=(i.y-s.top)/s.scale,r=this.lastProbe;c=!!r&&!o.length&&Math.abs(t-r.x)<.75&&Math.abs(n-r.y)<.75&&e-r.t<200&&r.deep===i.deep,c||(this.bridge.probe(t,n,i.radius/s.scale,i.deep,o,i.source===`hand`),this.lastProbe={x:t,y:n,t:e,deep:i.deep}),this.clearedProbe=!1}else(!this.clearedProbe||o.length&&e-this.trackedAt>=ea)&&(this.lastProbe=null,this.bridge.probe(null,null,0,!1,o),this.clearedProbe=!0,this.trackedAt=e);this.frames%30==0&&A().camera.status===`on`&&A().camera.fps!==this.tracker.fps&&k({camera:{...A().camera,fps:this.tracker.fps}}),this.draw(e),A().camera.status===`on`||this.cursor.alpha>.01||this.ripples.length>0||this.guide&&e-this.guide.at<ta||i?.inApp&&!c?this.raf=requestAnimationFrame(this.loop):(i?.inApp||o.length)&&(this.later=setTimeout(this.wake,i?.inApp?200:ea))};pointer(e){let t=A().mode;if(e){let e=this.hitStudio(this.cursor.x,this.cursor.y);return this.setHandTarget(e.kind===`studio`?e.el:null),this.cursor.overApp=e.kind===`app`,{x:this.cursor.x,y:this.cursor.y,source:`hand`,radius:j().aimAssist,deep:!1,inApp:e.kind===`app`}}if(this.setHandTarget(null),t===`edit`&&this.mouse)return{...this.mouse,source:`mouse`,radius:0,deep:this.mouse.alt,inApp:!0};if(t!==`edit`&&this.appMouse){let e=this.geom();return e?{x:e.left+this.appMouse.x*e.scale,y:e.top+this.appMouse.y*e.scale,source:`mouse`,radius:0,deep:!1,inApp:!0}:null}return null}hitStudio(e,t){let n=(e,t)=>{let n=document.elementFromPoint(e,t);if(!n)return null;if(n===this.frame||this.overlay&&(n===this.overlay||this.overlay.contains(n)))return{kind:`app`};let r=n.closest(Zi);return r&&!r.closest(`[data-hand-ignore]`)&&!r.disabled?{kind:`studio`,el:r}:null},r=n(e,t);if(r)return r;for(let r of[10,20])for(let i=0;i<8;i++){let a=i/8*Math.PI*2,o=n(e+Math.cos(a)*r,t+Math.sin(a)*r);if(o?.kind===`studio`)return o}return{kind:`none`}}setHandTarget(e){e!==this.handTarget&&(this.handTarget?.removeAttribute(`data-hand-hover`),this.handTarget=e,e?.setAttribute(`data-hand-hover`,``))}draw(e){let t=this.canvas;if(!t)return;if(!this.ripples.length&&!this.guide&&(this.calibrating||this.cursor.alpha<=.01)){this.painted&&=(t.getContext(`2d`)?.clearRect(0,0,t.width,t.height),t.style.visibility=`hidden`,!1);return}this.painted||(t.style.visibility=`visible`),this.painted=!0;let n=Math.min(2,window.devicePixelRatio||1),r=window.innerWidth,i=window.innerHeight;(t.width!==Math.round(r*n)||t.height!==Math.round(i*n))&&(t.width=Math.round(r*n),t.height=Math.round(i*n));let a=t.getContext(`2d`);if(!a)return;a.setTransform(n,0,0,n,0,0),a.clearRect(0,0,r,i);let o=this.colors.human||`#ffb224`;for(let t=this.ripples.length-1;t>=0;t--){let n=this.ripples[t],r=(e-n.t)/450;r>=1?this.ripples.splice(t,1):(a.globalAlpha=(1-r)*.9,a.strokeStyle=n.kind===`replay`?this.colors.ai||`#3dd6f5`:o,a.lineWidth=2,a.beginPath(),a.arc(n.x,n.y,10+r*(n.kind===`pin`?34:24),0,Math.PI*2),a.stroke())}let s=this.guide;if(s){let t=1-(1-Math.min(1,(e-s.at)/ta))**3,n=s.fromX+(s.x-s.fromX)*t,r=s.fromY+(s.y-s.fromY)*t,i=this.colors.ai||`#3dd6f5`;a.globalAlpha=1,a.fillStyle=i,a.strokeStyle=this.colors.inverse||`#000`,a.lineWidth=1.5,a.beginPath(),a.moveTo(n,r),a.lineTo(n+3.5,r+17),a.lineTo(n+7.5,r+12.5),a.lineTo(n+14,r+13),a.closePath(),a.fill(),a.stroke()}let c=this.calibrating?0:this.cursor.alpha;if(c<=.01){a.globalAlpha=1;return}let l=this.engine.state,{x:u,y:d}=this.cursor;if(a.globalAlpha=c,a.lineWidth=2,l.clutched)a.setLineDash([3,4]),a.strokeStyle=this.colors[`fg-2`]||`#999`,a.beginPath(),a.arc(u,d,14,0,Math.PI*2),a.stroke(),a.setLineDash([]),a.fillStyle=this.colors[`fg-2`]||`#999`,a.fillRect(u-4,d-5,2.5,10),a.fillRect(u+1.5,d-5,2.5,10);else if(l.dragging){a.strokeStyle=o,a.fillStyle=aa(o,.18),a.beginPath(),a.arc(u,d,15,0,Math.PI*2),a.fill(),a.stroke(),a.fillStyle=o;for(let e of[-1,1])a.beginPath(),a.moveTo(u-4.5,d+e*3),a.lineTo(u,d+e*8),a.lineTo(u+4.5,d+e*3),a.closePath(),a.fill()}else if(l.pinching)a.fillStyle=o,a.beginPath(),a.arc(u,d,6.5,0,Math.PI*2),a.fill(),a.strokeStyle=aa(o,.6),a.beginPath(),a.arc(u,d,11,0,Math.PI*2),a.stroke();else{let e=l.pinchAmount,t=(this.handTarget?9:15)-(this.handTarget?3:6)*e;a.fillStyle=aa(o,(this.handTarget?.04:.1)+.25*e),a.strokeStyle=o,a.beginPath(),a.arc(u,d,t,0,Math.PI*2),a.fill(),a.stroke(),a.fillStyle=o,a.beginPath(),a.arc(u,d,2.4,0,Math.PI*2),a.fill()}if(l.holdKind&&l.holdProgress>.03){let e=l.holdKind===`thumbUp`?this.colors.ok:l.holdKind===`thumbDown`?this.colors.bad:l.holdKind===`victory`?o:this.colors.fg;this.ring(a,u,d,l.holdProgress,e||`#fff`,{palm:`Stop`,thumbUp:`Keep`,thumbDown:`Undo`,victory:`Talk`}[l.holdKind])}else if(l.pinching&&!l.dragging&&l.pinchHold>.03){let e=this.pinchHoldMeaning();e!==`none`&&this.ring(a,u,d,l.pinchHold,o,e===`add`?`Add`:`Remove`)}else this.dwellProgress>.03&&this.ring(a,u,d,this.dwellProgress,o,`Select`);a.globalAlpha=1}ring(e,t,n,r,i,a){e.lineWidth=3,e.lineCap=`round`,e.strokeStyle=aa(i,.2),e.beginPath(),e.arc(t,n,23,0,Math.PI*2),e.stroke(),e.strokeStyle=i,e.beginPath(),e.arc(t,n,23,-Math.PI/2,-Math.PI/2+Math.PI*2*r),e.stroke(),e.lineCap=`butt`,e.font=`600 11px "Geist Variable", system-ui, sans-serif`;let o=e.measureText(a).width,s=t+30,c=n-9;e.fillStyle=i,oa(e,s,c,o+14,19,6),e.fill(),e.fillStyle=this.colors.inverse||`#000`,e.fillText(a,s+7,c+13.5)}async startCamera(e){if(!jr())return!1;let t=A();if(t.camera.status===`starting`)return!1;if(t.camera.status===`on`&&e===void 0)return!0;t.camera.status===`on`&&this.stopCamera(!1);let n=++this.cameraRun,r=()=>n!==this.cameraRun||!jr();k({camera:{...A().camera,status:`starting`,error:null}});let i=null;try{if(i=await ve((e===void 0?j().camera.deviceId:e)??void 0),r()||(this.stream=i,this.video||(this.video=document.createElement(`video`),this.video.muted=!0,this.video.playsInline=!0),this.video.srcObject=i,await this.video.play().catch(()=>void 0),r()))return this.letGoOf(i,n);for(let e of this.streamListeners)e(i);return this.tracker.numHands=j().engine.hand===`any`?1:2,await this.tracker.init(),r()?this.letGoOf(i,n):(this.tracker.onFrame=e=>this.onFrame(e),this.tracker.start(this.video),k({camera:{status:`on`,error:null,fps:0,delegate:this.tracker.delegate}}),j().setCamera({enabled:!0,...e===void 0?{}:{deviceId:e}}),!0)}catch(e){if(r())return this.letGoOf(i,n);be(this.stream),this.stream=null;for(let e of this.streamListeners)e(null);let t=e instanceof ge?e.message:`Hand tracking couldn’t start: ${e?.message??e}`;return k({camera:{status:`error`,error:t,fps:0,delegate:null}}),this.notify(t,`error`),!1}}letGoOf(e,t){if(be(e),t===this.cameraRun)this.stopCamera(!1);else if(e&&this.stream===e){this.stream=null;for(let e of this.streamListeners)e(null)}return!1}stopCamera(e=!0){this.cameraRun++,this.tracker.stop(),be(this.stream),this.stream=null;for(let e of this.streamListeners)e(null);this.engine.update({t:performance.now()+1e4,hands:[],aspect:4/3}),this.setHandTarget(null),k({camera:{status:`off`,error:null,fps:0,delegate:null},hand:{...A().hand,present:!1,holdKind:null}}),e&&j().setCamera({enabled:!1})}toggleCamera(){A().camera.status===`on`?this.stopCamera():this.startCamera()}onFrame(e){let t=this.engine.update(e);for(let t of this.frameListeners)t(e);for(let e of t)this.onHandEvent(e);let n=this.engine.state,r=A().hand;(r.present!==n.present||r.pose!==n.pose||r.holdKind!==n.holdKind||r.clutched!==n.clutched||r.dragging!==n.dragging||r.hand!==n.hand)&&k({hand:{present:n.present,pose:n.pose,holdKind:n.holdKind,clutched:n.clutched,dragging:n.dragging,hand:n.hand}})}onHandEvent(e){if(!this.calibrating)switch(e.type){case`lost`:this.dragging=null,this.setHandTarget(null);return;case`pinchStart`:return this.handPinchStart(e.x,e.y);case`hold`:return this.handHold(e.x,e.y);case`pinchCancel`:return this.restorePinch();case`tap`:return this.handTap(e.x,e.y);case`dragStart`:this.restorePinch(),this.dragging=this.hitStudio(e.x,e.y).kind===`app`?`app`:null;return;case`drag`:{if(this.dragging!==`app`||this.replayer.running||this.autopilot.running)return;let t=this.toApp(this.cursor.x,this.cursor.y);t&&this.bridge.scroll(t.x,t.y,-e.dx*1.7/this.scale,-e.dy*1.7/this.scale);return}case`dragEnd`:this.dragging=null;return;case`palm`:return this.stop(`palm`);case`thumbUp`:this.keep(`thumb`);return;case`thumbDown`:this.undo(`thumb`);return;case`victory`:return this.toggleTalk()}}pinchPick=null;handTargetAt(e,t){let n=A().hover,r=this.toApp(e,t);if(!n||!r)return null;let i=j().aimAssist/this.scale+6,a=n.rect;return r.x<a.x-i||r.x>a.x+a.w+i||r.y<a.y-i||r.y>a.y+a.h+i?null:n}handPinchStart(e,t){if(this.pinchPick=null,A().mode!==`edit`||this.hitStudio(e,t).kind!==`app`)return;let n=A(),r=this.handTargetAt(e,t),i={selection:n.selection,pins:n.pins};this.pinchPick={before:i,target:r},un(r,sn(i)).tap!==`none`&&(this.ripples.push({x:e,y:t,t:performance.now(),kind:`tap`}),O(`tap`),this.setPicked(dn(i,r)))}handHold(e,t){let n=this.pinchPick;n&&A().mode===`edit`&&(this.pinchPick=null,un(n.target,sn(n.before)).hold!==`none`&&(this.ripples.push({x:e,y:t,t:performance.now(),kind:`pin`}),O(`pick`),this.setPicked(fn(n.before,n.target))))}restorePinch(){let e=this.pinchPick;this.pinchPick=null,e&&this.setPicked(e.before)}handTap(e,t){let n=this.hitStudio(e,t);if(A().mode===`edit`&&n.kind===`app`){this.pinchPick=null;return}if(n.kind===`none`)return;if(this.ripples.push({x:e,y:t,t:performance.now(),kind:`tap`}),O(`tap`),n.kind===`studio`)return sa(n.el,e,t);if(this.replayer.running||this.autopilot.running)return;let r=A().hover,i=this.toApp(e,t);if(!i)return;let a=r&&i.x>=r.rect.x&&i.x<=r.rect.x+r.rect.w&&i.y>=r.rect.y&&i.y<=r.rect.y+r.rect.h,o=!r||a?i:{x:r.rect.x+r.rect.w/2,y:r.rect.y+r.rect.h/2};this.bridge.click(o.x,o.y)}pinchHoldMeaning(){let e=this.pinchPick;return e?un(e.target,sn(e.before)).hold:`none`}mouseMove(e,t,n){this.mouse={x:e,y:t,alt:n},this.lastMouseAt=performance.now(),this.wake()}mouseLeave(){this.mouse=null,this.wake()}async mouseClick(e,t,n,r,i=1){if(i>1)return;let a=this.toApp(e,t),o=(async()=>{let e=(a?await this.bridge.probeAt(a.x,a.y,0,r):null)??A().hover,t={selection:A().selection,pins:A().pins};this.setPicked(n?fn(t,e):dn(t,e))})();this.picking=o;try{await o}finally{this.picking===o&&(this.picking=null)}}picking=null;wheel(e,t){let n=this.mouse;if(!n)return;let r=this.toApp(n.x,n.y);r&&this.bridge.scroll(r.x,r.y,e/this.scale,t/this.scale)}select(e){this.setPicked(cn(e?[e]:[]))}setPicked(e){let t=A(),n=e.selection,r=n?.id===t.selection?.id,i=r||n?.src&&t.inspect?.file&&n.src.startsWith(t.inspect.file+`:`)?t.inspect:null;k({selection:n,pins:e.pins,inspect:n?i:null}),n&&(!r||!t.inspect)&&this.loadInspect(n)}toggleSelected(e){this.setPicked(fn({selection:A().selection,pins:A().pins},e))}deselect(e){let t=A();this.setPicked(cn(sn(t).filter(t=>t.id!==e),t.selection))}clearTargets(){k({selection:null,pins:[],inspect:null})}async step(e){let t=A().selection;if(!t)return this.notify(e===`parent`?`Select something first, then go up to what contains it.`:`Select something first.`,`info`);let n=await this.bridge.step(t.id,e);if(!n)return this.notify({parent:`That’s already the outermost element.`,child:`There’s nothing inside it to select.`,next:`That’s the last one.`,prev:`That’s the first one.`}[e],`info`);let r=A();r.selection?.id===t.id&&this.setPicked(pn(r,t,n))}selectParent(){return this.step(`parent`)}async selectCalled(e,t,n){let r=await this.bridge.find(n?.id??null,e,t);if(!r){let r=n?t===`in`?`inside it`:t===`out`?`around it`:`around or inside it`:`on the page`;return this.notify(`Couldn’t find a “${e}” ${r}.`,`info`)}let i=A();i.selection&&n?.id===i.selection.id?this.setPicked(pn(i,i.selection,r)):this.select(r)}dwell=null;dwellProgress=0;updateDwell(e,t){let n=A(),r=this.engine.state,i=n.hover;!j().dwellSelect||!t||n.mode!==`edit`||!this.cursor.overApp||!i||r.pinching||r.dragging||r.pose!==`point`&&r.pose!==`other`||n.pins.length||i.id===n.selection?.id||!i?(this.dwell=null,this.dwellProgress=0):(this.dwell?.id!==i.id&&(this.dwell={id:i.id,since:e,done:!1}),this.dwellProgress=this.dwell.done?0:Math.min(1,Math.max(0,(e-this.dwell.since-200)/800)),!this.dwell.done&&e-this.dwell.since>=1e3&&(this.dwell.done=!0,this.dwellProgress=0,this.ripples.push({x:this.cursor.x,y:this.cursor.y,t:e,kind:`tap`}),O(`tap`),this.select(i)))}traceEl(e){return c.post(`/inspect`,{ref:{src:e.src,frames:e.frames,hint:e.hint,tag:e.tag,text:e.text},pageUrl:A().app.url})}async loadInspect(e,t=!1){t||k({inspectLoading:!0});try{let{result:t}=await this.traceEl(e);A().selection?.id===e.id&&k({inspect:t})}catch{}finally{t||k({inspectLoading:!1})}}async setProp(e,t){let n=A().selection;if(n?.src)try{let r=await c.post(`/props`,{src:n.src,prop:e,value:t});this.applyResult(r,`${e}: ${t}`,[n])}catch(e){this.fail(e)}}async openInEditor(e){let t=e??A().selection??A().hover;if(!t)return this.notify(`Point at or select something from your app first.`,`info`);let n=A().inspect,r=n&&t.id===A().selection?.id?n:null;if(!r)try{r=(await this.traceEl(t)).result}catch{r=null}if(!r)return this.notify(`Couldn’t find that element’s source file.`,`warn`);await this.openFile(r.absPath,r.line,r.col)}async openFile(e,t=1,n=1){let r=`${e.split(`/`).slice(-2).join(`/`)}:${t}`,i=await fetch(`/__open-in-editor?file=${encodeURIComponent(`${e}:${t}:${n}`)}`,{method:`POST`}).catch(()=>null);if(i?.ok)return this.notify(`Opening ${r} in your editor…`,`info`);let a=(await i?.json().catch(()=>null))?.error;this.notify(a??`Couldn’t open ${r} in your editor.`,`warn`)}openRelative(e,t=1){let n=A().status?.target.root;n&&this.openFile(`${n.replace(/\/$/,``)}/${e}`,t,1)}async copyLocator(e){let t=await this.bridge.locator(e.id);if(!t)return this.notify(`Couldn’t build a locator for that element.`,`warn`);await navigator.clipboard?.writeText(t.locator.code).catch(()=>void 0),this.notify(`Copied ${t.locator.code}`,`ok`)}setMode(e){if(A().mode!==e&&(this.mouse=null,this.appMouse=null,this.wake(),k({mode:e,hover:null}),this.bridge.trackMouse(e!==`edit`),this.bridge.record(e===`record`),e===`record`)){let e=A().recorder;!e.steps.length&&!e.expectations.length&&k({recorder:{...Fr,startUrl:A().app.url||A().status?.target.url||null}}),j().setUi({panelOpen:!0,panelTab:`test`})}}newRecording(){k({recorder:{...Fr,startUrl:A().app.url||null}})}removeStep(e){let t=A().recorder;k({recorder:{...t,steps:t.steps.filter((t,n)=>n!==e)}})}removeExpectation(e){let t=A().recorder;k({recorder:{...t,expectations:t.expectations.filter((t,n)=>n!==e)}})}reloadApp(){k({app:{...A().app,connected:!1,reloadKey:A().app.reloadKey+1},hover:null})}applyVoiceSettings(){let e=j().voice;this.voice.engine=e.engine,this.voice.lang=e.lang,this.voice.autoStopMs=e.autoStopMs,k({voice:{...A().voice,supported:this.voice.supported}})}wireVoice(){let e=this.voice;e.asr.onChange=(e,t)=>k({voice:{...A().voice,model:e,modelError:t}}),e.onState=e=>{let t=A().voice.state;k({voice:{...A().voice,state:e,...e===`idle`?{trigger:null,words:[],bindings:[]}:{}}}),e===`listening`&&t!==`listening`&&O(`listen`)},e.onWords=(e,t)=>{k({voice:{...A().voice,words:e.map(e=>e.text),bindings:this.bind(e,t)}})},e.onFinal=e=>{let t={text:e.text,source:e.source,browser:e.browser,browserError:e.browserError,device:e.device,loudness:e.loudness,ms:e.ms};k({voice:{...A().voice,last:t}});let n=this.talking();if(this.dryRun)return!n&&A().island.kind===`listening`&&k({island:{kind:`idle`}}),this.dryRun(e.text,e);if(!e.text.trim()){!n&&A().island.kind===`listening`&&k({island:{kind:`idle`}});return}O(`send`);let r={words:e.words,aligned:e.aligned,span:e.span};if(j().voice.review)return this.draftSpoken(e,r);this.handleUtterance(e.text,r,`voice`)},e.onError=(e,t)=>{k({voice:{...A().voice,error:t}}),O(`error`),this.notify(t,`error`)},e.onNothing=()=>this.notify(`Didn’t hear anything. Try again, a little closer to the mic.`,`info`)}bind(e,t=!1){let n=A(),r=t?0:Tt.lagMs;return Dt(e,this.track,{...Tt,lagMs:r,pins:n.pins,selection:n.selection}).map(e=>({index:e.index,word:e.word,el:e.el,via:e.via}))}draftSpoken(e,t){this.drafted=t;let n=[...new Set([...e.browser,e.device])].filter(t=>t&&t!==e.text).slice(0,3);A().island.kind===`listening`&&k({island:{kind:`idle`}}),k({draft:{text:e.text,alternatives:n,n:(A().draft?.n??0)+1}})}submitText(e){let t=e.trim(),n=this.drafted;if(this.clearDraft(),t){if(n)return void this.handleUtterance(t,{...n,words:_i(t,n.span.start,n.span.end),aligned:!0},`voice`);this.handleUtterance(t,null,`typed`)}}clearDraft(){this.drafted=null,A().draft&&k({draft:null})}startTalk(e){this.voice.supported?this.talking()||(this.noticeTimer&&clearTimeout(this.noticeTimer),this.applyVoiceSettings(),k({voice:{...A().voice,trigger:e,words:[],bindings:[],error:null},island:{kind:`listening`}}),this.voice.start({handsFree:e===`toggle`})):(this.notify(`Voice needs a microphone and Chrome, Edge or Safari. Type your request instead.`,`warn`),k({focusInput:A().focusInput+1}))}stopTalk(){this.voice.stop()}cancelTalk(e){this.voice.cancel(),k({voice:{...A().voice,state:`idle`,trigger:null,words:[],bindings:[]}}),e?this.notify(e,`info`):A().island.kind===`listening`&&k({island:{kind:`idle`}})}talking(){let e=A().voice.state;return e===`starting`||e===`listening`}toggleTalk(){this.talking()?this.stopTalk():this.startTalk(`toggle`)}pressTalk(){this.spaceDownAt=performance.now(),this.talking()&&A().voice.trigger===`toggle`?(this.spaceConsumed=!0,this.stopTalk()):(this.spaceConsumed=!1,this.startTalk(`hold`))}releaseTalk(){if(!this.spaceDownAt)return;let e=performance.now()-this.spaceDownAt;if(this.spaceDownAt=0,this.spaceConsumed){this.spaceConsumed=!1;return}let t=A().voice;this.talking()&&t.trigger===`hold`&&(e<280?(k({voice:{...t,trigger:`toggle`}}),this.voice.setHandsFree(!0)):this.stopTalk())}onKeyDown(e){if(e.defaultPrevented)return;let t=A(),n=e.metaKey||e.ctrlKey;if(n&&e.key.toLowerCase()===`k`)e.preventDefault(),k({overlay:t.overlay===`palette`?null:`palette`});else if((!t.overlay&&!Jn()||e.code===`Space`&&this.dryRun&&!Qi(e.target))&&!$i(e.target)){if(e.code===`Space`&&!n&&!e.altKey)e.preventDefault(),e.repeat||this.pressTalk();else if(!e.repeat){if(e.key===`Escape`)return this.stop(`key`);if(e.key===`Enter`&&!n&&Lr(t).length)e.preventDefault(),this.keep(`key`);else if(n&&e.key.toLowerCase()===`z`&&!e.shiftKey)Lr(t).length&&(e.preventDefault(),this.undo(`key`));else if(!(n||e.altKey))switch(e.key){case`/`:e.preventDefault(),k({focusInput:t.focusInput+1});return;case`?`:k({overlay:`help`});return;case`e`:case`E`:return this.setMode(`edit`);case`u`:case`U`:return this.setMode(`use`);case`r`:case`R`:return this.setMode(`record`);case`c`:case`C`:return jr()?this.toggleCamera():void 0;case`m`:case`M`:E.recording&&E.mark(``,`key`);return;case`\\`:j().setUi({panelOpen:!j().ui.panelOpen});return;case`ArrowUp`:case`ArrowDown`:case`ArrowLeft`:case`ArrowRight`:t.selection&&!yr.getState().open&&(e.preventDefault(),this.step({ArrowUp:`parent`,ArrowDown:`child`,ArrowLeft:`prev`,ArrowRight:`next`}[e.key]));return;case`o`:case`O`:t.selection&&this.openInEditor(t.selection);return}}}}onKeyUp(e){e.code===`Space`&&this.spaceDownAt&&(e.preventDefault(),this.releaseTalk())}async handleUtterance(e,t,n){let r=e.trim();if(!r)return;if(this.picking&&await this.picking,this.dryRun)return A().island.kind===`listening`&&k({island:{kind:`idle`}}),this.dryRun(r);let i=A();k({history:[r,...i.history.filter(e=>e!==r)].slice(0,40)});let a=Ke(r),o=a?.text??r;if(E.recording&&(a?.kind===`session`||/^(?:mark|flag|bookmark)(?: (?:this|that|it|here|the moment|this moment))?[.!]?$/i.test(r)))return A().island.kind===`listening`&&k({island:{kind:`idle`}}),E.mark(r,`voice`),this.notify(`Marked this moment.`,`ok`);let s=vt(o,{hasFailingTest:i.recorder.run?.status===`failed`&&!!i.recorder.spec});if(E.command(r,n,s?s.kind:a?a.kind:`request`),s)return A().island.kind===`listening`&&k({island:{kind:`idle`}}),this.runCommand(s,t);if(i.mode===`record`){let e=yt(o);if(e)return this.addExpectation(e,t)}return this.sendIntent(o,t,n)}pointedAt(e){if(e?.words.length){let t=e.aligned?0:Tt.lagMs,n=Dt(e.words,this.track,{...Tt,lagMs:t,pins:[],selection:null}).find(e=>e.el);if(n?.el)return n.el;let r=this.pointedWhile(e);if(r)return r}return A().hover}pointedWhile(e){return this.track.dwellWinner(e.span.start-300,e.span.end+150)}targetFrom(e){let t=A();if(e?.words.length){let t=this.bind(e.words,e.aligned).find(e=>e.el);if(t?.el)return t.el;let n=this.pointedWhile(e);if(n)return n}if(t.selection)return t.selection;if(t.hover)return t.hover;if(t.mode===`record`){let e=this.track.dwellWinner(performance.now()-5e3,performance.now());if(e)return e}return t.pins[0]??null}async runCommand(e,t){switch(e.kind){case`keep`:return this.keep(`voice`);case`undo`:return this.undo(`voice`);case`cancel`:return this.stop(`voice`);case`parent`:return this.selectParent();case`nav`:return this.step(e.to);case`find`:{let n=A();return this.selectCalled(e.what,e.where,n.selection??(t?.words.length?this.pointedWhile(t):null)??n.hover)}case`clear`:return this.clearTargets(),this.notify(`Nothing selected.`,`info`);case`mode`:return this.setMode(e.mode),this.notify(e.mode===`record`?`Recording. Use the app, then point at what’s wrong and say what it should show.`:`${e.mode===`edit`?`Edit`:`Use`} mode.`,`info`);case`generate`:return this.generateTest();case`run`:return this.runTest();case`fix`:return this.fix(t?`voice`:`typed`);case`click`:{let e=this.targetFrom(t);if(!e)return this.notify(`Point at what to click while you say it.`,`info`);await this.bridge.click(e.rect.x+e.rect.w/2,e.rect.y+e.rect.h/2);return}case`type`:(await this.bridge.type(e.text,e.submit)).ok||this.notify(`Click a text field in the app first, then say “type …”.`,`info`);return;case`scroll`:{let t=this.geom();if(!t)return;let n=t.w/t.scale/2,r=t.h/t.scale/2,i=t.h/t.scale*.7,a=e.dir===`down`?i:e.dir===`up`?-i:e.dir===`top`?-1e6:1e6;this.bridge.scroll(n,r,0,a);return}case`reload`:return this.reloadApp();case`help`:k({overlay:`help`});return;case`open`:return this.openInEditor(this.targetFrom(t));case`select`:{let e=this.pointedAt(t);e?this.select(e):this.notify(`Point at what to select while you say it.`,`info`);return}case`add`:{let e=this.pointedAt(t);e?this.toggleSelected(e):this.notify(`Point at what to add while you say it.`,`info`);return}}}refsFor(e){let t=A(),n=[];if(e?.words.length&&(n=this.bind(e.words,e.aligned).filter(e=>e.el).map(e=>({el:e.el,role:e.via===`pin`?`pin:${e.word}`:e.word}))),!n.length){let r=e?.words.length?this.pointedWhile(e):t.hover;n=Ot(t.pins,t.selection,r).map((e,n)=>({el:e,role:t.pins.length?`pin ${n+1}`:t.selection?`selection`:`pointed`}))}let r=new Set,i=n.filter(e=>r.has(e.el.id)&&e.role===`it`?!1:(r.add(e.el.id),!0));return{refs:i.map(({el:e,role:t})=>({role:t,src:e.src,name:e.name,label:e.label,text:e.text,tag:e.tag,hint:e.hint,frames:e.frames})),els:i.map(e=>e.el)}}pointerKind(){return A().camera.status===`on`&&performance.now()-this.engine.state.lastSeen<3e3?`hand`:performance.now()-this.lastMouseAt<5e3?`mouse`:`none`}requests=new jn({started:(e,t)=>k({request:e,...t?{island:{kind:`thinking`}}:{}}),stopping:e=>{let t=A().request;t?.id===e&&k({request:{...t,step:`Stopping`,detail:void 0}})},ended:e=>{A().request?.id===e&&k({request:null})},waiting:e=>k({waiting:e}),cancel:e=>c.post(`/cancel`,{requestId:e}).catch(()=>void 0),fail:e=>this.fail(e)});appEpoch=0;ask(e){return this.requests.ask(e)||(this.notify(`3 requests are already waiting. Let them finish, or press Esc to stop them.`,`info`),Promise.resolve())}sendIntent(e,t,n){let{refs:r,els:i}=this.refsFor(t);return this.intent({text:e,refs:r,els:i,input:n,pointer:this.pointerKind(),pageUrl:A().app.url})}intent(e){let t=this.appEpoch;return this.ask({text:e.text,kind:`intent`,step:`Working`,run:async(n,r)=>{try{let i=await c.post(`/intent`,{text:e.text,refs:e.refs,requestId:n,input:e.input,pointer:e.pointer,pageUrl:e.pageUrl,...e.ai?{ai:!0}:{}});this.settle(n,i,e.text,e.els,{stopped:r(),epoch:t,again:()=>void this.intent({...e,ai:!0})})}finally{this.refreshSummary()}}})}settle(e,t,n,r,i){return A().request?.id===e&&k({request:null}),i.epoch===this.appEpoch?t.kind===`change`?(this.applyResult(t,n,r),i.stopped&&this.notify(`It was done before it could stop: “${t.change.title}” is a preview now. Keep or undo it.`,`info`),!0):(i.stopped||this.applyResult(t,n,r,i.again),!1):!1}applyResult(e,t,n,r){switch(e.kind){case`change`:{this.upsertChange(e.change);let t=n.map(t=>({changeId:e.change.id,el:t}));k({previewTargets:[...A().previewTargets,...t].slice(-8),island:{kind:`idle`}}),this.refreshAfterEdit();return}case`answer`:k({island:{kind:`answer`,text:e.text,said:t,model:e.model,latencyMs:e.latencyMs}});return;case`message`:return e.tone===`error`&&O(`error`),this.notify(e.text,e.tone===`error`?`error`:e.tone===`warn`?`warn`:`info`,this.nextActions(e.next,r));case`needs-key`:k({island:{kind:`needs-key`,text:e.text,actions:this.nextActions(e.next,r)}});return}}nextActions(e,t){let n=(e??[]).flatMap(e=>{switch(e.kind){case`ask-ai`:{let e=Yi(A().status?.ai.who);return t?[{label:e===`AI`?`Ask the AI anyway`:`Ask ${e} anyway`,primary:!0,run:()=>(this.dismissIsland(),t())}]:[]}case`connect-ai`:return[{label:`Connect an AI`,primary:!0,run:()=>k({overlay:`settings`,settingsTab:`ai`,island:{kind:`idle`}})}];case`link-folder`:return[{label:`Link its folder…`,primary:!0,run:()=>(this.dismissIsland(),x.show(`folder`))}];case`open`:{let t=/^(.+?):(\d+)(?::\d+)?$/.exec(e.src);return!t||!A().status?.target.root?[]:[{label:t[2]===`1`?`Open ${se(t[1])}`:`Open ${se(t[1])}:${t[2]}`,run:()=>this.openRelative(t[1],Number(t[2]))}]}}});return n.length?n:void 0}upsertChange(e){k({changes:[e,...A().changes.filter(t=>t.id!==e.id)]})}async keep(e,t){if(!t&&!Lr(A()).length)return this.notify(`Nothing is waiting to be kept.`,`info`);try{let n=await c.post(`/changes/keep`,{id:t,via:e,commit:j().ui.commitOnKeep});O(`keep`),await this.decided(n.kept);let r=n.kept.length===1?n.kept[0].title:`${n.kept.length} changes`;n.commitError?this.notify(`Kept: ${r}, but not committed. Git said: ${n.commitError}`,`warn`):this.notify(`Kept: ${r}${n.committed?` (committed)`:``}`,`ok`)}catch(e){this.fail(e)}}async undo(e,t=!1,n){if(!n&&!Lr(A()).length)return this.notify(`Nothing to undo.`,`info`);try{let r=await c.post(`/changes/undo`,{id:n,via:e,force:t});O(`undo`),await this.decided(r.undone),this.notify(r.undone.length===1?`Undone: ${r.undone[0].title}`:`Undid ${r.undone.length} changes.`,`info`),this.refreshAfterEdit()}catch(t){if(t instanceof o&&t.code===`conflict`){O(`error`),k({island:{kind:`message`,tone:`warn`,text:t.message,sticky:!0,actions:[{label:`Undo anyway`,run:()=>void this.undo(e,!0,n)},{label:`Leave it`,run:()=>k({island:{kind:`idle`}})}]}});return}this.fail(t)}}async decided(e){let t=new Set(e.map(e=>e.id));k({previewTargets:A().previewTargets.filter(e=>!t.has(e.changeId)),recorder:{...A().recorder,verifying:!1}}),await this.refreshChanges(),this.refreshSummary()}undoChange(e){return this.undo(`panel`,!1,e)}keepChange(e){return this.keep(`panel`,e)}stop(e){let t=A();if(this.replayer.running)return this.replayer.stop();if(this.autopilot.running)return this.autopilot.stop();if(t.voice.state!==`idle`)return this.cancelTalk();if(t.request)return void this.cancelRequest();if(t.island.kind!==`idle`)return k({island:{kind:`idle`}});if(t.selection||t.pins.length)return this.clearTargets()}async cancelRequest(){let e=this.requests.stop();e!==null&&this.notify(e?`Stopped. ${e===1?`The request waiting after it wasn’t sent.`:`The ${e} requests waiting after it weren’t sent.`}`:`Stopped.`,`info`)}dismissIsland(){k({island:{kind:`idle`}})}notify(e,t=`info`,n){this.noticeTimer&&clearTimeout(this.noticeTimer);let r={kind:`message`,text:e,tone:t,actions:n};k({island:r}),n?.length||(this.noticeTimer=setTimeout(()=>{A().island===r&&k({island:{kind:`idle`}})},t===`error`?7e3:t===`warn`?6e3:3800))}fail(e){O(`error`),this.notify(e instanceof Error?e.message:String(e),`error`)}async addExpectation(e,t){let n=this.targetFrom(t);if(!n)return this.notify(`Point at the element that shows the wrong value while you say it.`,`warn`);let r=await this.bridge.locator(n.id);if(!r)return this.notify(`Couldn’t build a locator for that element. Try pointing at it again.`,`warn`);let i={locator:r.locator.code,description:r.locator.description,expected:e.expected,actual:r.locator.text},a=A().recorder;k({recorder:{...a,expectations:[...a.expectations,i],spec:null,run:null}}),O(`keep`),this.notify(`Check added: ${i.description} should show “${i.expected}”${i.actual?`, it shows “${de(i.actual,i.expected)?.slice(0,40)}”`:``}.`,`ok`,[{label:`Generate test`,primary:!0,run:()=>void this.generateTest()},{label:`Add another`,run:()=>this.dismissIsland()}])}async addExpectationFor(e,t){let n=await this.bridge.locator(e.id);if(!n)return this.notify(`Couldn’t build a locator for that element.`,`warn`);let r=A().recorder,i={locator:n.locator.code,description:n.locator.description,expected:t,actual:n.locator.text};k({recorder:{...r,expectations:[...r.expectations,i],spec:null,run:null}})}findingTargets(e,t){let n=[];for(let r of e){let e=r.kind===`speech`?t.transcript.find(e=>e.start===r.t):null,i=r.issue?t.issues.find(e=>e.id===r.issue):null,a=e?.el??i?.el;a&&!n.some(e=>e.src===a.src&&e.label===a.label)&&n.push(a)}return n.slice(0,4)}async fixFromReport(e,t,n){let r=this.findingTargets(t,n).map(e=>({role:`finding`,src:e.src,name:e.name,label:e.label,text:e.text,tag:e.tag,hint:e.hint})),i=[`Fix this problem found in a test session: ${e.title}.`,...xt(e,t)].join(`
4
+ `);j().setUi({panelOpen:!0,panelTab:`changes`});let a=this.appEpoch;await this.ask({text:`Fix: ${e.title}`,kind:`fix`,step:`Working`,run:async(t,n)=>{let o=await c.post(`/intent`,{text:i.slice(0,1990),refs:r,requestId:t,input:`typed`,pointer:`none`,pageUrl:A().app.url});this.settle(t,o,e.title,[],{stopped:n(),epoch:a})}})}async fixFindings(e,t){if(!e.length)return;let n=[],r=e.map(({f:e,items:r},i)=>{for(let e of this.findingTargets(r,t))n.length<8&&!n.some(t=>(t.src??t.label)===(e.src??e.label))&&n.push({role:`finding`,src:e.src,name:e.name,label:e.label,text:e.text,tag:e.tag,hint:e.hint});return[`${i+1}. [${e.severity}] ${e.title}`,...xt(e,r).map(e=>` ${e}`)].join(`
5
+ `)}).join(`
6
+
7
+ `),i=e.length;await this.reportTask(`Fix ${i===1?`this problem`:`these ${i} problems`} found in a test session.`,r,n,i===1?`Fix: ${e[0].f.title}`:`Fix ${i} findings`)}async implementSuggestions(e,t){if(!e.length)return;let n=[`The session: ${t.title}. ${t.summary}`,``,...e.map((e,t)=>`${t+1}. (${e.kind}, ${e.effort} effort) ${e.title}: ${e.why}`)].join(`
8
+ `),r=e.length;await this.reportTask(`Implement ${r===1?`this suggestion`:`these ${r} suggestions`} from a test session report.`,n,[],r===1?e[0].title:`${r} suggestions`)}async reveal(e){A().mode!==`edit`&&this.setMode(`edit`);let t=await this.bridge.reveal(e.id,e.src,e.index);return t&&this.select(t),t}async fixReview(e,t){if(!e.length)return;let n=[];for(let t of e)for(let e of t.els??[])n.length<8&&!n.some(t=>(t.src??t.label)===(e.src??e.label))&&n.push({role:`finding`,src:e.src,name:e.name,label:e.label,text:e.text,tag:e.tag,hint:e.hint,frames:e.frames});let r=e.map((e,t)=>`${t+1}. [${e.rule}] ${e.title}\n Found: ${e.what}\n Fix: ${e.fix}${e.rewrite?`\n Change the text “${e.rewrite.before}” to “${e.rewrite.after}”.`:``}`).join(`
9
+ `),i=e.length===1?`Fix: ${e[0].title}`:`Fix ${e.length} ${t} findings`;await this.reportTask(`Fix these ${t} findings from the studio's page review. Fix each at its root: when the elements share a design token, style or component (one colour, one size), change that once so every use is fixed; the elements named are examples. Otherwise make the smallest change that satisfies the rule.`,r,n,i)}async reportTask(e,t,n,r){j().setUi({panelOpen:!0,panelTab:`changes`});let i=this.appEpoch;await this.ask({text:r,kind:`fix`,step:`Working`,run:async(a,o)=>{let s=await c.post(`/intent`,{text:e,brief:t.slice(0,16e3),refs:n,requestId:a,input:`typed`,pointer:`none`,pageUrl:A().app.url});this.settle(a,s,r,[],{stopped:o(),epoch:i})}})}async startAutopilot(e){if(!(this.autopilot.running||this.replayer.running)){if(!A().app.connected)return this.notify(`Open your app first: Autopilot uses it here, in the studio.`,`info`);if(!A().status?.ai.ready)return this.notify(`Autopilot needs an AI to decide what to try.`,`info`,[{label:`Connect an AI`,primary:!0,run:()=>k({overlay:`settings`,settingsTab:`ai`,island:{kind:`idle`}})}]);E.closeReport(),E.recording&&await E.stop(),await this.autopilot.run(e)}}async verifySession(e){if(!this.replayer.running){if(!e.analysis?.steps.some(e=>e.kind!==`navigate`&&e.locator))return this.notify(`This session has no steps to replay.`,`info`);E.closeReport(),E.recording&&await E.stop(),await this.replayer.run(e)}}async testFromReport(e,t,n,r){let i=ia(n,t.length?t[t.length-1].t+1e3:1/0),a=n.steps.find(e=>e.kind===`navigate`)?.url??r,o=[],s=Tn(e,n);s&&o.push({locator:s.locator,description:s.el.description??s.el.label,expected:s.expected,actual:s.el.text}),k({recorder:{...Fr,startUrl:a,steps:i,expectations:o}}),j().setUi({panelOpen:!0,panelTab:`test`}),o.length?await this.generateTest():this.notify(`Loaded ${i.length} steps from the session. Now point at the value that is wrong and say what it should show, or add a check in the Test tab.`,`info`)}checkSession(e,t){let n=ia(e);k({recorder:{...Fr,startUrl:e.steps.find(e=>e.kind===`navigate`)?.url??t,steps:n}}),this.setMode(`record`),j().setUi({panelOpen:!0,panelTab:`test`}),this.notify(`Loaded ${n.length} steps from the session. Point at a value that must be right, like a total, and say what it should show.`,`info`,[{label:`Got it`,run:()=>this.dismissIsland()}])}async generateTest(){let e=A().recorder;if(!e.expectations.length)return j().setUi({panelOpen:!0,panelTab:`test`}),this.notify(`First say what you expected: point at the wrong value and say “this should show …”.`,`info`);try{let t=await c.post(`/tests/generate`,{startUrl:e.startUrl??A().app.url,steps:e.steps,expectations:e.expectations});k({recorder:{...A().recorder,spec:t,run:null}}),j().setUi({panelOpen:!0,panelTab:`test`}),this.notify(`Test saved to ${t.path}.`,`ok`,[{label:`Run it`,primary:!0,run:()=>void this.runTest()}])}catch(e){this.fail(e)}}async runTest(){let e=A().recorder.spec;if(!e){if(!A().recorder.expectations.length)return this.notify(`Record a bug first: switch to Record mode, use the app, then say what you expected.`,`info`);if(await this.generateTest(),e=A().recorder.spec,!e)return}if(A().recorder.running||this.requests.has(`test`))return;let t=e.path;await this.ask({text:`Run ${t}`,kind:`test`,step:`Running the test`,run:e=>this.testRun(e,t)})}async testRun(e,t){k({recorder:{...A().recorder,running:!0}});let n;try{n=await c.post(`/tests/run`,{path:t})}catch(e){n={status:`error`,durationMs:0,message:e instanceof Error?e.message:String(e)}}let r=A().recorder.verifying;switch(k({recorder:{...A().recorder,running:!1,run:{...n,at:Date.now()}}}),A().request?.id===e&&k({request:null}),this.refreshSummary(),n.status){case`passed`:O(`keep`),r&&Lr(A()).length?k({island:{kind:`message`,tone:`ok`,sticky:!0,text:`The test passes with this fix. Keep it?`,actions:[{label:`Keep fix`,primary:!0,run:()=>void this.keep(`test`)},{label:`Undo`,run:()=>void this.undo(`test`)}]}}):this.notify(`Test passed in ${(n.durationMs/1e3).toFixed(1)} s.`,`ok`);return;case`failed`:O(`error`),k({recorder:{...A().recorder,verifying:!1}}),k({island:{kind:`message`,tone:`error`,sticky:!0,text:n.expected||n.received?`Test failed: expected “${n.expected??`?`}”, got “${n.received??`?`}”.`:`Test failed. ${n.message?.split(`
10
+ `)[0]??``}`,actions:[{label:`Fix with ${Yi(A().status?.ai.who)}`,primary:!0,run:()=>void this.fix()},{label:`Details`,run:()=>(j().setUi({panelOpen:!0,panelTab:`test`}),this.dismissIsland())}]}});return;case`setup-needed`:k({island:{kind:`message`,tone:`warn`,sticky:!0,text:n.message??`Playwright needs a one-time setup.`,actions:[{label:`Install test browser`,primary:!0,run:()=>void this.installBrowser()}]}});return;default:O(`error`),this.notify(n.message??`The test couldn’t run.`,`error`)}}async fix(e){let t=A().recorder;if(!t.spec||t.run?.status!==`failed`)return this.notify(`Run a failing test first, then ask for a fix.`,`info`);let n={path:t.spec.path,failure:t.run.message??``,input:e},r=this.appEpoch;await this.ask({text:`Fix the bug this test shows`,kind:`fix`,step:`Reading the failing test`,run:async(e,t)=>{let i=await c.post(`/fix`,{...n,requestId:e});this.settle(e,i,`fix it`,[],{stopped:t(),epoch:r})&&!t()&&(k({recorder:{...A().recorder,verifying:!0}}),setTimeout(()=>void this.runTest(),500))}})}async installBrowser(){k({recorder:{...A().recorder,installing:!0,installLog:[]},island:{kind:`idle`}}),j().setUi({panelOpen:!0,panelTab:`test`});try{let{ok:e}=await c.post(`/tests/install`);this.notify(e?`Test browser installed. Run the test again.`:`The install failed. See the log in the Test tab.`,e?`ok`:`error`,e?[{label:`Run test`,primary:!0,run:()=>void this.runTest()}]:void 0)}catch(e){this.fail(e)}finally{k({recorder:{...A().recorder,installing:!1}})}}appSwitched(){this.appEpoch++,this.requests.stop(),k({selection:null,pins:[],hover:null,previewTargets:[],inspect:null,recorder:Fr,changes:[],replay:null}),this.refreshStatus(),this.refreshChanges().then(()=>this.announceWaiting()),E.refreshList()}announceWaiting(){let e=A().changes.filter(e=>e.status===`preview`).length;e&&this.notify(e===1?`A change from before is still a preview in your code. Keep it or undo it.`:`${e} changes from before are still previews in your code. Keep or undo them.`,`info`)}async refreshStatus(){try{let e=await c.get(`/status`);return k({status:e,statusError:null}),e}catch(e){return k({statusError:e instanceof Error?e.message:String(e)}),setTimeout(()=>void this.refreshStatus(),2e3),null}}async refreshChanges(){try{let{changes:e}=await c.get(`/changes`);k({changes:e})}catch{}}async refreshSummary(){try{k({summary:await c.get(`/metrics/summary`)})}catch{}}pushContext=(()=>{let e=null,t=``;return()=>{e&&clearTimeout(e),e=setTimeout(()=>{let e=A(),n=(e,t)=>({role:t,src:e.src,name:e.name,label:e.label,text:e.text,tag:e.tag,hint:e.hint,frames:e.frames}),r={pageUrl:e.app.url||null,selection:e.selection?[n(e.selection,`selection`)]:[],pins:e.pins.map(e=>n(e,`pin`))},i=JSON.stringify(r);i!==t&&(t=i,c.put(`/context`,r).catch(()=>void 0))},400)}})()};function ia(e,t=1/0){return e.steps.filter(e=>e.t<=t&&e.kind!==`navigate`&&e.locator).map(e=>({kind:e.kind===`fill`?`fill`:e.kind===`press`?`press`:`click`,locator:e.locator,value:e.value,checked:e.checked,key:e.key,description:e.description}))}function aa(e,t){let n=/^#([0-9a-f]{6})$/i.exec(e);if(!n)return e;let r=parseInt(n[1],16);return`rgba(${r>>16&255}, ${r>>8&255}, ${r&255}, ${t})`}function oa(e,t,n,r,i,a){e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+i,a),e.arcTo(t+r,n+i,t,n+i,a),e.arcTo(t,n+i,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath()}function sa(e,t,n){let r={bubbles:!0,cancelable:!0,composed:!0,clientX:t,clientY:n,button:0,view:window},i={...r,pointerId:1,pointerType:`mouse`,isPrimary:!0};e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?e.focus():(e.dispatchEvent(new PointerEvent(`pointerdown`,{...i,buttons:1})),e.dispatchEvent(new MouseEvent(`mousedown`,{...r,buttons:1})),e.dispatchEvent(new PointerEvent(`pointerup`,{...i,buttons:0})),e.dispatchEvent(new MouseEvent(`mouseup`,{...r,buttons:0})),e.dispatchEvent(new MouseEvent(`click`,{...r,buttons:0})))}var ca=new ra,M=n(),la=(0,a.createContext)({});function ua(e){let t=(0,a.useRef)(null);return t.current===null&&(t.current=e()),t.current}var da=typeof window<`u`?a.useLayoutEffect:a.useEffect,fa=(0,a.createContext)(null);function pa(e,t){e.indexOf(t)===-1&&e.push(t)}function ma(e,t){let n=e.indexOf(t);n>-1&&e.splice(n,1)}var N=(e,t,n)=>n>t?t:n<e?e:n,ha=()=>{},ga=()=>{},P={},_a=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),va=e=>typeof e==`object`&&!!e,ya=e=>/^0[^.\s]+$/u.test(e);function ba(e){let t;return()=>(t===void 0&&(t=e()),t)}var F=e=>e,xa=(...e)=>e.reduce((e,t)=>n=>t(e(n))),Sa=(e,t,n)=>{let r=t-e;return r?(n-e)/r:1},Ca=class{constructor(){this.subscriptions=[]}add(e){return pa(this.subscriptions,e),()=>this.remove(e)}remove(e){ma(this.subscriptions,e)}notify(e,t,n){let r=this.subscriptions.length;if(r){if(r===1)this.subscriptions[0](e,t,n);else for(let i=0;i<r;i++){let r=this.subscriptions[i];r&&r(e,t,n)}}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}},I=e=>e*1e3,L=e=>e/1e3,wa=(e,t)=>t?1e3/t*e:0,Ta=(e,t,n)=>e*(3*(1-e)*((1-e)*t+e*n)+e*e);function Ea(e,t,n,r){return e===t&&n===r?F:i=>{let a=0,o=1,s=i;for(let t=0;;t++){s>=a&&s<=o||(s=(a+o)/2);let r=Ta(s,e,n)-i;if(r*r<1e-28||t===40)break;r>0?o=s:a=s,s-=r*1e-7/(Ta(s+1e-7,e,n)-i-r)}return Ta(s,t,r)}}var Da=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Oa=e=>t=>1-e(1-t),ka=Ea(.33,1.53,.69,.99),Aa=Oa(ka),ja=Da(Aa),Ma=e=>e>=1?1:(e*=2)<1?.5*Aa(e):.5*(2-2**(-10*(e-1))),Na=e=>1-Math.sin(Math.acos(e)),Pa=Oa(Na),Fa=Da(Na),Ia=Ea(.42,0,1,1),La=Ea(0,0,.58,1),Ra=Ea(.42,0,.58,1),za=e=>Array.isArray(e)&&typeof e[0]!=`number`,Ba=e=>Array.isArray(e)&&typeof e[0]==`number`,Va={linear:F,easeIn:Ia,easeInOut:Ra,easeOut:La,circIn:Na,circInOut:Fa,circOut:Pa,backIn:Aa,backInOut:ja,backOut:ka,anticipate:Ma},Ha=e=>typeof e==`string`,Ua=e=>{if(Ba(e)){e.length;let[t,n,r,i]=e;return Ea(t,n,r,i)}return Ha(e)?(Va[e],`${e}`,Va[e]):e},R={delta:0,timestamp:0,isProcessing:!1},Wa;function Ga(){Wa=void 0}var z={now:()=>(Wa===void 0&&z.set(R.isProcessing||P.useManualTiming?R.timestamp:performance.now()),Wa),set:e=>{Wa=e,queueMicrotask(Ga)}},Ka=e=>Math.round(e*1e5)/1e5,qa=e=>t=>typeof t==`string`&&t.startsWith(e),Ja=qa(`--`),Ya=qa(`var(--`),Xa=e=>Ya(e)?Za.test(e.split(`/*`)[0].trim()):!1,Za=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Qa(e){return typeof e==`string`&&e.split(`/*`)[0].includes(`var(--`)}var $a={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},eo={...$a,transform:e=>N(0,1,e)},to={...$a,default:1},no=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function ro(e){return e==null}var io=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ao=(e,t)=>n=>!!(typeof n==`string`&&io.test(n)&&n.startsWith(e)||t&&!ro(n)&&Object.prototype.hasOwnProperty.call(n,t)),oo=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(no);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},so=e=>N(0,255,e),co={...$a,transform:e=>Math.round(so(e))},lo={test:ao(`rgb`,`red`),parse:oo(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+co.transform(e)+`, `+co.transform(t)+`, `+co.transform(n)+`, `+Ka(eo.transform(r))+`)`};function uo(e){let t=``,n=``,r=``,i=``;return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),i=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),i=e.substring(4,5),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}}var fo={test:ao(`#`),parse:uo,transform:lo.transform},po=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),mo=po(`deg`),B=po(`%`),V=po(`px`),ho=po(`vh`),go=po(`vw`),_o={...B,parse:e=>B.parse(e)/100,transform:e=>B.transform(e*100)},vo={test:ao(`hsl`,`hue`),parse:oo(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+B.transform(Ka(t))+`, `+B.transform(Ka(n))+`, `+Ka(eo.transform(r))+`)`},H={test:e=>lo.test(e)||fo.test(e)||vo.test(e),parse:e=>lo.test(e)?lo.parse(e):vo.test(e)?vo.parse(e):fo.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?lo.transform(e):vo.transform(e),getAnimatableNone:e=>{let t=H.parse(e);return t.alpha=0,H.transform(t)}},yo=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu,bo=new RegExp(no.source),xo=new RegExp(yo.source,`i`);function So(e){return isNaN(e)&&typeof e==`string`&&(bo.test(e)||xo.test(e))}var Co=`number`,wo=`color`,To=`var`,Eo=`var(`,Do="${}",Oo=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function ko(e){let t=e.toString();return bo.test(t)||xo.test(t)}function Ao(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(Oo,e=>(H.test(e)?(r.color.push(a),i.push(wo),n.push(H.parse(e))):e.startsWith(Eo)?(r.var.push(a),i.push(To),n.push(e)):(r.number.push(a),i.push(Co),n.push(parseFloat(e))),++a,Do)).split(Do),indexes:r,types:i}}function jo(e){return Ao(e).values}function Mo({split:e,types:t}){let n=e.length;return r=>{let i=``;for(let a=0;a<n;a++)if(i+=e[a],r[a]!==void 0){let e=t[a];i+=e===Co?Ka(r[a]):e===wo?H.transform(r[a]):r[a]}return i}}function No(e){return Mo(Ao(e))}var Po=e=>typeof e==`number`?0:H.test(e)?H.getAnimatableNone(e):e,Fo=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:Po(e);function Io(e){let t=Ao(e);return Mo(t)(t.values.map((e,n)=>Fo(e,t.split[n])))}var U={test:So,parse:jo,createTransformer:No,getAnimatableNone:Io};function Lo(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function Ro({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let i=0,a=0,o=0;if(!t)i=a=o=n;else{let r=n<.5?n*(1+t):n+t-n*t,s=2*n-r;i=Lo(s,r,e+1/3),a=Lo(s,r,e),o=Lo(s,r,e-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(o*255),alpha:r}}function zo(e,t){return n=>n>0?t:e}var W=(e,t,n)=>e+(t-e)*n,Bo=(e,t,n)=>{let r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},Vo=[fo,lo,vo],Ho=e=>Vo.find(t=>t.test(e));function Uo(e){let t=Ho(e);if(!t)return`${e}`,!1;let n=t.parse(e);return t===vo&&(n=Ro(n)),n}var Wo=(e,t)=>{let n=Uo(e),r=Uo(t);if(!n||!r)return zo(e,t);let i={...n};return e=>(i.red=Bo(n.red,r.red,e),i.green=Bo(n.green,r.green,e),i.blue=Bo(n.blue,r.blue,e),i.alpha=W(n.alpha,r.alpha,e),lo.transform(i))},Go=new Set([`none`,`hidden`]);function Ko(e,t){return Go.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function qo(e,t){return n=>W(e,t,n)}function Jo(e){return typeof e==`number`?qo:typeof e==`string`?Xa(e)?zo:H.test(e)?Wo:Qo:Array.isArray(e)?Yo:typeof e==`object`?H.test(e)?Wo:Xo:zo}function Yo(e,t){let n=[...e],r=n.length,i=e.map((e,n)=>Jo(e)(e,t[n]));return e=>{for(let t=0;t<r;t++)n[t]=i[t](e);return n}}function Xo(e,t){let n={...e,...t},r={};for(let i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=Jo(e[i])(e[i],t[i]));return e=>{for(let t in r)n[t]=r[t](e);return n}}function Zo(e,t){let n=[],r={color:0,var:0,number:0};for(let i=0;i<t.values.length;i++){let a=t.types[i],o=e.indexes[a][r[a]],s=e.values[o]??0;n[i]=s,r[a]++}return n}var Qo=(e,t)=>{let n=U.createTransformer(t),r=Ao(e),i=Ao(t);return r.indexes.var.length===i.indexes.var.length&&r.indexes.color.length===i.indexes.color.length&&r.indexes.number.length>=i.indexes.number.length?Go.has(e)&&!i.values.length||Go.has(t)&&!r.values.length?Ko(e,t):xa(Yo(Zo(r,i),i.values),n):(`${e}${t}`,zo(e,t))},$o=/^(-?(?:\d+(?:\.\d*)?|\.\d+))([a-z%]*)$/iu;function es(e,t){let n=$o.exec(e);if(!n)return;let r=$o.exec(t);if(!r||n[2]!==r[2])return;let i=n[2],a=parseFloat(n[1]),o=parseFloat(r[1]);return e=>Ka(W(a,o,e))+i}function ts(e,t,n){if(typeof e==`number`&&typeof t==`number`&&typeof n==`number`)return W(e,t,n);if(typeof e==`string`&&typeof t==`string`){let n=es(e,t);if(n)return n}return Jo(e)(e,t)}var ns=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`];function rs(e){let t=new Set,n=new Set,r=!1,i=!1,a=new Set,o={delta:0,timestamp:0,isProcessing:!1};function s(t){a.has(t)&&(n.add(t),e()),t(o)}let c={schedule:(e,i=!1,o=!1)=>{let s=o&&r?t:n;return i&&a.add(e),s.add(e),e},cancel:e=>{n.delete(e),a.delete(e)},process:e=>{if(o=e,r){i=!0;return}r=!0;let a=t;t=n,n=a,t.forEach(s),t.clear(),r=!1,i&&(i=!1,c.process(e))}};return c}var is=40;function as(e,t,n={delta:0,timestamp:0,isProcessing:!1}){let r=!1,i=!0,a=()=>r=!0,o=ns.reduce((e,t)=>(e[t]=rs(a),e),{}),{setup:s,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:f,render:p,postRender:m}=o,h=()=>{let a=P.useManualTiming,o=a?n.timestamp:performance.now();r=!1,a||(n.delta=i?1e3/60:Math.max(Math.min(o-n.timestamp,is),1)),n.timestamp=o,n.isProcessing=!0,s.process(n),c.process(n),l.process(n),u.process(n),d.process(n),f.process(n),p.process(n),m.process(n),n.isProcessing=!1,r&&t&&(i=!1,e(h))},g=()=>{r=!0,i=!0,n.isProcessing||e(h)};return{schedule:ns.reduce((e,t)=>{let n=o[t];return e[t]=(e,t=!1,i=!1)=>(r||g(),n.schedule(e,t,i)),e},{}),cancel:e=>{for(let t=0;t<ns.length;t++)o[ns[t]].cancel(e)},state:n,steps:o}}var{schedule:G,cancel:os,steps:ss}=as(typeof requestAnimationFrame<`u`?requestAnimationFrame:F,!0,R),cs=e=>{let t=({timestamp:t})=>e(t);return{start:(e=!0)=>G.update(t,e),stop:()=>os(t),now:()=>R.isProcessing?R.timestamp:z.now()}},ls=(e,t,n=10)=>{let r=``,i=Math.max(Math.round(t/n),2);for(let t=0;t<i;t++)r+=Math.round(e(t/(i-1))*1e4)/1e4+`, `;return`linear(${r.substring(0,r.length-2)})`},us=2e4;function ds(e,t=50,n=us,r){let i=0,a=e.next(i);for(r?.push(a.value);!a.done&&i<n;)i+=t,a=e.next(i),r?.push(a.value);return i>=n?1/0:i}function fs(e,t=100,n){let{keyframes:r,velocity:i}=e,a=r&&r[r.length-1]-r[0],o=n({...e,velocity:i&&a?i*t/a:i,keyframes:[0,t]}),s=Math.min(ds(o),us);return{type:`keyframes`,ease:e=>o.next(s*e).value/t,duration:L(s)}}var K={stiffness:100,damping:10,mass:1,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05},ps=e=>e<0?1/Math.max(1+e,K.minDamping):Math.max(1-e,K.minDamping);function ms(e,t){if(!(e>1))return 1;let n=Math.sqrt(e*e-1),r=e-n,i=e+n,a=2*n*Math.exp(-t)*(1+t);return _s(e=>i*Math.exp(-r*e)-r*Math.exp(-i*e)-a,e=>Math.exp(-i*e)-Math.exp(-r*e),t)/t}function hs(e,t){return e*Math.sqrt(1-t*t)}var gs=12;function _s(e,t,n){let r=n;for(let n=1;n<gs;n++)r-=e(r)/t(r);return r}var vs=.001;function ys({duration:e=K.duration,bounce:t=K.bounce}){let n,r;K.maxDuration;let i=ps(t);e=N(K.minDuration,K.maxDuration,L(e)),i<1?(n=t=>{let n=t*i,r=n*e,a=hs(t,i),o=Math.exp(-r);return vs-n/a*o},r=t=>{let r=t*i*e,a=i*i*t*t*e,o=Math.exp(-r),s=hs(t*t,i);return(-n(t)+vs>0?-1:1)*-a*o/s}):(n=t=>-.001+Math.exp(-t*e)*(t*e+1),r=t=>Math.exp(-t*e)*(-t*(e*e)));let a=5/e,o=_s(n,r,a),s=o*ms(i,o*e),c=s*s;return{stiffness:c,damping:i*2*Math.sqrt(c),duration:I(e)}}var bs=(e,t)=>(t?e>=0:e>0)&&e<1/0;function xs(e,t){if(bs(e,t))return e}function Ss(e){let t=xs(e.stiffness),n=xs(e.damping,!0),r=xs(e.mass),i={...e,stiffness:t??K.stiffness,damping:n??K.damping,mass:r??K.mass,isResolvedFromDuration:!1,isTimeDefined:(t??n??r)===void 0&&(e.duration!==void 0||e.bounce!==void 0)};if(i.isTimeDefined){if(e.visualDuration){let t=ps(e.bounce||0),n=2*Math.PI/(e.visualDuration*1.2)*ms(t,2*Math.PI/1.2);i.stiffness=n*n,i.damping=2*t*Math.sqrt(i.stiffness)}else Object.assign(i,ys(i)),i.isResolvedFromDuration=!0;(!bs(i.stiffness)||!bs(i.damping,!0))&&(i.stiffness=K.stiffness,i.damping=K.damping)}return i}function Cs(e=K.visualDuration,t=K.bounce){let n=typeof e==`object`?e:{visualDuration:e,keyframes:[0,1],bounce:t},r=n.keyframes[0],i=n.keyframes[n.keyframes.length-1],a={done:!1,value:r},{stiffness:o,damping:s,mass:c,duration:l,isResolvedFromDuration:u,isTimeDefined:d}=Ss({...n}),f=e=>d?0:-L(e),p=s/(2*Math.sqrt(o*c)),m=L(Math.sqrt(o/c)),h=p*m,g={target:i,delta:i-r,velocity:f(n.velocity||0)||0,restSpeed:0,restDelta:0},_=()=>{let e=Math.abs(g.delta)<5;g.restSpeed=n.restSpeed||(e?K.restSpeed.granular:K.restSpeed.default),g.restDelta=n.restDelta||(e?K.restDelta.granular:K.restDelta.default)};_();let v,y,b;if(p<1){let e=hs(m,p),t={A:0,sinC:0,cosC:0,t:-1,env:0,sin:0,cos:0};b=()=>{t.A=(g.velocity+h*g.delta)/e,t.sinC=h*t.A+g.delta*e,t.cosC=h*g.delta-t.A*e};let n=n=>{n!==t.t&&(t.t=n,t.env=Math.exp(-h*n),t.sin=Math.sin(e*n),t.cos=Math.cos(e*n))};v=e=>(n(e),g.target-t.env*(t.A*t.sin+g.delta*t.cos)),y=e=>(n(e),t.env*(t.sinC*t.sin+t.cosC*t.cos))}else if(p===1){v=e=>g.target-Math.exp(-m*e)*(g.delta+(g.velocity+m*g.delta)*e);let e={C:0};b=()=>{e.C=g.velocity+m*g.delta},y=t=>Math.exp(-m*t)*(m*e.C*t-g.velocity)}else{let e=m*Math.sqrt(p*p-1),t=h-e,n=h+e,r=d?1/0:300/e,i=(e,t)=>Math.exp(t>r?-e*r-h*(t-r):-e*t),a={S:0,F:0};b=()=>{let t=(g.velocity+h*g.delta)/e;a.S=(g.delta+t)/2,a.F=(g.delta-t)/2},v=e=>g.target-a.S*i(t,e)-a.F*i(n,e),y=e=>t*a.S*i(t,e)+n*a.F*i(n,e)}b();let x=u&&l||null,S={calculatedDuration:x,retarget:(e,t)=>{g.target=e[e.length-1],g.delta=g.target-e[0],g.velocity=f(t),n.restSpeed&&n.restDelta||_(),S.calculatedDuration=x,a.done=!1,b()},velocity:e=>I(y(e)),next:e=>{let t=v(e);if(u)a.done=e>=l;else{let n=I(y(e));a.done=Math.abs(n)<=g.restSpeed&&Math.abs(g.target-t)<=g.restDelta}return a.value=a.done?g.target:t,a},toString:()=>{let e=Math.min(ds(S),us),t=ls(t=>S.next(e*t).value,e,30);return e+`ms `+t},toTransition:()=>{}};return S}Cs.applyToOptions=e=>{let t=fs(e,100,Cs);return e.ease=t.ease,e.duration=I(t.duration),e.type=`keyframes`,e};function ws({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:i=10,bounceStiffness:a=500,modifyTarget:o,min:s,max:c,restDelta:l=.5,restSpeed:u}){let d=e[0],f={done:!1,value:d},p=e=>e<s||e>c,m=e=>s===void 0?c:c===void 0||Math.abs(s-e)<Math.abs(c-e)?s:c,h=n*t,g=d+h,_=o===void 0?g:o(g);_!==g&&(h=_-d);let v=e=>-h*Math.exp(-e/r),y=e=>{let t=v(e);f.done=Math.abs(t)<=l,f.value=f.done?_:_+t},b,x,S=e=>{p(f.value)&&(b=e,x=Cs({keyframes:[f.value,m(f.value)],velocity:-v(e)/r*1e3,damping:i,stiffness:a,restDelta:l,restSpeed:u}))};return S(0),{calculatedDuration:null,next:e=>{let t=!1;return!x&&b===void 0&&(t=!0,y(e),S(e)),b!==void 0&&e>=b?x.next(e-b):(!t&&y(e),f)}}}function Ts(e,t,n){let r=[],i=n||P.mix||ts,a=e.length-1;for(let n=0;n<a;n++){let a=i(e[n],e[n+1]);t&&(a=xa(Array.isArray(t)?t[n]||F:t,a)),r.push(a)}return r}function Es(e,t,{clamp:n=!0,ease:r,mixer:i}={}){let a=e.length;if(t.length,a===1)return()=>t[0];if(a===2&&t[0]===t[1])return()=>t[1];let o=e[0]===e[1];e[0]>e[a-1]&&(e=[...e].reverse(),t=[...t].reverse());let s=Ts(t,r,i),c=s.length,l=n=>{if(o&&n<e[0])return t[0];let r=0;if(c>1)for(;r<e.length-2&&!(n<e[r+1]);r++);let i=Sa(e[r],e[r+1],n);return s[r](i)};return n?t=>l(N(e[0],e[a-1],t)):l}function Ds(e,t){let n=e[e.length-1];for(let r=1;r<=t;r++){let i=Sa(0,t,r);e.push(W(n,1,i))}}function Os(e){let t=[0];return Ds(t,e.length-1),t}function ks(e,t){return e.map(e=>e*t)}function As(e,t){return e.map(()=>t||Ra).splice(0,e.length-1)}function js({duration:e=300,keyframes:t,times:n,ease:r=`easeInOut`}){let i=za(r)?r.map(Ua):Ua(r)||Ra,a={done:!1,value:t[0]};if(t.length===2&&!Array.isArray(i)&&(!n||n.length!==2||n[0]===0&&n[1]===1)){let[n,r]=t,o=n===r?void 0:(P.mix||ts)(n,r);return{calculatedDuration:e,next:t=>(a.value=o?o(i(e>0?N(0,1,t/e):1)):r,a.done=t>=e,a)}}let o=Es(ks(n&&n.length===t.length?n:Os(t),e),t,{ease:Array.isArray(i)?i:As(t,i)});return{calculatedDuration:e,next:t=>(a.value=o(t),a.done=t>=e,a)}}var Ms=5;function Ns(e,t,n){let r=Math.max(t-Ms,0);return wa(n-e(r),t-r)}function Ps(e,t,n=0){return t<=0?n:e.velocity?e.velocity(t):Ns(t=>e.next(t).value,t,e.next(t).value)}var Fs=e=>e!==null;function Is(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(Fs),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}var Ls={decay:ws,inertia:ws,tween:js,keyframes:js,spring:Cs};function Rs(e){typeof e.type==`string`&&(e.type=Ls[e.type])}var zs=40,Bs=(e,t)=>t-e>zs&&!P.useManualTiming?t:e;function Vs(e,t){return{kind:e,animation:t,timestamp:z.now(),frameTimestamp:R.timestamp,frameIsProcessing:R.isProcessing}}function Hs(e,t,n){let r=globalThis.__MOTION_INSPECT__;if(r)try{r({...Vs(`animation-start`,e),options:n?{...t,...n}:t})}catch{}}function Us(e,t){let n=globalThis.__MOTION_INSPECT__;if(n)try{n({...Vs(`layout-animation-start`,e),node:t})}catch{}}var Ws=class{constructor(){this.isResolved=!1}get finished(){return this._finished||=this.isResolved?Promise.resolve():new Promise(e=>{this._resolve=e}),this._finished}updateFinished(){this._finished=this._resolve=void 0,this.isResolved=!1}notifyFinished(){this.isResolved=!0,this._resolve?.()}then(e,t){return this.finished.then(e,t)}},Gs=e=>e/100,Ks=class extends Ws{constructor(e){super(),this.state=`idle`,this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{let{motionValue:e}=this.options;e&&e.updatedAt!==z.now()&&this.tick(z.now()),this.isStopped=!0,this.state!==`idle`&&(this.teardown(),this.options.onStop?.())},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause(),Hs(this,this.options)}initAnimation(){let{options:e}=this;Rs(e);let{type:t=js,repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:a=0}=e,{keyframes:o}=e,s=t||js;s!==js&&typeof o[0]!=`number`&&(this.mixKeyframes=xa(Gs,ts(o[0],o[1])),o=[0,100]);let c=s(o===e.keyframes?e:{...e,keyframes:o});i===`mirror`&&(this.mirroredGenerator=s({...e,keyframes:[...o].reverse(),velocity:-a})),c.calculatedDuration===null&&(c.calculatedDuration=ds(c));let{calculatedDuration:l}=c;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(n+1)-r,this.generator=c}updateTime(e){let t=Math.round(e-this.startTime)*this.playbackSpeed;this.currentTime=this.holdTime===null?t:this.holdTime}tick(e,t=!1){let{generator:n,totalDuration:r,mixKeyframes:i,mirroredGenerator:a,resolvedDuration:o,calculatedDuration:s}=this;if(this.startTime===null)return n.next(0);let{delay:c=0,keyframes:l,repeat:u,repeatType:d,repeatDelay:f,type:p,onUpdate:m,finalKeyframe:h}=this.options;this.startTime===this.pendingStartTime&&(this.startTime=Bs(this.startTime,e)),this.pendingStartTime=void 0,this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),t?this.currentTime=e:this.updateTime(e);let g=this.currentTime-c*(this.playbackSpeed>=0?1:-1),_=this.playbackSpeed>=0?g<0:g>r;this.currentTime=Math.max(g,0),this.state===`finished`&&this.holdTime===null&&(this.currentTime=r);let v=this.currentTime,y=n;if(u){let e=Math.min(this.currentTime,r)/o,t=Math.floor(e),n=e%1;!n&&e>=1&&(n=1),n===1&&t--,t=Math.min(t,u+1),t%2&&(d===`reverse`?(n=1-n,f&&(n-=f/o)):d===`mirror`&&(y=a)),v=N(0,1,n)*o}let b;_?(this.delayState.value=l[0],b=this.delayState):b=y.next(v),i&&!_&&(b.value=i(b.value));let{done:x}=b;!_&&s!==null&&(x=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);let S=this.holdTime===null&&(this.state===`finished`||this.state===`running`&&x);return S&&p!==ws&&(b.value=Is(l,this.options,h,this.speed)),m&&m(b.value),S&&this.finish(),b}then(e,t){return this.finished.then(e,t)}get duration(){return L(this.calculatedDuration)}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+L(e)}get time(){return L(this.currentTime)}set time(e){e=I(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state=`paused`,this.holdTime=e,this.tick(e))}getGeneratorVelocity(){return Ps(this.generator,this.currentTime,this.options.velocity)}get speed(){return this.playbackSpeed}set speed(e){let t=this.playbackSpeed!==e;t&&this.driver&&this.updateTime(z.now()),this.playbackSpeed=e,t&&this.driver&&(this.time=L(this.currentTime))}play(){if(this.isStopped)return;let{driver:e=cs,startTime:t}=this.options;this.driver||=e(e=>this.tick(e)),this.options.onPlay?.();let n=this.driver.now();this.state===`finished`?(this.updateFinished(),this.startTime=n):this.holdTime===null?this.startTime||=t??(this.pendingStartTime=n):this.startTime=n-this.holdTime/(this.playbackSpeed||1),this.state===`finished`&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state=`running`,this.driver.start()}pause(){this.state=`paused`,this.updateTime(z.now()),this.holdTime=this.currentTime}complete(){this.state!==`running`&&this.play(),this.state=`finished`,this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state=`finished`,this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state=`idle`,this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&=(this.driver.stop(),void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type=`keyframes`,this.options.ease=`linear`,this.initAnimation()),this.driver?.stop(),e.observe(this)}},qs=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function Js(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(no)||[];if(!r)return e;let i=n.replace(r,``),a=+!!qs.has(t);return r!==n&&(a*=100),t+`(`+a+i+`)`}var Ys=/\b([a-z-]*)\(.*?\)/gu,Xs={...U,getAnimatableNone:e=>{let t=e.match(Ys);return t?t.map(Js).join(` `):e}},Zs={...U,getAnimatableNone:e=>{let t=U.parse(e);return U.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},Qs={...$a,transform:Math.round},$s={rotate:mo,pathRotation:mo,rotateX:mo,rotateY:mo,rotateZ:mo,scale:to,scaleX:to,scaleY:to,scaleZ:to,skew:mo,skewX:mo,skewY:mo,distance:V,translateX:V,translateY:V,translateZ:V,x:V,y:V,z:V,perspective:V,transformPerspective:V,opacity:eo,originX:_o,originY:_o,originZ:V},ec={borderWidth:V,borderTopWidth:V,borderRightWidth:V,borderBottomWidth:V,borderLeftWidth:V,borderRadius:V,borderTopLeftRadius:V,borderTopRightRadius:V,borderBottomRightRadius:V,borderBottomLeftRadius:V,width:V,maxWidth:V,height:V,maxHeight:V,top:V,right:V,bottom:V,left:V,inset:V,insetBlock:V,insetBlockStart:V,insetBlockEnd:V,insetInline:V,insetInlineStart:V,insetInlineEnd:V,padding:V,paddingTop:V,paddingRight:V,paddingBottom:V,paddingLeft:V,paddingBlock:V,paddingBlockStart:V,paddingBlockEnd:V,paddingInline:V,paddingInlineStart:V,paddingInlineEnd:V,margin:V,marginTop:V,marginRight:V,marginBottom:V,marginLeft:V,marginBlock:V,marginBlockStart:V,marginBlockEnd:V,marginInline:V,marginInlineStart:V,marginInlineEnd:V,fontSize:V,backgroundPositionX:V,backgroundPositionY:V,...$s,zIndex:Qs,fillOpacity:eo,strokeOpacity:eo,numOctaves:Qs},tc={...ec,color:H,backgroundColor:H,outlineColor:H,fill:H,stroke:H,borderColor:H,borderTopColor:H,borderRightColor:H,borderBottomColor:H,borderLeftColor:H,filter:Xs,WebkitFilter:Xs,mask:Zs,WebkitMask:Zs},nc=e=>tc[e],rc=new Set([Xs,Zs]);function ic(e,t){let n=nc(e);return rc.has(n)||(n=U),n.getAnimatableNone?n.getAnimatableNone(t):void 0}function ac(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var oc=e=>e*180/Math.PI,sc=e=>lc(oc(Math.atan2(e[1],e[0]))),cc={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:sc,rotateZ:sc,skewX:e=>oc(Math.atan(e[1])),skewY:e=>oc(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},lc=e=>(e%=360,e<0&&(e+=360),e),uc=sc,dc=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),fc=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),pc={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:dc,scaleY:fc,scale:e=>(dc(e)+fc(e))/2,rotateX:e=>lc(oc(Math.atan2(e[6],e[5]))),rotateY:e=>lc(oc(Math.atan2(-e[2],e[0]))),rotateZ:uc,rotate:uc,skewX:e=>oc(Math.atan(e[4])),skewY:e=>oc(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function mc(e){return+!!e.includes(`scale`)}function hc(e,t){if(!e||e===`none`)return mc(t);let n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u),r,i;if(n)r=pc,i=n;else{let t=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=cc,i=t}if(!i)return mc(t);let a=r[t],o=i[1].split(`,`).map(_c);return typeof a==`function`?a(o):o[a]}var gc=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return hc(n,t)};function _c(e){return parseFloat(e.trim())}var vc=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],yc=new Set([...vc,`pathRotation`]),bc=e=>e===$a||e===V,xc=new Set([`x`,`y`,`z`]),Sc=vc.filter(e=>!xc.has(e));function Cc(e){let t=[];return Sc.forEach(n=>{let r=e.getValue(n);if(r!==void 0){let e=r.get(),i=+!!n.startsWith(`scale`);if(e===i)return;t.push([n,e]),r.set(i)}}),t}var wc=new Set([`bottom`,`right`]);function Tc(e,t,n,r,i,a){let o=parseFloat(e);if(!isNaN(o))return o;let{min:s,max:c}=t()[n],l=c-s;return a===`border-box`?l:l-parseFloat(r)-parseFloat(i)}var Ec={width:({width:e,paddingLeft:t=`0`,paddingRight:n=`0`,boxSizing:r},i)=>Tc(e,i,`x`,t,n,r),height:({height:e,paddingTop:t=`0`,paddingBottom:n=`0`,boxSizing:r},i)=>Tc(e,i,`y`,t,n,r),top:({top:e})=>parseFloat(e),left:({left:e})=>parseFloat(e),bottom:({top:e},t)=>{let{y:n}=t();return parseFloat(e)+(n.max-n.min)},right:({left:e},t)=>{let{x:n}=t();return parseFloat(e)+(n.max-n.min)},x:({transform:e})=>hc(e,`x`),y:({transform:e})=>hc(e,`y`)};Ec.translateX=Ec.x,Ec.translateY=Ec.y;var Dc=new Set,Oc=!1,kc=!1,Ac=!1;function jc(){if(kc){let e=[],t=new Set,n=new Set;Dc.forEach(r=>{r.needsMeasurement&&(e.push(r),t.add(r.element),wc.has(r.name)&&n.add(r.element))});let r=new Map;n.forEach(e=>{let t=Cc(e);t.length&&(r.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();let t=r.get(e);t&&t.forEach(([t,n])=>{e.getValue(t)?.set(n)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{e.suspendedScrollY!==void 0&&window.scrollTo(0,e.suspendedScrollY)})}kc=!1,Oc=!1,Dc.forEach(e=>e.complete(Ac)),Dc.clear()}function Mc(){Dc.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(kc=!0)})}function Nc(){Ac=!0,Mc(),jc(),Ac=!1}function Pc(e,t,n){if(typeof e==`string`){if(_a(e)||ya(e))return parseFloat(e);if(!U.test(e)&&U.test(n))return ic(t,n)}return e??void 0}var Fc=class{constructor(e,t,n,r,i,a=!1){this.state=`pending`,this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=n,this.motionValue=r,this.element=i,this.isAsync=a}scheduleResolve(){this.state=`scheduled`,this.isAsync?(Dc.add(this),Oc||(Oc=!0,G.read(Mc),G.resolveKeyframes(jc))):(this.readKeyframes(),this.complete())}readKeyframes(){let{unresolvedKeyframes:e,name:t,element:n,motionValue:r}=this;if(e[0]===null){let i=r?.get(),a=e[e.length-1];if(i!==void 0)e[0]=i;else if(n&&t){let r=Pc(n.readValue(t,a),t,a);r!==void 0&&(e[0]=r)}e[0]===void 0&&(e[0]=a),r&&i===void 0&&r.set(e[0])}ac(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state=`complete`,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Dc.delete(this)}cancel(){this.state===`scheduled`&&(Dc.delete(this),this.state=`pending`)}resume(){this.state===`pending`&&this.scheduleResolve()}},Ic=e=>e.startsWith(`--`);function Lc(e,t,n){Ic(t)?e.style.setProperty(t,n):e.style[t]=n}var Rc={};function zc(e,t){let n=ba(e);return()=>Rc[t]??n()}var Bc=zc(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),Vc=zc(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),Hc=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,Uc={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:Hc([0,.65,.55,1]),circOut:Hc([.55,0,1,.45]),backIn:Hc([.31,.01,.66,-.59]),backOut:Hc([.33,1.53,.69,.99])};function Wc(e,t){if(e)return typeof e==`function`?Vc()?ls(e,t):`ease-out`:Ba(e)?Hc(e):Array.isArray(e)?e.map(e=>Wc(e,t)||Uc.easeOut):Uc[e]}function Gc(e,t,n,{delay:r=0,duration:i=300,repeat:a=0,repeatType:o=`loop`,ease:s=`easeOut`,times:c}={},l=void 0){let u={[t]:n};c&&(u.offset=c);let d=Wc(s,i);Array.isArray(d)&&(u.easing=d);let f={delay:r,duration:i,easing:Array.isArray(d)?`linear`:d,fill:`both`,iterations:a+1,direction:o===`reverse`?`alternate`:`normal`};return l&&(f.pseudoElement=l),e.animate(u,f)}function Kc(e){return typeof e==`function`&&`applyToOptions`in e}function qc({type:e,...t}){return Kc(e)&&Vc()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var Jc=class extends Ws{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;let{element:t,name:n,keyframes:r,pseudoElement:i,allowFlatten:a=!1,finalKeyframe:o,onComplete:s}=e;this.isPseudoElement=!!i,this.allowFlatten=a,this.options=e,e.type;let c=qc(e);this.animation=Gc(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=Is(r,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(e),Lc(t,n,e),this.animation.cancel()}s?.(),this.notifyFinished()},Hs(this,e,c)}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state===`finished`&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;let{state:e}=this;e!==`idle`&&e!==`finished`&&(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){let e=this.options?.element;!this.isPseudoElement&&e?.isConnected&&this.animation.commitStyles?.()}get duration(){let e=this.animation.effect?.getComputedTiming?.().duration||0;return L(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+L(e)}get time(){return L(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=I(e),t&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime===null?this.animation.playState:`finished`}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,onAttach:t,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:`linear`}),this.animation.onfinish=null,e&&Bc()?(this.animation.timeline=e,t?.(this.animation),F):n(this)}},Yc={anticipate:Ma,backInOut:ja,circInOut:Fa};function Xc(e){return e in Yc}function Zc(e){typeof e.ease==`string`&&Xc(e.ease)&&(e.ease=Yc[e.ease])}var Qc=10,$c=class extends Jc{constructor(e){Zc(e),Rs(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){let{motionValue:t,onUpdate:n,onComplete:r,element:i,...a}=this.options;if(!t)return;if(e!==void 0){t.set(e);return}let o=new Ks({...a,autoplay:!1}),s=Math.max(Qc,z.now()-this.startTime),c=N(0,Qc,s-Qc),l=o.sample(s).value,{name:u}=this.options;i&&u&&Lc(i,u,l),t.setWithVelocity(o.sample(Math.max(0,s-c)).value,l,c),o.stop()}},el=(e,t)=>t!==`zIndex`&&!!(typeof e==`number`||Array.isArray(e)||typeof e==`string`&&(U.test(e)||e===`0`)&&!e.startsWith(`url(`));function tl(e){let t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function nl(e,t,n,r){let i=e[0];if(i===null)return!1;if(t===`display`||t===`visibility`)return!0;let a=e[e.length-1],o=el(i,t),s=el(a,t);return!o||!s?(o!==s&&`${t}${i}${a}${o?a:i}`,!1):tl(e)||(n===`spring`||Kc(n))&&r}function rl(e){e.duration=0,e.type=`keyframes`}var il=new Set([`opacity`,`clipPath`,`filter`,`transform`,`backgroundColor`]),al=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function ol(e){for(let t=0;t<e.length;t++)if(typeof e[t]==`string`&&al.test(e[t]))return!0;return!1}var sl=new Set([`color`,`backgroundColor`,`outlineColor`,`fill`,`stroke`,`borderColor`,`borderTopColor`,`borderRightColor`,`borderBottomColor`,`borderLeftColor`]),cl=ba(()=>Object.hasOwnProperty.call(Element.prototype,`animate`));function ll(e){let{motionValue:t,name:n,repeatDelay:r,repeatType:i,damping:a,type:o,keyframes:s}=e;if(!n||!(il.has(n)||sl.has(n)))return!1;let c=t?.owner?.current;if(!(c instanceof HTMLElement)&&!(c instanceof SVGElement))return!1;let{onUpdate:l,transformTemplate:u}=t.owner.getProps();return cl()&&(il.has(n)||sl.has(n)&&ol(s))&&(n!==`transform`||!u)&&!l&&!r&&i!==`mirror`&&a!==0&&o!==`inertia`}var ul=class extends Ws{constructor(e){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=z.now();let{keyframes:t,name:n,motionValue:r,element:i}=e,a=e;a.autoplay??=!0,a.delay??=0,a.type??=`keyframes`,a.repeat??=0,a.repeatDelay??=0,a.repeatType??=`loop`;let o=i?.KeyframeResolver||Fc;this.keyframeResolver=new o(t,(e,t,n)=>this.onKeyframesResolved(e,t,a,!n),n,r,i),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,t,n,r){this.keyframeResolver=void 0;let{name:i,type:a,velocity:o,delay:s,isHandoff:c,onUpdate:l}=n;this.resolvedAt=z.now();let u=!0;nl(e,i,a,o)||(u=!1,(P.instantAnimations||!s)&&l?.(Is(e,n,t)),e[0]=e[e.length-1],rl(n),n.repeat=0);let{onComplete:d}=n;n.finalKeyframe=t,n.keyframes=e,n.onComplete=()=>{d?.(),this.notifyFinished()};let f=u&&!c&&ll(n);r&&(f||this.resolvedAt!==this.createdAt)&&(n.startTime??=Bs(this.createdAt,this.resolvedAt));let p;if(f){n.element=n.motionValue?.owner?.current;try{p=new $c(n)}catch{p=new Ks(n)}}else p=new Ks(n);this.pendingTimeline&&=(this.stopTimeline=p.attachTimeline(this.pendingTimeline),void 0),this._animation=p}get finished(){return this._animation?this._animation.finished:super.finished}then(e,t){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Nc()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}};function dl(e,t,n,r=0,i=1){let a=Array.from(e).sort((e,t)=>e.sortNodePosition(t)).indexOf(t),o=e.size,s=(o-1)*r;return typeof n==`function`?n(a,o):i===1?a*r:s-a*r}var fl=30,pl=e=>!isNaN(parseFloat(e)),ml={current:void 0},hl=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=z.now();if(this.updatedAt!==t&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&(this.notifyChange(),this.dependents))for(let e of this.dependents)e.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=z.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=pl(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on(`change`,e)}on(e,t){var n;return e===`change`?this.onChangeSubscribe(t):((n=this.events)[e]||(n[e]=new Ca)).add(t)}onChangeSubscribe(e){let{events:t}=this;return!t.change&&!this.changeSubscriber?this.changeSubscriber=e:(t.change||(t.change=new Ca,t.change.add(this.changeSubscriber),this.changeSubscriber=void 0),t.change.add(e)),()=>{this.changeSubscriber===e?this.changeSubscriber=void 0:t.change?.remove(e),this.stopIfUnobserved()}}stopIfUnobserved(){G.read(()=>{!this.changeSubscriber&&!this.events.change?.getSize()&&this.stop()})}clearListeners(){this.changeSubscriber=void 0;for(let e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,t,n){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.notifyChange()}notifyChange(){let{current:e,changeSubscriber:t}=this;t?t(e):this.events.change?.notify(e)}addDependent(e){this.dependents||=new Set,this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return ml.current&&ml.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){let e=z.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>fl)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,fl);return wa(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0;let n=!1,r;r=e(()=>{n=!0,this.events.animationComplete?.notify(),this.animation===r&&this.clearAnimation(),t()}),n||(this.animation=r),this.events.animationStart?.notify()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){this.animation=void 0}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}};function gl(e,t){return new hl(e,t)}function _l(e,t){if(e?.inherit&&t){let{inherit:n,...r}=e;return{...t,...r}}return e}function vl(e,t){let n=e?.[t]??e?.default??e;return n===e?n:_l(n,e)}var yl={type:`spring`,stiffness:500,damping:25,restSpeed:10},bl=e=>({type:`spring`,stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),xl={type:`keyframes`,duration:.8},Sl={type:`keyframes`,ease:[.25,.1,.35,1],duration:.3},Cl=(e,{keyframes:t})=>t.length>2?xl:yc.has(e)?e.startsWith(`scale`)?bl(t[1]):yl:Sl,wl=new Set([`when`,`delay`,`delayChildren`,`staggerChildren`,`staggerDirection`,`repeat`,`repeatType`,`repeatDelay`,`from`,`elapsed`]);function Tl(e){for(let t in e)if(!wl.has(t))return!0;return!1}var El=(e,t,n,r={},i,a)=>o=>{let s=vl(r,e)||{},c=s.delay||r.delay||0,{elapsed:l=0}=r;l-=I(c);let u={keyframes:Array.isArray(n)?n:[null,n],ease:`easeOut`,velocity:t.getVelocity(),...s,delay:-l,onUpdate:e=>{t.set(e),s.onUpdate&&s.onUpdate(e)},onComplete:()=>{o(),s.onComplete&&s.onComplete()},name:e,motionValue:t,element:a?void 0:i};Tl(s)||Object.assign(u,Cl(e,u)),u.duration&&=I(u.duration),u.repeatDelay&&=I(u.repeatDelay),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(rl(u),u.delay===0&&(d=!0)),(P.instantAnimations||P.skipAnimations||i?.shouldSkipAnimations||s.skipAnimations)&&(d=!0,rl(u),u.delay=0),u.allowFlatten=!s.type&&!s.ease,d&&!a&&t.get()!==void 0){let e=Is(u.keyframes,s);if(e!==void 0){G.update(()=>{u.onUpdate(e),u.onComplete()});return}}return s.isSync?new Ks(u):new ul(u)},Dl=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Ol(e){let t=Dl.exec(e);if(!t)return[,];let[,n,r,i]=t;return[`--${n??r}`,i]}function kl(e,t,n=1){`${e}`;let[r,i]=Ol(e);if(!r)return;let a=window.getComputedStyle(t).getPropertyValue(r);if(a){let e=a.trim();return _a(e)?parseFloat(e):e}return Xa(i)?kl(i,t,n+1):i}function Al(e){let t=[{},{}];return e?.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function jl(e,t,n,r){let i=t=>typeof t==`function`?t(n===void 0?e.custom:n,...Al(r)):t;return t=i(t),typeof t==`string`&&(t=e.variants&&e.variants[t]),i(t)}function Ml(e,t,n){return jl(e.getProps(),t,n,e)}var Nl=(e,t)=>t===`exit`?e.presenceContext?.custom:void 0,Pl=new Set([`width`,`height`,`top`,`left`,`right`,`bottom`,...vc]),Fl=e=>Array.isArray(e);function Il(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,gl(n))}function Ll(e){return Fl(e)?e[e.length-1]||0:e}function Rl(e,t){let{transitionEnd:n={},transition:r={},...i}=Ml(e,t)||{};i={...i,...n};for(let t in i)Il(e,t,Ll(i[t]))}var q=e=>!!(e&&e.getVelocity);function zl(e){return!!(q(e)&&e.add)}function Bl(e,t){let n=e.getValue(`willChange`);if(zl(n))return n.add(t);if(!n&&P.WillChange){let n=new P.WillChange(`auto`);e.addValue(`willChange`,n),n.add(t)}}function Vl(e){return e.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}var Hl=`data-`+Vl(`framerAppearId`);function Ul(e){return e.props[Hl]}var Wl=typeof window<`u`;function Gl({protectedKeys:e,needsAnimating:t},n){let r=n in e&&!t[n];return t[n]=!1,r}function Kl(e,t,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:a,transitionEnd:o,...s}=t,c=e.getDefaultTransition();a=a?_l(a,c):c;let l=a?.reduceMotion,u=a?.skipAnimations;r&&(a=r);let d=[],f=i&&e.animationState?.getState()[i],p=a?.path;p&&p.animateVisualElement(e,s,a,n,d);for(let t in s){let r=e.getValue(t,e.latestValues[t]??null),i=s[t];if(i===void 0||f&&Gl(f,t))continue;let o={delay:n,...vl(a||{},t)};u&&(o.skipAnimations=!0);let c=r.get();if(c!==void 0&&!r.isAnimating()&&!Array.isArray(i)&&i===c&&!o.velocity){G.update(()=>r.set(i));continue}let p=!1;if(Wl&&window.MotionHandoffAnimation){let n=Ul(e);if(n){let e=window.MotionHandoffAnimation(n,t,G);e!==null&&(o.startTime=e,p=!0)}}Bl(e,t);let m=l??e.shouldReduceMotion;r.start(El(t,r,i,m&&Pl.has(t)?{type:!1}:o,e,p));let h=r.animation;h&&d.push(h)}if(o){let t=()=>G.update(()=>{o&&Rl(e,o)});d.length?Promise.all(d).then(t):t()}return d}function ql(e,t,n={}){let r=Ml(e,t,Nl(e,n.type)),i=n.transitionOverride||(r?.transition??(e.getDefaultTransition()||{})),a=()=>Promise.all(r?Kl(e,r,n):[]),o=(r=0)=>{let{variantChildren:a}=e,{delayChildren:o=0,staggerChildren:s,staggerDirection:c}=i,l=[];return a?.forEach(e=>{e.notify(`AnimationStart`,t),l.push(ql(e,t,{...n,delay:r+(typeof o==`function`?0:o)+dl(a,e,o,s,c)}).then(()=>e.notify(`AnimationComplete`,t)))}),Promise.all(l)},{when:s}=i;return s?s===`beforeChildren`?a().then(()=>o()):o().then(a):Promise.all([a(),o(n.delay)])}function Jl(e,t,n={}){return e.notify(`AnimationStart`,t),(Array.isArray(t)?Promise.all(t.map(t=>ql(e,t,n))):typeof t==`string`?ql(e,t,n):Promise.all(Kl(e,Ml(e,t,n.custom),n))).then(()=>{e.notify(`AnimationComplete`,t)})}var Yl={test:e=>e===`auto`,parse:e=>e},Xl=e=>t=>t.test(e),Zl=[$a,V,B,mo,go,ho,Yl],Ql=e=>Zl.find(Xl(e));function $l(e){return typeof e==`number`?e===0:e===null||e===`none`||e===`0`||ya(e)}var eu=new Set([`auto`,`none`,`0`]);function tu(e,t,n){let r=0,i;for(;r<e.length&&!i;){let t=e[r];typeof t==`string`&&!eu.has(t)&&ko(t)&&(i=e[r]),r++}if(i&&n)for(let r of t)e[r]!==i&&(e[r]=ic(n,i))}var nu=class extends Fc{constructor(e,t,n,r,i){super(e,t,n,r,i,!0)}readKeyframes(){let{unresolvedKeyframes:e,element:t,name:n}=this;if(!t||!t.current)return;super.readKeyframes();for(let n=0;n<e.length;n++){let r=e[n];if(typeof r==`string`&&(r=r.trim(),Xa(r))){let i=kl(r,t.current);i!==void 0&&(e[n]=i),n===e.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!Pl.has(n)||e.length!==2)return;let[r,i]=e;if(typeof r==`number`&&typeof i==`number`)return;let a=Ql(r),o=Ql(i);if(Qa(r)!==Qa(i)&&Ec[n])this.needsMeasurement=!0;else if(a!==o){if(bc(a)&&bc(o))for(let t=0;t<e.length;t++){let n=e[t];typeof n==`string`&&(e[t]=parseFloat(n))}else Ec[n]&&(this.needsMeasurement=!0)}}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,n=[];for(let t=0;t<e.length;t++)(e[t]===null||$l(e[t]))&&n.push(t);n.length&&tu(e,n,t)}measure(){let{element:e,name:t}=this;return Ec[t](window.getComputedStyle(e.current),()=>e.measureViewportBox())}measureInitialState(){let{element:e,unresolvedKeyframes:t,name:n}=this;if(!e||!e.current)return;n===`height`&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=this.measure(),t[0]=this.measuredOrigin;let r=t[t.length-1];r!==void 0&&this.motionValue?.jump(r,!1)}measureEndState(){let{element:e,unresolvedKeyframes:t}=this;if(!e||!e.current)return;this.motionValue?.jump(this.measuredOrigin,!1);let n=t.length-1,r=t[n];t[n]=this.measure(),r!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=r),this.removedTransforms?.length&&this.removedTransforms.forEach(([t,n])=>{e.getValue(t).set(n)}),this.resolveNoneKeyframes()}},ru=[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomRightRadius`,`borderBottomLeftRadius`];function iu(e){return va(e)&&`offsetHeight`in e&&!(`ownerSVGElement`in e)}function au(e){return va(e)&&`ownerSVGElement`in e}var ou=(e,t)=>t&&typeof e==`number`?t.transform(e):e;function su(e,t,n){if(e==null)return[];if(e instanceof EventTarget)return[e];if(typeof e==`string`){let r=document;t&&(r=t.current);let i=n?.[e]??r.querySelectorAll(e);return i?Array.from(i):[]}return Array.from(e).filter(e=>e!=null)}var cu={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},lu=vc.length;function uu(e,t,n){let r=``,i=!0;for(let a=0;a<lu;a++){let o=vc[a],s=e[o];if(s===void 0)continue;let c=!0;if(typeof s==`number`)c=s===+!!o.startsWith(`scale`);else{let e=parseFloat(s);c=o.startsWith(`scale`)?e===1:e===0}if(!c||n){let e=ou(s,ec[o]);if(!c){i=!1;let t=cu[o]||o;r+=`${t}(${e}) `}n&&(t[o]=e)}}let a=e.pathRotation;return a&&(i=!1,r+=`rotate(${ou(a,ec.pathRotation)}) `),r=r.trim(),n?r=n(t,i?``:r):i&&(r=`none`),r}function du(e,t,n){let{style:r,vars:i,transformOrigin:a}=e,o=!1,s=!1;for(let e in t){let n=t[e];if(yc.has(e))o=!0;else if(Ja(e))i[e]=n;else{let t=ou(n,ec[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=uu(t,e.transform,n):r.transform&&=`none`),s){let{originX:e=`50%`,originY:t=`50%`,originZ:n=0}=a;r.transformOrigin=`${e} ${t} ${n}`}}var fu={offset:`stroke-dashoffset`,array:`stroke-dasharray`},pu={offset:`strokeDashoffset`,array:`strokeDasharray`};function mu(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?fu:pu;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var hu=[`transform`,`opacity`,`clipPath`,`filter`,`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function gu(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(du(e,s,l),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};let{attrs:d,style:f}=e;for(let e of hu)d[e]!==void 0&&(f[e]=d[e],delete d[e]);(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??`50% 50%`,delete d.transformOrigin),f.transform&&(f.transformBox=u?.transformBox??`fill-box`,delete d.transformBox),t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),r!==void 0&&(d.scale=r),i!==void 0&&mu(d,i,a,o,!1)}function _u({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function vu({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function yu(e,t){if(!t)return e;let n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function bu(e){return e===void 0||e===1}function xu({scale:e,scaleX:t,scaleY:n}){return!bu(e)||!bu(t)||!bu(n)}function Su(e){return xu(e)||Cu(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Cu(e){return wu(e.x)||wu(e.y)}function wu(e){return e&&e!==`0%`}function Tu(e,t,n){return n+t*(e-n)}function Eu(e,t,n,r,i){return i!==void 0&&(e=Tu(e,i,r)),Tu(e,n,r)+t}function Du(e,t=0,n=1,r,i){e.min=Eu(e.min,t,n,r,i),e.max=Eu(e.max,t,n,r,i)}function Ou(e,{x:t,y:n}){Du(e.x,t.translate,t.scale,t.originPoint),Du(e.y,n.translate,n.scale,n.originPoint)}var ku=.999999999999,Au=1.0000000000001;function ju(e,t,n,r=!1){let i=n.length;if(!i)return;t.x=t.y=1;let a,o;for(let s=0;s<i;s++){a=n[s],o=a.projectionDelta;let{visualElement:i}=a.options;i&&i.props.style&&i.props.style.display===`contents`||(r&&a.options.layoutScroll&&a.scroll&&a!==a.root&&(J(e.x,-a.scroll.offset.x),J(e.y,-a.scroll.offset.y)),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Ou(e,o)),r&&Su(a.latestValues)&&Pu(e,a.latestValues,a.layout?.layoutBox))}t.x<Au&&t.x>ku&&(t.x=1),t.y<Au&&t.y>ku&&(t.y=1)}function J(e,t){e.min+=t,e.max+=t}function Mu(e,t,n,r,i=.5){Du(e,t,n,W(e.min,e.max,i),r)}function Nu(e,t){return typeof e==`string`?parseFloat(e)/100*(t.max-t.min):e}function Pu(e,t,n){let r=n??e;Mu(e.x,Nu(t.x,r.x),t.scaleX,t.scale,t.originX),Mu(e.y,Nu(t.y,r.y),t.scaleY,t.scale,t.originY)}function Fu(e,t){return _u(yu(e.getBoundingClientRect(),t))}function Iu(e,t,n){let r=Fu(e,n),{scroll:i}=t;return i&&(J(r.x,i.offset.x),J(r.y,i.offset.y)),r}var{schedule:Lu,cancel:Ru}=as(queueMicrotask,!1),Y={x:!1,y:!1};function zu(){return Y.x||Y.y}function Bu(e){return e===`x`||e===`y`?Y[e]?null:(Y[e]=!0,()=>{Y[e]=!1}):Y.x||Y.y?null:(Y.x=Y.y=!0,()=>{Y.x=Y.y=!1})}function Vu(e,t){let n=su(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function Hu(e){return!(e.pointerType===`touch`||zu())}function Uu(e,t,n={}){let[r,i,a]=Vu(e,n);return r.forEach(e=>{let n=!1,r=!1,a,o=()=>{e.removeEventListener(`pointerleave`,u)},s=e=>{a&&=(a(e),void 0),o()},c=e=>{n=!1,window.removeEventListener(`pointerup`,c),window.removeEventListener(`pointercancel`,c),r&&(r=!1,s(e))},l=()=>{n=!0,window.addEventListener(`pointerup`,c,i),window.addEventListener(`pointercancel`,c,i)},u=e=>{e.pointerType!==`touch`&&(n?r=!0:s(e))};e.addEventListener(`pointerenter`,n=>{if(!Hu(n))return;r=!1;let o=t(e,n);typeof o==`function`&&(a=o,e.addEventListener(`pointerleave`,u,i))},i),e.addEventListener(`pointerdown`,l,i)}),a}var Wu=(e,t)=>t?e===t||Wu(e,t.parentElement):!1,Gu=e=>e.pointerType===`mouse`?typeof e.button!=`number`||e.button<=0:e.isPrimary!==!1,Ku=new Set([`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`]);function qu(e){return Ku.has(e.tagName)||e.isContentEditable===!0}var Ju=new Set([`INPUT`,`SELECT`,`TEXTAREA`]);function Yu(e){return Ju.has(e.tagName)||e.isContentEditable===!0}var Xu=new WeakSet;function Zu(e){return t=>{t.key===`Enter`&&e(t)}}function Qu(e,t){e.dispatchEvent(new PointerEvent(`pointer`+t,{isPrimary:!0,bubbles:!0}))}var $u=(e,t)=>{let n=e.currentTarget;if(!n)return;let r=Zu(()=>{if(Xu.has(n))return;Qu(n,`down`);let e=Zu(()=>{Qu(n,`up`)});n.addEventListener(`keyup`,e,t),n.addEventListener(`blur`,()=>Qu(n,`cancel`),t)});n.addEventListener(`keydown`,r,t),n.addEventListener(`blur`,()=>n.removeEventListener(`keydown`,r),t)};function ed(e){return Gu(e)&&!zu()}var td=new WeakSet;function nd(e,t,n={}){let[r,i,a]=Vu(e,n),o=e=>{let r=e.currentTarget;if(!ed(e)||td.has(e))return;Xu.add(r),n.stopPropagation&&td.add(e);let a=t(r,e),o={...i,capture:!0},s=(e,t)=>{window.removeEventListener(`pointerup`,c,o),window.removeEventListener(`pointercancel`,l,o),Xu.has(r)&&Xu.delete(r),ed(e)&&typeof a==`function`&&a(e,{success:t})},c=e=>{s(e,r===window||r===document||n.useGlobalTarget||Wu(r,e.target))},l=e=>{s(e,!1)};window.addEventListener(`pointerup`,c,o),window.addEventListener(`pointercancel`,l,o)};return r.forEach(e=>{(n.useGlobalTarget?window:e).addEventListener(`pointerdown`,o,i),iu(e)&&(e.addEventListener(`focus`,e=>$u(e,i)),!qu(e)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=0))}),a}var rd=new WeakMap,id,ad=(e,t,n)=>(r,i)=>i&&i[0]?i[0][e+`Size`]:au(r)&&`getBBox`in r?r.getBBox()[t]:r[n],od=ad(`inline`,`width`,`offsetWidth`),sd=ad(`block`,`height`,`offsetHeight`);function cd({target:e,borderBoxSize:t}){rd.get(e)?.forEach(n=>{n(e,{get width(){return od(e,t)},get height(){return sd(e,t)}})})}function ld(e){e.forEach(cd)}function ud(){typeof ResizeObserver<`u`&&(id=new ResizeObserver(ld))}function dd(e,t){id||ud();let n=su(e);return n.forEach(e=>{let n=rd.get(e);n||(n=new Set,rd.set(e,n)),n.add(t),id?.observe(e)}),()=>{n.forEach(e=>{let n=rd.get(e);n?.delete(t),n?.size||id?.unobserve(e)})}}var fd=new Set,pd;function md(){pd=()=>{let e={get width(){return window.innerWidth},get height(){return window.innerHeight}};fd.forEach(t=>t(e))},window.addEventListener(`resize`,pd)}function hd(e){return fd.add(e),pd||md(),()=>{fd.delete(e),!fd.size&&typeof pd==`function`&&(window.removeEventListener(`resize`,pd),pd=void 0)}}function gd(e,t){return typeof e==`function`?hd(e):dd(e,t)}var _d={value:null,addProjectionMetrics:null};function vd(e){return au(e)&&e.tagName===`svg`}var yd=e=>typeof e==`number`?e:parseFloat(e),bd=()=>({translate:0,scale:1,origin:0,originPoint:0}),xd=()=>({x:bd(),y:bd()}),Sd=()=>({min:0,max:0}),X=()=>({x:Sd(),y:Sd()}),Cd=new WeakMap;function wd(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function Td(e){return typeof e==`string`||Array.isArray(e)}var Ed=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],Dd=[`initial`,...Ed];function Od(e){if(wd(e.animate))return!0;for(let t=0;t<Dd.length;t++)if(Td(e[Dd[t]]))return!0;return!1}function kd(e){return!!(Od(e)||e.variants)}function Ad(e,t,n){for(let r in t){let i=t[r],a=n[r];if(q(i))e.addValue(r,i);else if(q(a))e.addValue(r,gl(i,{owner:e}));else if(a!==i){if(e.hasValue(r)){let t=e.getValue(r);t.liveStyle===!0?t.jump(i):t.hasAnimated||t.set(i)}else{let t=e.getStaticValue(r);e.addValue(r,gl(t===void 0?i:t,{owner:e}))}}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var jd={current:null},Md={current:!1},Nd=typeof window<`u`;function Pd(){if(Md.current=!0,Nd){if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>jd.current=e.matches;e.addEventListener(`change`,t),t()}else jd.current=!1}}var Fd=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],Id={};function Ld(e){Id=e}function Rd(){return Id}var zd=class{scrapeMotionValuesFromProps(e,t,n){return{}}constructor({parent:e,props:t,presenceContext:n,reducedMotionConfig:r,skipAnimations:i,blockInitialAnimation:a,visualState:o},s={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=Fc,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify(`Update`,this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{let e=z.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,G.render(this.render,!1,!0))};let{latestValues:c,renderState:l}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=t.initial?{...c}:{},this.renderState=l,this.parent=e,this.props=t,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.skipAnimationsConfig=i,this.options=s,this.blockInitialAnimation=!!a,this.isControllingVariants=Od(t),this.isVariantNode=kd(t),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);let{willChange:u,...d}=this.scrapeMotionValuesFromProps(t,{},this);for(let e in d){let t=d[e];c[e]!==void 0&&q(t)&&t.set(c[e])}}mount(e){if(this.hasBeenMounted)for(let e in this.initialValues)this.values.get(e)?.jump(this.initialValues[e]),this.latestValues[e]=this.initialValues[e];if(this.current=e,Cd.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.isVariantNode&&!this.isControllingVariants){let e=this;do e=e.props.inherit!==!1&&e.parent;while(e&&!e.isVariantNode);if(e){let{variantChildren:t}=e;t.add(this),this.removeFromVariantTree=()=>t.delete(this)}}this.values.forEach((e,t)=>this.bindToMotionValue(t,e)),this.reducedMotionConfig===`never`?this.shouldReduceMotion=!1:this.reducedMotionConfig===`always`?this.shouldReduceMotion=!0:(Md.current||Pd(),this.shouldReduceMotion=jd.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),os(this.notifyUpdate),os(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(let e in this.events)this.events[e].clear();for(let e in this.features){let t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??=new Set,this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,t){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),t.accelerate&&il.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new Jc({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:I(o)}),c=n(s);this.valueSubscriptions.set(e,()=>{c(),s.cancel()});return}let n=yc.has(e);n&&this.onBindTransform&&this.onBindTransform();let r=t.on(`change`,t=>{this.latestValues[e]=t,this.props.onUpdate&&G.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()}),i;typeof window<`u`&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i&&i()})}sortNodePosition(e){return!this.current||!e.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e=`animation`;for(e in Id){let t=Id[e];if(!t)continue;let{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(this)),this.features[e]){let t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):X()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let t=0;t<Fd.length;t++){let n=Fd[t];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);let r=e[`on`+n];r&&(this.propEventSubscriptions[n]=this.on(n,r))}this.prevMotionValues=Ad(this,this.scrapeMotionValuesFromProps(e,this.prevProps||{},this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}addValue(e,t){let n=this.values.get(e);if(t!==n){n&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t);let r=t.get();r!==void 0&&(this.latestValues[e]=r)}}removeValue(e){this.values.delete(e);let t=this.valueSubscriptions.get(e);t&&(t(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return n===void 0&&t!==void 0&&(n=gl(t??this.getDefaultValue?.(e),{owner:this}),this.addValue(e,n)),n}readValue(e,t){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n==`string`&&(_a(n)||ya(n))?n=parseFloat(n):typeof n!=`number`&&!U.test(n)&&U.test(t)&&(n=ic(e,t)),this.setBaseTarget(e,q(n)?n.get():n)),q(n)?n.get():n}setBaseTarget(e,t){this.baseTarget[e]=t}on(e,t){return this.events[e]||(this.events[e]=new Ca),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){Lu.render(this.render)}},Bd=class extends zd{constructor(){super(...arguments),this.KeyframeResolver=nu}sortInstanceNodePosition(e,t){return e.compareDocumentPosition(t)&2?1:-1}getBaseTargetFromProps(e,t){let n=e.style;return n?n[t]:void 0}removeValueFromRenderState(e,{vars:t,style:n}){delete t[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);let{children:e}=this.props;q(e)&&(this.childSubscription=e.on(`change`,e=>{this.current&&(this.current.textContent=`${e}`)}))}},Vd=class{constructor(e){this.isMounted=!1,this.node=e}update(){}};function Hd(e,{style:t,vars:n},r,i){let a=e.style,o;for(o in t)a[o]=t[o];for(o in i?.applyProjectionStyles(a,r),n)a.setProperty(o,n[o])}var Ud={};function Wd(e,{layout:t,layoutId:n}){return yc.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!Ud[e]||e===`opacity`)}function Gd(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(q(r[t])||i&&q(i[t])||Wd(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}function Kd(e){return window.getComputedStyle(e)}var qd=class extends Bd{constructor(){super(...arguments),this.type=`html`,this.renderInstance=Hd}mount(e){e.style,super.mount(e)}readValueFromInstance(e,t){if(yc.has(t))return this.projection?.isProjecting?mc(t):gc(e,t);{let n=Kd(e),r=(Ja(t)?n.getPropertyValue(t):n[t])||0;return typeof r==`string`?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:t}){return Fu(e,t)}build(e,t,n){du(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return Gd(e,t,n)}},Jd=new Set([`baseFrequency`,`diffuseConstant`,`kernelMatrix`,`kernelUnitLength`,`keySplines`,`keyTimes`,`limitingConeAngle`,`markerHeight`,`markerWidth`,`numOctaves`,`targetX`,`targetY`,`surfaceScale`,`specularConstant`,`specularExponent`,`stdDeviation`,`tableValues`,`viewBox`,`gradientTransform`,`pathLength`,`startOffset`,`textLength`,`lengthAdjust`]),Yd=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function Xd(e,t,n,r){Hd(e,t,void 0,r);for(let n in t.attrs)e.setAttribute(Jd.has(n)?n:Vl(n),t.attrs[n])}function Zd(e,t,n){let r=Gd(e,t,n);for(let n in e)if(q(e[n])||q(t[n])){let t=vc.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var Qd=class extends Bd{constructor(){super(...arguments),this.type=`svg`,this.isSVGTag=!1,this.measureInstanceViewportBox=X}getBaseTargetFromProps(e,t){return yc.has(t)?super.getBaseTargetFromProps(e,t)??mc(t):e[t]}getDefaultValue(e){return yc.has(e)?this.latestValues[e]??mc(e):void 0}readValueFromInstance(e,t){if(yc.has(t)){let e=nc(t);return e&&e.default||0}if(hu.includes(t)){let n=getComputedStyle(e)[t];if(typeof n==`string`&&n)return n.trim()}return t=Jd.has(t)?t:Vl(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return Zd(e,t,n)}build(e,t,n){gu(e,t,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,t,n,r){Xd(e,t,n,r)}mount(e){this.isSVGTag=Yd(e.tagName),super.mount(e)}};function $d(e,t){if(!Array.isArray(t))return!1;let n=t.length;if(n!==e.length)return!1;for(let r=0;r<n;r++)if(t[r]!==e[r])return!1;return!0}var ef=[...Ed].reverse();function tf(e){let t=t=>Promise.all(t.map(({animation:t,options:n})=>Jl(e,t,n))),n=rf(),r=!0,i=!1;function a(a){let{props:o,parent:s,manuallyAnimateOnMount:c}=e,l=r||i,u=[],d=new Set,f={},p=1/0,m=e;do m=m.props.inherit!==!1&&m.parent;while(m&&!m.isControllingVariants);if(ef.forEach((t,r)=>{let i=n[t],h=o[t],g=m&&m.props[t],_=h===void 0?Td(g)||g===!1?g:void 0:h,v=Td(_),y=t===a?i.isActive:null;y===!1&&(p=r);let b=v&&h===void 0&&!(l&&c);if(i.protectedKeys={...f},!i.isActive&&y===null||!_&&!i.prevProp||wd(_)||typeof _==`boolean`)return;if(t===`exit`&&i.isActive&&y!==!0){f={...f,...i.prevResolvedValues};return}let x=nf(i.prevProp,_),S=x||v&&(y&&!b||r>p),ee=!1,te=Array.isArray(_)?_:[_],ne={};if(y!==!1)for(let n of te){let{transition:r,transitionEnd:i,...a}=Ml(e,n,Nl(e,t))||{};ne={...ne,...a,...i}}let{prevResolvedValues:re}=i;for(let t in{...re,...ne}){if(t in f)continue;let n=ne[t],r=re[t],a=Array.isArray(n)&&Array.isArray(r)?!$d(n,r)||x:n!==r;if(a&&n==null)d.add(t);else if(a||n!==void 0&&d.has(t)){S=!0,d.delete(t)&&(ee=!0),i.needsAnimating[t]=!0;let n=e.getValue(t);n&&(n.liveStyle=!1)}else i.protectedKeys[t]=!0}if(i.prevProp=_,i.prevResolvedValues=ne,i.isActive&&(f={...f,...ne}),S&&(!(b&&x)||ee))for(let n of te){let r={type:t};if(typeof n==`string`&&l&&c&&s?.enteringChildren){let t=Ml(s,n)?.transition?.delayChildren;r.delay=dl(s.enteringChildren,e,t)}u.push({animation:n,options:r})}}),d.size){let{initial:t}=o,n={},r=typeof t!=`boolean`&&Ml(e,Array.isArray(t)?t[0]:t,e.presenceContext?.custom);r&&r.transition&&(n.transition=r.transition),d.forEach(i=>{let a=e.getValue(i);a&&(a.liveStyle=!0);let s=r&&!Array.isArray(t)?r[i]:void 0,c=e.getBaseTargetFromProps(o,i);n[i]=(s===void 0?c!==void 0&&!q(c)?c:e.initialValues[i]===void 0?e.baseTarget[i]:void 0:s)??null}),u.push({animation:n})}let h=l&&e.blockInitialAnimation||r&&!c&&(o.initial===!1||o.initial===o.animate);return r=i=!1,!h&&u.length?t(u):Promise.resolve()}function o(t,r){if(n[t].isActive===r)return Promise.resolve();e.variantChildren?.forEach(e=>e.animationState?.setActive(t,r)),n[t].isActive=r;let i=a(t);for(let e in n)n[e].protectedKeys={};return i}return{animateChanges:a,setActive:o,setAnimateFunction:n=>{t=n(e)},getState:()=>n,reset:()=>{n=rf(),i=!0}}}function nf(e,t){return typeof t==`string`?t!==e:Array.isArray(t)?!$d(t,e):!1}function rf(){let e={};for(let t of Ed)e[t]={isActive:t===`animate`,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}};return e}function af(e,t){e.min=t.min,e.max=t.max}function Z(e,t){af(e.x,t.x),af(e.y,t.y)}function of(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}var sf=.9999,cf=1.0001,lf=-.01,uf=.01;function Q(e){return e.max-e.min}function df(e,t,n){return Math.abs(e-t)<=n}function ff(e,t,n,r=.5){e.origin=r,e.originPoint=W(t.min,t.max,e.origin),e.scale=Q(n)/Q(t),e.translate=W(n.min,n.max,e.origin)-e.originPoint,(e.scale>=sf&&e.scale<=cf||isNaN(e.scale))&&(e.scale=1),(e.translate>=lf&&e.translate<=uf||isNaN(e.translate))&&(e.translate=0)}function pf(e,t,n,r){ff(e.x,t.x,n.x,r?r.originX:void 0),ff(e.y,t.y,n.y,r?r.originY:void 0)}function mf(e,t,n,r=0){e.min=(r?W(n.min,n.max,r):n.min)+t.min,e.max=e.min+Q(t)}function hf(e,t,n,r){mf(e.x,t.x,n.x,r?.x),mf(e.y,t.y,n.y,r?.y)}function gf(e,t,n,r=0){let i=r?W(n.min,n.max,r):n.min;e.min=t.min-i,e.max=e.min+Q(t)}function _f(e,t,n,r){gf(e.x,t.x,n.x,r?.x),gf(e.y,t.y,n.y,r?.y)}function vf(e,t,n,r,i){return e-=t,e=Tu(e,1/n,r),i!==void 0&&(e=Tu(e,1/i,r)),e}function yf(e,t=0,n=1,r=.5,i,a=e,o=e){if(B.test(t)&&(t=parseFloat(t),t=W(o.min,o.max,t/100)-o.min),typeof t!=`number`)return;let s=W(a.min,a.max,r);e===a&&(s-=t),e.min=vf(e.min,t,n,s,i),e.max=vf(e.max,t,n,s,i)}function bf(e,t,[n,r,i],a,o){yf(e,t[n],t[r],t[i],t.scale,a,o)}var xf=[`x`,`scaleX`,`originX`],Sf=[`y`,`scaleY`,`originY`];function Cf(e,t,n,r){bf(e.x,t,xf,n?n.x:void 0,r?r.x:void 0),bf(e.y,t,Sf,n?n.y:void 0,r?r.y:void 0)}function wf(e){return e.translate===0&&e.scale===1}function Tf(e){return wf(e.x)&&wf(e.y)}function Ef(e,t){return e.min===t.min&&e.max===t.max}function Df(e,t){return Ef(e.x,t.x)&&Ef(e.y,t.y)}function Of(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function kf(e,t){return Of(e.x,t.x)&&Of(e.y,t.y)}function Af(e){return Q(e.x)/Q(e.y)}function jf(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function $(e){return[e(`x`),e(`y`)]}function Mf(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}var Nf={correct:(e,t)=>{if(!t.target)return e;if(typeof e==`string`){if(V.test(e))e=parseFloat(e);else return e}return`${Mf(e,t.target.x)}% ${Mf(e,t.target.y)}%`}},Pf={correct:(e,{treeScale:t,projectionDelta:n})=>{let r=e,i=U.parse(e);if(i.length>5)return r;let a=U.createTransformer(e),o=typeof i[0]==`number`?0:1,s=n.x.scale*t.x,c=n.y.scale*t.y;i[0+o]/=s,i[1+o]/=c;let l=W(s,c,.5);return typeof i[2+o]==`number`&&(i[2+o]/=l),typeof i[3+o]==`number`&&(i[3+o]/=l),a(i)}};function Ff(e,t,n){let r=``,i=e.x.translate/t.x,a=e.y.translate/t.y,o=n?.z||0;if((i||a||o)&&(r=`translate3d(${i}px, ${a}px, ${o}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){let{transformPerspective:e,rotate:t,pathRotation:i,rotateX:a,rotateY:o,skewX:s,skewY:c}=n;e&&(r=`perspective(${e}px) ${r}`),t&&(r+=`rotate(${t}deg) `),i&&(r+=`rotate(${i}deg) `),a&&(r+=`rotateX(${a}deg) `),o&&(r+=`rotateY(${o}deg) `),s&&(r+=`skewX(${s}deg) `),c&&(r+=`skewY(${c}deg) `)}let s=e.x.scale*t.x,c=e.y.scale*t.y;return(s!==1||c!==1)&&(r+=`scale(${s}, ${c})`),r||`none`}var If=ru.length,Lf=e=>typeof e==`number`||V.test(e);function Rf(e,t,n,r,i,a){i?(e.opacity=W(0,n.opacity??1,Bf(r)),e.opacityExit=W(t.opacity??1,0,Vf(r))):a&&(e.opacity=W(t.opacity??1,n.opacity??1,r));for(let i=0;i<If;i++){let a=ru[i],o=zf(t,a),s=zf(n,a);(o!==void 0||s!==void 0)&&(o||=0,s||=0,o===0||s===0||Lf(o)===Lf(s)?(e[a]=Math.max(W(yd(o),yd(s),r),0),(B.test(s)||B.test(o))&&(e[a]+=`%`)):e[a]=s)}(t.rotate||n.rotate)&&(e.rotate=W(t.rotate||0,n.rotate||0,r))}function zf(e,t){return e[t]===void 0?e.borderRadius:e[t]}var Bf=Hf(0,.5,Pa),Vf=Hf(.5,.95,F);function Hf(e,t,n){return r=>r<e?0:r>t?1:n(Sa(e,t,r))}function Uf(e,t,n){let r=q(e)?e:gl(e);return r.start(El(``,r,t,n)),r.animation}function Wf(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n,r)}var Gf=(e,t)=>e.depth-t.depth,Kf=class{constructor(){this.children=[],this.isDirty=!1}add(e){pa(this.children,e),this.isDirty=!0}remove(e){ma(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(Gf),this.isDirty=!1,this.children.forEach(e)}};function qf(e,t){let n=z.now(),r=({timestamp:i})=>{let a=i-n;a>=t&&(os(r),e(a-t))};return G.setup(r,!0),()=>os(r)}function Jf(e){return q(e)?e.get():e}var Yf=class{constructor(){this.members=[]}add(e){pa(this.members,e);for(let t=this.members.length-1;t>=0;t--){let n=this.members[t];if(n===e||n===this.lead||n===this.prevLead)continue;let r=n.instance;(!r||r.isConnected===!1)&&!n.snapshot&&(ma(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(ma(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){let e=this.members[this.members.length-1];e&&this.promote(e)}}relegate(e){for(let t=this.members.indexOf(e)-1;t>=0;t--){let e=this.members[t];if(e.isPresent!==!1&&e.instance?.isConnected!==!1)return this.promote(e),!0}return!1}promote(e,t){let n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.updateSnapshot(),e.scheduleRender();let{layoutDependency:r}=n.options,{layoutDependency:i}=e.options;(r===void 0||r!==i)&&(e.resumeFrom=n,t&&(n.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root?.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{e.options.onExitComplete?.(),e.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}},Xf={borderRadius:{...Nf,applyTo:[...ru]},borderTopLeftRadius:Nf,borderTopRightRadius:Nf,borderBottomLeftRadius:Nf,borderBottomRightRadius:Nf,boxShadow:Pf},Zf={hasAnimatedSinceResize:!0,hasEverUpdated:!1};Object.assign(Ud,{...Xf,...Ud});var Qf={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},$f=[``,`X`,`Y`,`Z`],ep=1e3,tp=0;function np(e,t,n,r){let{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function rp(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;let{visualElement:t}=e.options;if(!t)return;let n=Ul(t);if(window.MotionHasOptimisedAnimation(n,`transform`)){let{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,`transform`,G,!(t||r))}let{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&rp(r)}function ip({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=t?.()){this.id=tp++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,_d.value&&(Qf.nodes=Qf.calculatedTargetDeltas=Qf.calculatedProjections=0),this.nodes.forEach(sp),this.nodes.forEach(vp),this.nodes.forEach(yp),this.nodes.forEach(cp),_d.addProjectionMetrics&&_d.addProjectionMetrics(Qf)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=e,this.root=n?n.root||n:this,this.path=n?[...n.path,n]:[],this.parent=n,this.depth=n?n.depth+1:0;for(let e=0;e<this.path.length;e++)this.path[e].shouldResetTransform=!0;this.root===this&&(this.nodes=new Kf)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new Ca),this.eventHandlers.get(e).add(t)}notifyListeners(e,...t){let n=this.eventHandlers.get(e);n&&n.notify(...t)}hasListeners(e){return this.eventHandlers.has(e)}mount(t){if(this.instance)return;this.isSVG=au(t)&&!vd(t),this.instance=t;let{layoutId:n,layout:r,visualElement:i}=this.options;if(i&&!i.current&&i.mount(t),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(r||n)&&(this.isLayoutDirty=!0),e){let n,r=0,i=()=>this.root.updateBlockedByResize=!1;G.read(()=>{r=window.innerWidth}),e(t,()=>{let e=window.innerWidth;e!==r&&(r=e,this.root.updateBlockedByResize=!0,n&&n(),n=qf(i,250),Zf.hasAnimatedSinceResize&&(Zf.hasAnimatedSinceResize=!1,this.nodes.forEach(_p)))})}n&&this.root.registerSharedNode(n,this),this.options.animate!==!1&&i&&(n||r)&&this.addEventListener(`didUpdate`,({delta:e,hasLayoutChanged:t,hasRelativeLayoutChanged:n,layout:r})=>{if(this.isAnimationBlocked){this.target=void 0,this.relativeTarget=void 0;return}let a=this.options.transition||i.getDefaultTransition()||Ep,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=i.getProps(),c=!this.targetLayout||!kf(this.targetLayout,r),l=!t&&n;if(this.options.layoutRoot||this.resumeFrom||l||t&&(c||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);let t={...vl(a,`layout`),onPlay:o,onComplete:s};(i.shouldReduceMotion||this.options.layoutRoot)&&(t.delay=0,t.type=!1),this.startAnimation(t),this.setAnimationOrigin(e,l,t.path)}else t||_p(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=r})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);let e=this.getStack();e&&e.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),os(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(bp),this.animationId++)}getTransformTemplate(){let{visualElement:e}=this.options;return e&&e.getProps().transformTemplate}willUpdate(e=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&rp(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let e=0;e<this.path.length;e++){let t=this.path[e];t.shouldResetTransform=!0,(typeof t.latestValues.x==`string`||typeof t.latestValues.y==`string`)&&(t.isLayoutDirty=!0),t.updateScroll(`snapshot`),t.options.layoutRoot&&t.willUpdate(!1),t.isAnimationBlocked&&(t.dragSnapshot||=t.measure(),this.dragAncestor=t)}let{layoutId:t,layout:n}=this.options;if(t===void 0&&!n)return;let r=this.getTransformTemplate();this.prevTransformTemplateValue=r?r(this.latestValues,``):void 0,this.updateSnapshot(),e&&this.notifyListeners(`willUpdate`)}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){let e=this.updateBlockedByResize;this.unblockUpdate(),this.updateBlockedByResize=!1,this.clearAllSnapshots(),e&&this.nodes.forEach(dp),this.nodes.forEach(up);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(fp);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(mp),this.nodes.forEach(hp),this.nodes.forEach(gp),this.nodes.forEach(ap),this.nodes.forEach(op)):this.nodes.forEach(fp),this.clearAllSnapshots();let e=z.now();R.delta=N(0,1e3/60,e-R.timestamp),R.timestamp=e,R.isProcessing=!0,ss.update.process(R),ss.preRender.process(R),ss.render.process(R),R.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Lu.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(lp),this.sharedNodes.forEach(xp)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,G.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){G.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){!this.snapshot&&this.instance&&(this.snapshot=this.measure(),this.snapshot&&!Q(this.snapshot.measuredBox.x)&&!Q(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let e=0;e<this.path.length;e++)this.path[e].updateScroll();let e=this.layout;this.layout=this.measure(!1),this.layoutCorrected||=X(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners(`measure`,this.layout.layoutBox);let{visualElement:t}=this.options;t&&t.notify(`LayoutMeasure`,this.layout.layoutBox,e?e.layoutBox:void 0)}updateScroll(e=`measure`){let t=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===e&&(t=!1),t&&this.instance){let t=r(this.instance);this.scroll={animationId:this.root.animationId,phase:e,isRoot:t,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:t}}}resetTransform(){if(!i)return;let e=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,t=this.projectionDelta&&!Tf(this.projectionDelta),n=this.getTransformTemplate(),r=n?n(this.latestValues,``):void 0,a=r!==this.prevTransformTemplateValue;e&&this.instance&&(t||Su(this.latestValues)||a)&&(i(this.instance,r),this.shouldResetTransform=!1,this.scheduleRender())}measure(e=!0){let t=this.measurePageBox(),n=this.removeElementScroll(t);return e&&(n=this.removeTransform(n)),Ap(n),{animationId:this.root.animationId,measuredBox:t,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){let{visualElement:e}=this.options;if(!e)return X();let t=e.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Mp))){let{scroll:e}=this.root;e&&(J(t.x,e.offset.x),J(t.y,e.offset.y))}return t}removeElementScroll(e){let t=X();if(Z(t,e),this.scroll?.wasRoot)return t;for(let n=0;n<this.path.length;n++){let r=this.path[n],{scroll:i,options:a}=r;r!==this.root&&i&&a.layoutScroll&&(i.wasRoot&&Z(t,e),J(t.x,i.offset.x),J(t.y,i.offset.y))}return t}applyTransform(e,t=!1,n){let r=n||X();Z(r,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];!t&&n.options.layoutScroll&&n.scroll&&n!==n.root&&(J(r.x,-n.scroll.offset.x),J(r.y,-n.scroll.offset.y)),Su(n.latestValues)&&Pu(r,n.latestValues,n.layout?.layoutBox)}return Su(this.latestValues)&&Pu(r,this.latestValues,this.layout?.layoutBox),r}removeTransform(e){let t=X();Z(t,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];if(!Su(n.latestValues))continue;let r;n.instance&&(xu(n.latestValues)&&n.updateSnapshot(),r=X(),Z(r,n.measurePageBox())),Cf(t,n.latestValues,n.snapshot?.layoutBox,r)}return Su(this.latestValues)&&Cf(t,this.latestValues),t}setTargetDelta(e){this.targetDelta=e,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(e){this.options={...this.options,...e,crossfade:e.crossfade===void 0||e.crossfade}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==R.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(e=!1){let t=this.getLead();this.isProjectionDirty||=t.isProjectionDirty,this.isTransformDirty||=t.isTransformDirty,this.isSharedProjectionDirty||=t.isSharedProjectionDirty;let n=!!this.resumingFrom||this!==t;if(!(e||n&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;let{layout:r,layoutId:i}=this.options;if(!this.layout||!(r||i))return;this.resolvedRelativeTargetAt=R.timestamp;let a=this.getClosestProjectingParent();!this.targetDelta&&!this.relativeTarget&&(this.options.layoutAnchor!==!1&&a&&a.layout?this.createRelativeTarget(a,this.layout.layoutBox,a.layout.layoutBox):this.removeRelativeTarget()),(this.relativeTarget||this.targetDelta)&&(this.target||(this.target=X(),this.targetWithTransforms=X()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),hf(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):Z(this.target,this.layout.layoutBox),Ou(this.target,this.targetDelta)):Z(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget&&(this.attemptToResolveRelativeTarget=!1,this.options.layoutAnchor!==!1&&a&&!!a.resumingFrom==!!this.resumingFrom&&!a.options.layoutScroll&&a.target&&this.animationProgress!==1?this.createRelativeTarget(a,this.target,a.target):this.relativeParent=this.relativeTarget=void 0),_d.value&&Qf.calculatedTargetDeltas++)}getClosestProjectingParent(){if(!(!this.parent||xu(this.parent.latestValues)||Cu(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}createRelativeTarget(e,t,n){this.relativeParent=e,this.forceRelativeParentToResolveTarget(),this.relativeTarget=X(),this.relativeTargetOrigin=X(),_f(this.relativeTargetOrigin,t,n,this.options.layoutAnchor||void 0),Z(this.relativeTarget,this.relativeTargetOrigin)}removeRelativeTarget(){this.relativeParent=this.relativeTarget=void 0}calcProjection(){let e=this.getLead(),t=!!this.resumingFrom||this!==e,n=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(n=!1),t&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(n=!1),this.resolvedRelativeTargetAt===R.timestamp&&(n=!1),n)return;let{layout:r,layoutId:i}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(r||i))return;Z(this.layoutCorrected,this.layout.layoutBox);let a=this.treeScale.x,o=this.treeScale.y;ju(this.layoutCorrected,this.treeScale,this.path,t),e.layout&&!e.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(e.target=e.layout.layoutBox,e.targetWithTransforms=X());let{target:s}=e;s?(!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(of(this.prevProjectionDelta.x,this.projectionDelta.x),of(this.prevProjectionDelta.y,this.projectionDelta.y)),pf(this.projectionDelta,this.layoutCorrected,s,this.latestValues),(this.treeScale.x!==a||this.treeScale.y!==o||!jf(this.projectionDelta.x,this.prevProjectionDelta.x)||!jf(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners(`projectionUpdate`,s)),_d.value&&Qf.calculatedProjections++):this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender())}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(e=!0){if(this.options.visualElement?.scheduleRender(),e){let e=this.getStack();e&&e.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=xd(),this.projectionDelta=xd(),this.projectionDeltaWithTransform=xd()}setAnimationOrigin(e,t=!1,n){let r=this.snapshot,i=r?r.latestValues:{},a={...this.latestValues},o=xd();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let s=X(),c=(r?r.source:void 0)!==(this.layout?this.layout.source:void 0),l=this.getStack(),u=!l||l.members.length<=1,d=!(!c||u||this.options.crossfade!==!0||this.path.some(Tp));this.animationProgress=0;let f,p=n?.interpolateProjection(e);this.mixTargetDelta=t=>{let n=t/1e3,r=p?.(n);r?(o.x.translate=r.x,o.x.scale=W(e.x.scale,1,n),o.x.origin=e.x.origin,o.x.originPoint=e.x.originPoint,o.y.translate=r.y,o.y.scale=W(e.y.scale,1,n),o.y.origin=e.y.origin,o.y.originPoint=e.y.originPoint):(Sp(o.x,e.x,n),Sp(o.y,e.y,n)),this.setTargetDelta(o),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(_f(s,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),wp(this.relativeTarget,this.relativeTargetOrigin,s,n),f&&Df(this.relativeTarget,f)&&(this.isProjectionDirty=!1),f||=X(),Z(f,this.relativeTarget)),c&&(this.animationValues=a,Rf(a,i,this.latestValues,n,d,u)),r&&r.rotate!==void 0&&(this.animationValues||=a,this.animationValues.pathRotation=r.rotate),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=n},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(e){this.notifyListeners(`animationStart`),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&=(os(this.pendingAnimation),void 0),this.pendingAnimation=G.update(()=>{Zf.hasAnimatedSinceResize=!0,this.motionValue||=gl(0),this.motionValue.jump(0,!1),this.currentAnimation=Uf(this.motionValue,[0,1e3],{...e,velocity:0,isSync:!0,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onComplete:()=>{e.onComplete&&e.onComplete(),this.completeAnimation()}}),Us(this.currentAnimation,this),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);let e=this.getStack();e&&e.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners(`animationComplete`)}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(ep),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){let e=this.getLead(),{targetWithTransforms:t,layout:n,latestValues:r}=e,{target:i}=e;if(t&&i&&n){if(this!==e&&this.layout&&n&&jp(this.options.animationType,this.layout.layoutBox,n.layoutBox)){i=this.target||X();let t=Q(this.layout.layoutBox.x);i.x.min=e.target.x.min,i.x.max=i.x.min+t;let n=Q(this.layout.layoutBox.y);i.y.min=e.target.y.min,i.y.max=i.y.min+n}Z(t,i),Pu(t,r),pf(this.projectionDeltaWithTransform,this.layoutCorrected,t,r)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new Yf),this.sharedNodes.get(e).add(t);let n=t.options.initialPromotionConfig;t.promote({transition:n?n.transition:void 0,preserveFollowOpacity:n&&n.shouldPreserveFollowOpacity?n.shouldPreserveFollowOpacity(t):void 0})}isLead(){let e=this.getStack();return!e||e.lead===this}getLead(){let{layoutId:e}=this.options;return e&&this.getStack()?.lead||this}getPrevLead(){let{layoutId:e}=this.options;return e?this.getStack()?.prevLead:void 0}getStack(){let{layoutId:e}=this.options;if(e)return this.root.sharedNodes.get(e)}promote({needsReset:e,transition:t,preserveFollowOpacity:n}={}){let r=this.getStack();r&&r.promote(this,n),e&&(this.projectionDelta=void 0,this.needsReset=!0),t&&this.setOptions({transition:t})}relegate(){let e=this.getStack();return e?e.relegate(this):!1}resetSkewAndRotation(){let{visualElement:e}=this.options;if(!e)return;let t=!1,{latestValues:n}=e;if((n.z||n.rotate||n.rotateX||n.rotateY||n.rotateZ||n.skewX||n.skewY)&&(t=!0),!t)return;let r={};n.z&&np(`z`,e,r,this.animationValues);for(let t=0;t<$f.length;t++)np(`rotate${$f[t]}`,e,r,this.animationValues),np(`skew${$f[t]}`,e,r,this.animationValues);e.render();for(let t in r)e.setStaticValue(t,r[t]),this.animationValues&&(this.animationValues[t]=r[t]);e.scheduleRender()}applyProjectionStyles(e,t){if(!this.instance||this.isSVG)return;if(!this.isVisible){e.visibility=`hidden`;return}let n=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,e.visibility=``,e.opacity=``,e.pointerEvents=Jf(t?.pointerEvents)||``,e.transform=n?n(this.latestValues,``):`none`;return}let r=this.getLead();if(!this.projectionDelta||!this.layout||!r.target){this.options.layoutId&&(e.opacity=this.latestValues.opacity===void 0?1:this.latestValues.opacity,e.pointerEvents=Jf(t?.pointerEvents)||``),this.hasProjected&&!Su(this.latestValues)&&(e.transform=n?n({},``):`none`,this.hasProjected=!1);return}e.visibility=``;let i=r.animationValues||r.latestValues;this.applyTransformsToTarget();let a=Ff(this.projectionDeltaWithTransform,this.treeScale,i);n&&(a=n(i,a)),e.transform=a;let{x:o,y:s}=this.projectionDelta;e.transformOrigin=`${o.origin*100}% ${s.origin*100}% 0`,e.opacity=r.animationValues?r===this?i.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:i.opacityExit:r===this?i.opacity===void 0?``:i.opacity:i.opacityExit===void 0?0:i.opacityExit;for(let t in Ud){if(i[t]===void 0)continue;let{correct:n,applyTo:o,isCSSVariable:s}=Ud[t],c=a===`none`?i[t]:n(i[t],r);if(o){let t=o.length;for(let n=0;n<t;n++)e[o[n]]=c}else s?this.options.visualElement.renderState.vars[t]=c:e[t]=c}this.options.layoutId&&(e.pointerEvents=r===this?Jf(t?.pointerEvents)||``:`none`)}clearSnapshot(){this.resumeFrom=this.snapshot=this.dragSnapshot=this.dragAncestor=void 0}resetTree(){this.root.nodes.forEach(e=>e.currentAnimation?.stop()),this.root.nodes.forEach(up),this.root.sharedNodes.clear()}}}function ap(e){e.updateLayout(),pp(e)}function op(e){let t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners(`didUpdate`)){let{layoutBox:n,measuredBox:r}=e.layout,{animationType:i}=e.options,a=t.source!==e.layout.source;if(i===`size`)$(e=>{let r=a?t.measuredBox[e]:t.layoutBox[e],i=Q(r);r.min=n[e].min,r.max=r.min+i});else if(i===`x`||i===`y`){let e=i===`x`?`y`:`x`;af(a?t.measuredBox[e]:t.layoutBox[e],n[e])}else jp(i,t.layoutBox,n)&&$(r=>{let i=a?t.measuredBox[r]:t.layoutBox[r],o=Q(n[r]);i.max=i.min+o,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[r].max=e.relativeTarget[r].min+o)});let o=xd();pf(o,n,t.layoutBox);let s=xd();a?pf(s,e.applyTransform(r,!0),t.measuredBox):pf(s,n,t.layoutBox);let c=!Tf(o),l=!1;if(!e.resumeFrom){let r=e.getClosestProjectingParent();if(r&&!r.resumeFrom){let{snapshot:i,layout:a}=r;if(i&&a){let o=e.options.layoutAnchor||void 0,s=X();_f(s,t.layoutBox,i.layoutBox,o);let c=X();_f(c,n,a.layoutBox,o),kf(s,c)||(l=!0),r.options.layoutRoot&&(e.relativeTarget=c,e.relativeTargetOrigin=s,e.relativeParent=r)}}}e.notifyListeners(`didUpdate`,{layout:n,snapshot:t,delta:s,layoutDelta:o,hasLayoutChanged:c,hasRelativeLayoutChanged:l})}else if(e.isLead()){let{onExitComplete:t}=e.options;t&&t()}e.options.transition=void 0}function sp(e){_d.value&&Qf.nodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty),e.isTransformDirty||=e.parent.isTransformDirty)}function cp(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function lp(e){e.clearSnapshot()}function up(e){e.clearMeasurements()}function dp(e){e.isLayoutDirty=!0,e.updateLayout()}function fp(e){e.isLayoutDirty=!1}function pp(e){let{snapshot:t,dragAncestor:n}=e,r=n?.layout;if(!t||!r||e.resumeFrom||e.isAnimationBlocked)return;let i=n.dragSnapshot;$(e=>J(t.layoutBox[e],r.layoutBox[e].min-i.layoutBox[e].min))}function mp(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.dragSnapshot||e.layout,e.isLayoutDirty=!0)}function hp(e){e.relativeTarget&&e.relativeParent?.isLayoutDirty&&(e.currentAnimation?e.isLayoutDirty=!0:(e.targetDelta=void 0,e.removeRelativeTarget()))}function gp(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify(`BeforeLayoutMeasure`),e.resetTransform()}function _p(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function vp(e){e.resolveTargetDelta()}function yp(e){e.calcProjection()}function bp(e){e.resetSkewAndRotation()}function xp(e){e.removeLeadSnapshot()}function Sp(e,t,n){e.translate=W(t.translate,0,n),e.scale=W(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Cp(e,t,n,r){e.min=W(t.min,n.min,r),e.max=W(t.max,n.max,r)}function wp(e,t,n,r){Cp(e.x,t.x,n.x,r),Cp(e.y,t.y,n.y,r)}function Tp(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}var Ep={duration:.45,ease:[.4,0,.1,1]},Dp=e=>typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Op=Dp(`applewebkit/`)&&!Dp(`chrome/`)?Math.round:F;function kp(e){e.min=Op(e.min),e.max=Op(e.max)}function Ap(e){kp(e.x),kp(e.y)}function jp(e,t,n){return e===`position`||e===`preserve-aspect`&&!df(Af(t),Af(n),.2)}function Mp(e){return e!==e.root&&e.scroll?.wasRoot}var Np=ip({attachResizeListener:(e,t)=>Wf(e,`resize`,t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),Pp={current:void 0},Fp=ip({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Pp.current){let e=new Np({});e.mount(window),e.setOptions({layoutScroll:!0}),Pp.current=e}return Pp.current},resetTransform:(e,t)=>{e.style.transform=t===void 0?`none`:t},checkIsScrollRoot:e=>window.getComputedStyle(e).position===`fixed`}),Ip=(0,a.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`});function Lp(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}function Rp(...e){return t=>{let n=!1,r=e.map(e=>{let r=Lp(e,t);return!n&&typeof r==`function`&&(n=!0),r});if(n)return()=>{for(let t=0;t<r.length;t++){let n=r[t];typeof n==`function`?n():Lp(e[t],null)}}}}function zp(...e){return a.useCallback(Rp(...e),e)}var Bp=class extends a.Component{getSnapshotBeforeUpdate(e){let t=this.props.childRef.current;if(iu(t)&&e.isPresent&&!this.props.isPresent&&this.props.pop!==!1){let e=t.offsetParent,n=iu(e)&&e.offsetWidth||0,r=iu(e)&&e.offsetHeight||0,i=getComputedStyle(t),a=this.props.sizeRef.current;a.height=parseFloat(i.height),a.width=parseFloat(i.width),a.top=t.offsetTop,a.left=t.offsetLeft,a.right=n-a.width-a.left,a.bottom=r-a.height-a.top,a.direction=i.direction}return null}componentDidUpdate(){}render(){return this.props.children}};function Vp({children:e,isPresent:t,anchorX:n,anchorY:r,root:i,pop:o}){let s=(0,a.useId)(),c=(0,a.useRef)(null),l=(0,a.useRef)({width:0,height:0,top:0,left:0,right:0,bottom:0,direction:`ltr`}),{nonce:u}=(0,a.useContext)(Ip),d=zp(c,o===!1?void 0:e.props?.ref??e?.ref);return(0,a.useInsertionEffect)(()=>{let{width:e,height:a,top:d,left:f,right:p,bottom:m,direction:h}=l.current;if(t||o===!1||!c.current||!e||!a)return;let g=h===`rtl`,_=n===`left`?g?`right: ${p}`:`left: ${f}`:g?`left: ${f}`:`right: ${p}`,v=r===`bottom`?`bottom: ${m}`:`top: ${d}`,y=c.current;y.dataset.motionPopId=s;let b=y.ownerDocument,x=b.createElement(`style`);u&&(x.nonce=u);let S=i??b.head;return S.appendChild(x),x.sheet&&x.sheet.insertRule(`
11
+ [data-motion-pop-id="${s}"] {
12
+ position: absolute !important;
13
+ width: ${e}px !important;
14
+ height: ${a}px !important;
15
+ ${_}px !important;
16
+ ${v}px !important;
17
+ }
18
+ `),()=>{c.current?.removeAttribute(`data-motion-pop-id`),S.contains(x)&&S.removeChild(x)}},[t]),(0,M.jsx)(Bp,{isPresent:t,childRef:c,sizeRef:l,pop:o,children:o===!1?e:a.cloneElement(e,{ref:d})})}var Hp=({children:e,initial:t,isPresent:n,onExitComplete:r,custom:i,presenceAffectsLayout:o,mode:s,anchorX:c,anchorY:l,root:u})=>{let d=ua(Up),f=(0,a.useId)(),p=(0,a.useRef)(n),m=(0,a.useRef)(r);da(()=>{p.current=n,m.current=r});let h=!0,g=(0,a.useMemo)(()=>(h=!1,{id:f,initial:t,isPresent:n,custom:i,onExitComplete:e=>{d.set(e,!0);for(let e of d.values())if(!e)return;r&&r()},register:e=>(d.set(e,!1),()=>{d.delete(e),!p.current&&!d.size&&m.current?.()})}),[n,d,r]);return o&&h&&(g={...g}),(0,a.useMemo)(()=>{d.forEach((e,t)=>d.set(t,!1))},[n]),a.useEffect(()=>{!n&&!d.size&&r&&r()},[n]),e=(0,M.jsx)(Vp,{pop:s===`popLayout`,isPresent:n,anchorX:c,anchorY:l,root:u,children:e}),(0,M.jsx)(fa.Provider,{value:g,children:e})};function Up(){return new Map}function Wp(e=!0){let t=(0,a.useContext)(fa);if(t===null)return[!0,null];let{isPresent:n,onExitComplete:r,register:i}=t,o=(0,a.useId)();(0,a.useEffect)(()=>{if(e)return i(o)},[e]);let s=(0,a.useCallback)(()=>e&&r&&r(o),[o,r,e]);return!n&&r?[!1,s]:[!0]}var Gp=e=>e.key||``;function Kp(e){let t=[];return a.Children.forEach(e,e=>{(0,a.isValidElement)(e)&&t.push(e)}),t}var qp=({children:e,custom:t,initial:n=!0,onExitComplete:r,presenceAffectsLayout:i=!0,mode:o=`sync`,propagate:s=!1,anchorX:c=`left`,anchorY:l=`top`,root:u})=>{let[d,f]=Wp(s),p=(0,a.useMemo)(()=>Kp(e),[e]),m=s&&!d?[]:p.map(Gp),h=(0,a.useRef)(!0),g=ua(()=>new Map),_=(0,a.useRef)(new Set),[v,y]=(0,a.useState)(p),[b,x]=(0,a.useState)(p);da(()=>{s&&!d&&!b.length&&f?.()},[d,s,b.length,f]),da(()=>{h.current=!1;for(let e=0;e<b.length;e++){let t=Gp(b[e]);m.includes(t)?(g.delete(t),_.current.delete(t)):g.get(t)!==!0&&g.set(t,!1)}},[b,m.length,m.join(`-`)]);let S=[];if(p!==v){let e=[...p],t=0;for(let n of b){let r=m.indexOf(Gp(n));r===-1?(e.splice(t++,0,n),S.push(n)):t=r+S.length+1}return S.every(e=>g.get(Gp(e)))?e=p:o===`wait`&&(e=S),x(Kp(e)),y(p),null}let{forceRender:ee}=(0,a.useContext)(la);return(0,M.jsx)(M.Fragment,{children:b.map(e=>{let a=Gp(e),v=s&&!d?!1:p===b||m.includes(a);return(0,M.jsx)(Hp,{isPresent:v,initial:!h.current||n?void 0:!1,custom:t,presenceAffectsLayout:i,mode:o,root:u,onExitComplete:v?void 0:()=>{if(_.current.has(a))return;if(g.has(a))_.current.add(a),g.set(a,!0);else return;let e=!0;g.forEach(t=>{t||(e=!1)}),e&&(ee?.(),y([]),s&&f?.(),r&&r())},anchorX:c,anchorY:l,children:e},a)})})},Jp=(0,a.createContext)({strict:!1}),Yp={animation:[`animate`,`variants`,`whileHover`,`whileTap`,`exit`,`whileInView`,`whileFocus`,`whileDrag`],exit:[`exit`],drag:[`drag`,`dragControls`],focus:[`whileFocus`],hover:[`whileHover`,`onHoverStart`,`onHoverEnd`],tap:[`whileTap`,`onTap`,`onTapStart`,`onTapCancel`],pan:[`onPan`,`onPanStart`,`onPanSessionStart`,`onPanEnd`],inView:[`whileInView`,`onViewportEnter`,`onViewportLeave`],layout:[`layout`,`layoutId`]},Xp=!1;function Zp(){if(Xp)return;let e={};for(let t in Yp)e[t]={isEnabled:e=>Yp[t].some(t=>!!e[t])};Ld(e),Xp=!0}function Qp(){return Zp(),Rd()}function $p(e){let t=Qp();for(let n in e)t[n]={...t[n],...e[n]};Ld(t)}var em=(0,a.createContext)({});function tm(e,t){if(Od(e)){let{initial:t,animate:n}=e;return{initial:t===!1||Td(t)?t:void 0,animate:Td(n)?n:void 0}}return e.inherit===!1?{}:t}function nm(e){let{initial:t,animate:n}=tm(e,(0,a.useContext)(em));return(0,a.useMemo)(()=>({initial:t,animate:n}),[rm(t),rm(n)])}function rm(e){return Array.isArray(e)?e.join(` `):e}var im=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function am(e,t,n){for(let r in t)!q(t[r])&&!Wd(r,n)&&(e[r]=t[r])}function om({transformTemplate:e},t){return(0,a.useMemo)(()=>{let n=im();return du(n,t,e),Object.assign({},n.vars,n.style)},[t])}function sm(e,t){let n=e.style||{},r={};return am(r,n,e),Object.assign(r,om(e,t)),r}function cm(e,t){let n={},r=sm(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout=`none`,r.touchAction=e.drag===!0?`none`:`pan-${e.drag===`x`?`y`:`x`}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=r,n}var lm=()=>({...im(),attrs:{}});function um(e,t,n,r){let i=(0,a.useMemo)(()=>{let n=lm();return gu(n,t,Yd(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};am(t,e.style,e),i.style={...t,...i.style}}return i}var dm=new Set(`animate.exit.variants.initial.style.values.transition.transformTemplate.custom.inherit.onBeforeLayoutMeasure.onAnimationStart.onAnimationComplete.onUpdate.onDragStart.onDrag.onDragEnd.onMeasureDragConstraints.onDirectionLock.onDragTransitionEnd._dragX._dragY.onHoverStart.onHoverEnd.onViewportEnter.onViewportLeave.globalTapTarget.propagate.ignoreStrict.viewport`.split(`.`));function fm(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||dm.has(e)}function pm(e,t){return e.startsWith(`on`)?!fm(e):t?.(e)??!fm(e)}function mm(e,t,n,r){let i={};for(let a in e)(a!==`values`||typeof e.values!=`object`)&&(q(e[a])||(pm(a,r)||n===!0&&fm(a)||!t&&!fm(a)||e.draggable&&a.startsWith(`onDrag`))&&(i[a]=e[a]));return i}var hm=[`animate`,`circle`,`defs`,`desc`,`ellipse`,`g`,`image`,`line`,`filter`,`marker`,`mask`,`metadata`,`path`,`pattern`,`polygon`,`polyline`,`rect`,`stop`,`switch`,`symbol`,`svg`,`text`,`tspan`,`use`,`view`];function gm(e){return typeof e!=`string`||e.includes(`-`)?!1:!!(hm.indexOf(e)>-1||/[A-Z]/u.test(e))}function _m(e,t,n,{latestValues:r},i,o=!1,s,c){let l=(s??gm(e)?um:cm)(t,r,i,e),u=mm(t,typeof e==`string`,o,c),d=e===a.Fragment?{}:{...u,...l,ref:n},{children:f}=t,p=(0,a.useMemo)(()=>q(f)?f.get():f,[f]);return(0,a.createElement)(e,{...d,children:p})}function vm({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:ym(n,r,i,e),renderState:t()}}function ym(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=Jf(a[e]);let{initial:o,animate:s}=e,c=Od(e),l=kd(e);t&&l&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),s===void 0&&(s=t.animate));let u=n?n.initial===!1:!1;u||=o===!1;let d=u?s:o;if(d&&typeof d!=`boolean`&&!wd(d)){let t=Array.isArray(d)?d:[d];for(let n=0;n<t.length;n++){let r=jl(e,t[n]);if(r){let{transitionEnd:e,transition:t,...n}=r;for(let e in n){let t=n[e];if(Array.isArray(t)){let e=u?t.length-1:0;t=t[e]}t!==null&&(i[e]=t)}for(let t in e)i[t]=e[t]}}}return i}var bm=e=>(t,n)=>{let r=(0,a.useContext)(em),i=(0,a.useContext)(fa),o=()=>vm(e,t,r,i);return n?o():ua(o)},xm=bm({scrapeMotionValuesFromProps:Gd,createRenderState:im}),Sm=bm({scrapeMotionValuesFromProps:Zd,createRenderState:lm}),Cm=Symbol.for(`motionComponentSymbol`);function wm(e,t,n){let r=(0,a.useRef)(n);(0,a.useInsertionEffect)(()=>{r.current=n});let i=(0,a.useRef)(null);return(0,a.useCallback)(n=>{n&&e.onMount?.(n),t&&(n?t.mount(n):t.unmount());let a=r.current;if(typeof a==`function`){if(n){let e=a(n);typeof e==`function`&&(i.current=e)}else i.current?(i.current(),i.current=null):a(n)}else a&&(a.current=n)},[t])}var Tm=(0,a.createContext)({});function Em(e){return e&&typeof e==`object`&&Object.prototype.hasOwnProperty.call(e,`current`)}function Dm(e,t,n,r,i,o){let{visualElement:s}=(0,a.useContext)(em),c=(0,a.useContext)(Jp),l=(0,a.useContext)(fa),u=(0,a.useContext)(Ip),d=u.reducedMotion,f=u.skipAnimations,p=(0,a.useRef)(null),m=(0,a.useRef)(!1);r||=c.renderer,!p.current&&r&&(p.current=r(e,{visualState:t,parent:s,props:n,presenceContext:l,blockInitialAnimation:l?l.initial===!1:!1,reducedMotionConfig:d,skipAnimations:f,isSVG:o}),m.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));let h=p.current,g=(0,a.useContext)(Tm);h&&!h.projection&&i&&(h.type===`html`||h.type===`svg`)&&Om(p.current,n,i,g);let _=(0,a.useRef)(!1);(0,a.useInsertionEffect)(()=>{h&&_.current&&h.update(n,l)});let v=n[Hl],y=(0,a.useRef)(!!v&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(v)&&window.MotionHasOptimisedAnimation?.(v));return da(()=>{m.current&&h&&(h.animationState?.animateChanges(),h.enteringChildren=void 0)},[]),da(()=>{m.current=!0,h&&(_.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),h.scheduleRenderMicrotask(),y.current&&h.animationState&&h.animationState.animateChanges())}),(0,a.useEffect)(()=>{h&&(!y.current&&h.animationState&&h.animationState.animateChanges(),y.current&&=(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(v)}),!1),h.enteringChildren=void 0)}),h}function Om(e,t,n,r){let{layoutId:i,layout:a,drag:o,dragConstraints:s,layoutScroll:c,layoutRoot:l,layoutAnchor:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t[`data-framer-portal-id`]?void 0:km(e.parent)),e.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!o||s&&Em(s),visualElement:e,animationType:typeof a==`string`?a:`both`,initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:l,layoutAnchor:u})}function km(e){if(e)return e.options.allowProjection===!1?km(e.parent):e.projection}function Am(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&$p(r);let o=n?n===`svg`:gm(e),s=o?Sm:xm;function c(n,c){let l,u={...(0,a.useContext)(Ip),...n,layoutId:jm(n)},{isStatic:d,isValidProp:f}=u,p=nm(n),m=s(n,d);if(!d&&typeof window<`u`){Mm(u,r);let t=Nm(u);l=t.MeasureLayout,p.visualElement=Dm(e,m,u,i,t.ProjectionNode,o)}return(0,M.jsxs)(em.Provider,{value:p,children:[l&&p.visualElement?(0,M.jsx)(l,{visualElement:p.visualElement,...u}):null,_m(e,n,wm(m,p.visualElement,c),m,d,t,o,f)]})}c.displayName=`motion.${typeof e==`string`?e:`create(${e.displayName??e.name??``})`}`;let l=(0,a.forwardRef)(c);return l[Cm]=e,l}function jm({layoutId:e}){let t=(0,a.useContext)(la).id;return t&&e!==void 0?t+`-`+e:e}function Mm(e,t){(0,a.useContext)(Jp).strict}function Nm(e){let{drag:t,layout:n}=Qp();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function Pm(e,t){if(typeof Proxy>`u`)return Am;let n=new Map,r=(n,r)=>Am(n,r,e,t);return new Proxy((e,t)=>r(e,t),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,Am(a,void 0,e,t)),n.get(a))})}var Fm=(e,t)=>t.isSVG??gm(e)?new Qd(t):new qd(t,{allowProjection:e!==a.Fragment}),Im=class extends Vd{constructor(e){super(e),e.animationState||=tf(e)}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();wd(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){let{animate:e}=this.node.getProps(),{animate:t}=this.node.prevProps||{};e!==t&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}},Lm=0,Rm={animation:{Feature:Im},exit:{Feature:class extends Vd{constructor(){super(...arguments),this.id=Lm++}update(){let{presenceContext:e,prevPresenceContext:t,animationState:n}=this.node;if(!e||!n)return;let{isPresent:r,onExitComplete:i}=e,a=t?.isPresent;if(r===a)return;if(r&&a===!1){if(this.exit===!0){let{initial:e}=this.node.getProps();if(e&&!Array.isArray(e)){let{transition:t,transitionEnd:n,...r}=Ml(this.node,e)||{};for(let e in r)this.node.getValue(e)?.jump(r[e])}this.node.blockInitialAnimation=!1,n.reset(),n.animateChanges()}else n.setActive(`exit`,!1);this.exit=void 0;return}let o=this.exit=n.setActive(`exit`,!r);i&&!r&&o.then(()=>{this.exit===o&&(this.exit=!0,i(this.id))})}mount(){let{register:e,onExitComplete:t}=this.node.presenceContext||{};t&&t(this.id),e&&(this.unmount=e(this.id))}unmount(){}}}};function zm(e){return{point:{x:e.pageX,y:e.pageY}}}var Bm=e=>t=>Gu(t)&&e(t,zm(t));function Vm(e,t,n,r){return Wf(e,t,Bm(n),r)}var Hm=({current:e})=>e?e.ownerDocument.defaultView:null,Um=(e,t)=>Math.abs(e-t);function Wm(e,t){let n=Um(e.x,t.x),r=Um(e.y,t.y);return Math.sqrt(n**2+r**2)}var Gm=new Set([`auto`,`scroll`]),Km=class{constructor(e,t,{transformPagePoint:n,contextWindow:r=window,dragSnapToOrigin:i=!1,distanceThreshold:a=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=e=>{this.handleScroll(e.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.hasPendingMove=!1,this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=qm(this.lastRawMoveEventInfo,this.transformPagePoint));let e=Ym(this.lastMoveEventInfo,this.history),t=this.startEvent!==null,n=Wm(e.offset,{x:0,y:0})>=this.distanceThreshold;if(!t&&!n)return;let{point:r}=e;this.history.push({...r,timestamp:z.now()});let{onStart:i,onMove:a}=this.handlers;t||(i&&i(this.lastMoveEvent,e),this.startEvent=this.lastMoveEvent),a&&a(this.lastMoveEvent,e)},this.handlePointerMove=(e,t)=>{this.lastMoveEvent=e,this.lastRawMoveEventInfo=t,this.lastMoveEventInfo=qm(t,this.transformPagePoint),this.hasPendingMove=!0,G.update(this.updatePoint,!0)},this.handlePointerUp=(e,t)=>{this.hasPendingMove&&this.updatePoint(),this.end();let{onEnd:n,onSessionEnd:r,resumeAnimation:i}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&i&&i(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;let a=Ym(e.type===`pointercancel`?this.lastMoveEventInfo:qm(t,this.transformPagePoint),this.history);this.startEvent&&n&&n(e,a),r&&r(e,a)},!Gu(e))return;this.dragSnapToOrigin=i,this.handlers=t,this.transformPagePoint=n,this.distanceThreshold=a,this.contextWindow=r||window;let s=qm(zm(e),this.transformPagePoint),{point:c}=s,{timestamp:l}=R;this.history=[{...c,timestamp:l}];let{onSessionStart:u}=t;u&&u(e,Ym(s,this.history));let d={passive:!0,capture:!0};this.removeListeners=xa(Vm(this.contextWindow,`pointermove`,this.handlePointerMove,d),Vm(this.contextWindow,`pointerup`,this.handlePointerUp,d),Vm(this.contextWindow,`pointercancel`,this.handlePointerUp,d)),o&&this.startScrollTracking(o)}startScrollTracking(e){let t=e.parentElement;for(;t;){let e=getComputedStyle(t);(Gm.has(e.overflowX)||Gm.has(e.overflowY))&&this.scrollPositions.set(t,{x:t.scrollLeft,y:t.scrollTop}),t=t.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.addEventListener(`scroll`,this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.removeEventListener(`scroll`,this.onWindowScroll)}}handleScroll(e){let t=this.scrollPositions.get(e);if(!t)return;let n=e===window,r=n?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},i={x:r.x-t.x,y:r.y-t.y};(i.x!==0||i.y!==0)&&(n?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(e,r),G.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),os(this.updatePoint)}};function qm(e,t){return t?{point:t(e.point)}:e}function Jm(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Ym({point:e},t){return{point:e,delta:Jm(e,Zm(t)),offset:Jm(e,Xm(t)),velocity:Qm(t,.1)}}function Xm(e){return e[0]}function Zm(e){return e[e.length-1]}function Qm(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null,i=Zm(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>I(t)));)n--;if(!r)return{x:0,y:0};r===e[0]&&e.length>2&&i.timestamp-r.timestamp>I(t)*2&&(r=e[1]);let a=L(i.timestamp-r.timestamp);if(a===0)return{x:0,y:0};let o={x:(i.x-r.x)/a,y:(i.y-r.y)/a};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function $m(e,{min:t,max:n},r){return t!==void 0&&e<t?e=r?W(t,e,r.min):Math.max(e,t):n!==void 0&&e>n&&(e=r?W(n,e,r.max):Math.min(e,n)),e}function eh(e,t,n){return{min:t===void 0?void 0:e.min+t,max:n===void 0?void 0:e.max+n-(e.max-e.min)}}function th(e,{top:t,left:n,bottom:r,right:i}){return{x:eh(e.x,n,i),y:eh(e.y,t,r)}}function nh(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,r]=[r,n]),{min:n,max:r}}function rh(e,t){return{x:nh(e.x,t.x),y:nh(e.y,t.y)}}function ih(e,t){let n=.5,r=Q(e),i=Q(t);return i>r?n=Sa(t.min,t.max-r,e.min):r>i&&(n=Sa(e.min,e.max-i,t.min)),N(0,1,n)}function ah(e,t){let n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}var oh=.35;function sh(e=oh){return e===!1?e=0:e===!0&&(e=oh),{x:ch(e,`left`,`right`),y:ch(e,`top`,`bottom`)}}function ch(e,t,n){return{min:lh(e,t),max:lh(e,n)}}function lh(e,t){return typeof e==`number`?e:e[t]||0}var uh=new WeakMap,dh=class{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=X(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:t=!1,distanceThreshold:n}={}){let{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;let i=e=>{t&&this.snapToCursor(e),this.stopAnimation()},a=(e,t)=>{let{drag:n,dragPropagation:r,onDragStart:i}=this.getProps();if(n&&!r&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Bu(n),!this.openDragLock))return;this.latestPointerEvent=e,this.latestPanInfo=t,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),$(e=>{let t=this.getAxisMotionValue(e).get()||0;if(B.test(t)){let{projection:n}=this.visualElement;if(n&&n.layout){let r=n.layout.layoutBox[e];r&&(t=Q(r)*(parseFloat(t)/100))}}this.originPoint[e]=t}),i&&G.update(()=>i(e,t),!1,!0),Bl(this.visualElement,`transform`);let{animationState:a}=this.visualElement;a&&a.setActive(`whileDrag`,!0)},o=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t;let{dragPropagation:n,dragDirectionLock:r,onDirectionLock:i,onDrag:a}=this.getProps();if(!n&&!this.openDragLock)return;let{offset:o}=t;r&&this.currentDirection===null?(this.currentDirection=hh(o),this.currentDirection!==null&&i&&i(this.currentDirection)):(this.updateAxis(`x`,t.point,o),this.updateAxis(`y`,t.point,o),this.visualElement.render(),a&&G.update(()=>a(e,t),!1,!0))},s=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t,this.stop(e,t),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>{let{dragSnapToOrigin:e}=this.getProps();(e||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:l}=this.getProps();this.panSession=new Km(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:s,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:n,contextWindow:Hm(this.visualElement),element:this.visualElement.current})}stop(e,t){let n=e||this.latestPointerEvent,r=t||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!r||!n)return;let{velocity:a}=r;this.startAnimation(a);let{onDragEnd:o}=this.getProps();o&&G.postRender(()=>o(n,r))}cancel(){this.isDragging=!1;let{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();let{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive(`whileDrag`,!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,t,n){let{drag:r}=this.getProps();if(!n||!mh(e,r,this.currentDirection))return;let i=this.getAxisMotionValue(e),a=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(a=$m(a,this.constraints[e],this.elastic[e])),i.set(a)}resolveConstraints(){let{dragConstraints:e,dragElastic:t}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;e&&Em(e)?this.constraints||=this.resolveRefConstraints():this.constraints=e&&n?th(n.layoutBox,e):!1,this.elastic=sh(t),r!==this.constraints&&!Em(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&$(e=>{this.constraints!==!1&&this.getAxisMotionValue(e)&&(this.constraints[e]=ah(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){let{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!Em(e))return!1;let n=e.current,{projection:r}=this.visualElement;if(!r||!r.layout)return!1;r.root&&(r.root.scroll=void 0,r.root.updateScroll());let i=Iu(n,r.root,this.visualElement.getTransformPagePoint()),a=rh(r.layout.layoutBox,i);if(t){let e=t(vu(a));this.hasMutatedConstraints=!!e,e&&(a=_u(e))}return a}startAnimation(e){let{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),s=this.constraints||{},c=$(o=>{if(!mh(o,t,this.currentDirection))return;let c=s&&s[o]||{};(a===!0||a===o)&&(c={min:0,max:0});let l=r?200:1e6,u=r?40:1e7,d={type:`inertia`,velocity:n?e[o]:0,bounceStiffness:l,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...c};return this.startAxisValueAnimation(o,d)});return Promise.all(c).then(o)}startAxisValueAnimation(e,t){let n=this.getAxisMotionValue(e);return Bl(this.visualElement,e),n.start(El(e,n,0,t,this.visualElement,!1))}stopAnimation(){$(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){let t=`_drag${e.toUpperCase()}`;return this.visualElement.getProps()[t]||this.visualElement.getValue(e,this.visualElement.latestValues[e]??0)}snapToCursor({clientX:e,clientY:t}){let{drag:n}=this.getProps(),r={x:e,y:t},i=this.visualElement.getTransformPagePoint()?.(r)||r,a=this.visualElement.measureViewportBox();$(e=>{if(!mh(e,n,this.currentDirection))return;let t=this.getAxisMotionValue(e),{min:r,max:o}=a[e];t.set((t.get()||0)+i[e]-W(r,o,.5))})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;let{drag:e,dragConstraints:t}=this.getProps(),{projection:n}=this.visualElement;if(!Em(t)||!n||!this.constraints)return;this.stopAnimation();let r=this.constraints,i={x:0,y:0};$(e=>{let t=this.getAxisMotionValue(e).get();i[e]=ih({min:t,max:t},r[e])});let{transformTemplate:a}=this.visualElement.getProps();this.visualElement.current.style.transform=a?a({},``):`none`,n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),$(t=>{let n=this.getAxisMotionValue(t);if(!mh(t,e,null)||!n.get())return;let{min:r,max:a}=this.constraints[t];n.set(W(r,a,i[t]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;uh.set(this.visualElement,this);let e=this.visualElement.current,t=Vm(e,`pointerdown`,t=>{let{drag:n,dragListener:r=!0}=this.getProps(),i=t.target,a=i!==e&&Yu(i);n&&r&&!a&&this.start(t)}),n,r=()=>{let{dragConstraints:t}=this.getProps();Em(t)&&t.current&&(this.constraints=this.resolveRefConstraints(),n||=ph(e,t.current,()=>this.scalePositionWithinConstraints()))},{projection:i}=this.visualElement,a=i.addEventListener(`measure`,r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),G.read(r);let o=Wf(window,`resize`,()=>this.scalePositionWithinConstraints()),s=i.addEventListener(`didUpdate`,(({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&($(t=>{let n=this.getAxisMotionValue(t);n&&(this.originPoint[t]+=e[t].translate,n.set(n.get()+e[t].translate))}),this.visualElement.render())}));return()=>{o(),t(),a(),s&&s(),n&&n()}}getProps(){let e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:n=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:a=oh,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:o}}};function fh(e){let t=!0;return()=>{t?t=!1:e()}}function ph(e,t,n){let r=gd(e,fh(n)),i=gd(t,fh(n));return()=>{r(),i()}}function mh(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function hh(e,t=10){let n=null;return Math.abs(e.y)>t?n=`y`:Math.abs(e.x)>t&&(n=`x`),n}var gh=class extends Vd{constructor(e){super(e),this.removeGroupControls=F,this.removeListeners=F,this.controls=new dh(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||F}update(){let{dragControls:e}=this.node.getProps(),{dragControls:t}=this.node.prevProps||{};e!==t&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}},_h=e=>(t,n)=>{e&&G.update(()=>e(t,n),!1,!0)},vh=class extends Vd{constructor(){super(...arguments),this.removePointerDownListener=F}onPointerDown(e){this.session=new Km(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Hm(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:_h(e),onStart:_h(t),onMove:_h(n),onEnd:(e,t)=>{delete this.session,r&&G.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=Vm(this.node.current,`pointerdown`,e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}},yh=!1,bh=class extends a.Component{componentDidMount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n,layoutId:r}=this.props,{projection:i}=e;i&&(t.group&&t.group.add(i),n&&n.register&&r&&n.register(i),yh&&i.root.didUpdate(),i.addEventListener(`animationComplete`,()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Zf.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){let{layoutDependency:t,visualElement:n,drag:r,isPresent:i}=this.props,{projection:a}=n;return a&&(a.isPresent=i,e.layoutDependency!==t&&a.setOptions({...a.options,layoutDependency:t}),yh=!0,r||e.layoutDependency!==t||t===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||G.postRender(()=>{let e=a.getStack();(!e||!e.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){let{visualElement:e,layoutAnchor:t}=this.props,{projection:n}=e;n&&(n.options.layoutAnchor=t,n.root.didUpdate(),Lu.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;yh=!0,r&&(r.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(r),n&&n.deregister&&n.deregister(r))}safeToRemove(){let{safeToRemove:e}=this.props;e&&e()}render(){return null}};function xh(e){let[t,n]=Wp(),r=(0,a.useContext)(la);return(0,M.jsx)(bh,{...e,layoutGroup:r,switchLayoutGroup:(0,a.useContext)(Tm),isPresent:t,safeToRemove:n})}var Sh={pan:{Feature:vh},drag:{Feature:gh,ProjectionNode:Fp,MeasureLayout:xh}};function Ch(e,t,n){let{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive(`whileHover`,n===`Start`);let i=r[`onHover`+n];i&&G.postRender(()=>i(t,zm(t)))}var wh=class extends Vd{mount(){let{current:e}=this.node;e&&(this.unmount=Uu(e,(e,t)=>(Ch(this.node,t,`Start`),e=>Ch(this.node,e,`End`))))}unmount(){}},Th=class extends Vd{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(`:focus-visible`)}catch{e=!0}e&&this.node.animationState&&(this.node.animationState.setActive(`whileFocus`,!0),this.isActive=!0)}onBlur(){this.isActive&&this.node.animationState&&(this.node.animationState.setActive(`whileFocus`,!1),this.isActive=!1)}mount(){this.unmount=xa(Wf(this.node.current,`focus`,()=>this.onFocus()),Wf(this.node.current,`blur`,()=>this.onBlur()))}unmount(){}};function Eh(e,t,n){let{props:r}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&r.whileTap&&e.animationState.setActive(`whileTap`,n===`Start`);let i=r[`onTap`+(n===`End`?``:n)];i&&G.postRender(()=>i(t,zm(t)))}var Dh=class extends Vd{mount(){let{current:e}=this.node;if(!e)return;let{globalTapTarget:t,propagate:n}=this.node.props;this.unmount=nd(e,(e,t)=>(Eh(this.node,t,`Start`),(e,{success:t})=>Eh(this.node,e,t?`End`:`Cancel`)),{useGlobalTarget:t,stopPropagation:n?.tap===!1})}unmount(){}},Oh=new WeakMap,kh=new WeakMap,Ah=e=>{let t=Oh.get(e.target);t&&t(e)},jh=e=>{e.forEach(Ah)};function Mh({root:e,...t}){let n=e||document;kh.has(n)||kh.set(n,{});let r=kh.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(jh,{root:e,...t})),r[i]}function Nh(e,t,n){let r=Mh(t);return Oh.set(e,n),r.observe(e),()=>{Oh.delete(e),r.unobserve(e)}}var Ph={some:0,all:1},Fh=class extends Vd{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();let{viewport:e={}}=this.node.getProps(),{root:t,margin:n,amount:r=`some`,once:i}=e,a={root:t?t.current:void 0,rootMargin:n,threshold:typeof r==`number`?r:Ph[r]},o=e=>{let{isIntersecting:t}=e;if(this.isInView===t||(this.isInView=t,i&&!t&&this.hasEnteredView))return;t&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(`whileInView`,t);let{onViewportEnter:n,onViewportLeave:r}=this.node.getProps(),a=t?n:r;a&&a(e)};this.stopObserver=Nh(this.node.current,a,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>`u`)return;let{props:e,prevProps:t}=this.node;[`amount`,`margin`,`root`].some(Ih(e,t))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}};function Ih({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}var Lh={inView:{Feature:Fh},tap:{Feature:Dh},focus:{Feature:Th},hover:{Feature:wh}},Rh={layout:{ProjectionNode:Fp,MeasureLayout:xh}},zh=Pm({...Rm,...Lh,...Sh,...Rh},Fm),Bh=e=>e?.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase();function Vh(e,t,n=[]){if(t==null)throw Error(`[lucide]: iconNode is required when icon name is used`);return{name:Bh(e),size:24,node:t,...n.length>0?{aliases:n}:{}}}var Hh=e=>{let t=``,n=!1;for(let r of e)r===`-`||r===`_`||r<=` `?n=t.length>0:(t.length===0?t+=r.toLowerCase():t+=n?r.toUpperCase():r,n=!1);return t},Uh=e=>{let t=Hh(e);return t.charAt(0).toUpperCase()+t.slice(1)},Wh=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),Gh={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":2,"stroke-linecap":`round`,"stroke-linejoin":`round`};function Kh(e){return e!=null}function qh(e,t={}){let n=t.attributeNames??{},r=e=>n[e]??e,i=e.size??e.width??Gh.width,a=e.size??e.height??Gh.height,o=e.aliases?.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>`lucide-${e}`)??[],s=[...e.name?[`lucide-${e.name}`]:[],...o],c=t.className?.split(` `).filter(Boolean)??[],l=t.includeDefaultClasses===!1?Wh(...c):Wh(`lucide`,...s,...c),u=t.absoluteStrokeWidth?Number(t.strokeWidth??Gh[`stroke-width`])*Number(e.size??e.width??Gh.width)/Number(t.size??t.width??Gh.width):t.strokeWidth??Gh[`stroke-width`];return[`svg`,{...Object.entries(Gh).reduce((e,[t,n])=>(e[r(t)]=n,e),{}),...`color`in t&&t.color&&{[r(`stroke`)]:t.color},...`size`in t&&Kh(t.size)&&{[r(`width`)]:t.size,[r(`height`)]:t.size},...`width`in t&&Kh(t.width)&&{[r(`width`)]:t.width},...`height`in t&&Kh(t.height)&&{[r(`height`)]:t.height},[r(`stroke-width`)]:u,...l&&{[r(`class`)]:l},[r(`viewBox`)]:`0 0 ${i} ${a}`,...t.hasA11yProp===!1?{[r(`aria-hidden`)]:`true`}:{},...`attributes`in t&&t.attributes},e.node.map(e=>{let[n,i,a]=e,o=t.nonScalingStroke?{[r(`vector-effect`)]:`non-scaling-stroke`,...i}:i;return a?[n,o,a]:[n,o]})]}function Jh(e,t={}){return qh(e,{...t,attributeNames:{...t.attributeNames,class:`className`,"stroke-width":`strokeWidth`,"stroke-linecap":`strokeLinecap`,"stroke-linejoin":`strokeLinejoin`,"vector-effect":`vectorEffect`}})}var Yh=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},Xh=(0,a.createContext)({}),Zh=()=>(0,a.useContext)(Xh),Qh=(0,a.forwardRef)(({color:e,size:t,width:n,height:r,strokeWidth:i,absoluteStrokeWidth:o,nonScalingStroke:s,className:c=``,children:l,iconNode:u=[],icon:d={node:u,aliases:[],size:24},...f},p)=>{let{size:m=24,strokeWidth:h=2,absoluteStrokeWidth:g=!1,nonScalingStroke:_=!1,color:v=`currentColor`,className:y=``}=Zh()??{},b=!!l||Yh(f),[x,S,ee=[]]=Jh(d,{color:e??v,width:n??t??m,height:r??t??m,strokeWidth:i??h,absoluteStrokeWidth:o??g,nonScalingStroke:s??_,className:Wh(y,c),hasA11yProp:b,attributes:f});return(0,a.createElement)(x,{ref:p,...S},[...ee.map(([e,t])=>(0,a.createElement)(e,t)),...Array.isArray(l)?l:[l]])});function $h(e,t=[],n=[]){let r=typeof e==`string`?Vh(e,t,n):e,i=(0,a.forwardRef)(({className:e,...t},n)=>(0,a.createElement)(Qh,{ref:n,icon:r,className:e,...t}));return r.name&&(i.displayName=Uh(r.name)),i}var eg={name:`check`,size:24,node:[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]};eg.node;var tg=$h(eg),ng={name:`x`,size:24,node:[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]};ng.node;var rg=$h(ng),ig={primary:`bg-fg text-inverse hover:bg-fg/90 shadow-[inset_0_1px_0_rgba(255,255,255,.12)]`,secondary:`bg-raised text-fg ring-1 ring-inset ring-line-strong hover:bg-hover hover:ring-line-strong`,ghost:`text-fg-2 hover:text-fg hover:bg-hover`,human:`bg-human text-[#1b1203] hover:brightness-105`,ai:`bg-ai-soft text-ai-fg ring-1 ring-inset ring-ai-line/40 hover:bg-ai-soft/80`,danger:`text-bad hover:bg-bad-soft`,ok:`bg-ok text-inverse hover:brightness-105`},ag={xs:`h-6 px-2 text-[11.5px] gap-1 rounded-[6px]`,sm:`h-7 px-2.5 text-[12.5px] gap-1.5 rounded-[7px]`,md:`h-8 px-3 text-[13px] gap-2 rounded-[8px]`},og=(0,a.forwardRef)(function({variant:e=`secondary`,size:t=`sm`,icon:n,kbd:i,className:a,children:o,...s},c){return(0,M.jsxs)(`button`,{ref:c,"data-hand":!0,className:r(`inline-flex shrink-0 select-none items-center justify-center whitespace-nowrap font-medium transition-[background-color,color,box-shadow,filter] duration-150 disabled:pointer-events-none disabled:opacity-45 [&_svg]:size-[14px] [&_svg]:shrink-0`,ig[e],ag[t],a),...s,children:[n,o,i]})}),sg=(0,a.forwardRef)(function({className:e,active:t,size:n=`md`,...i},a){return(0,M.jsx)(`button`,{ref:a,"data-hand":!0,className:r(`inline-flex shrink-0 select-none items-center justify-center rounded-[7px] text-fg-2 transition-colors duration-150 hover:bg-hover hover:text-fg disabled:pointer-events-none disabled:opacity-40 [&_svg]:size-[15px]`,n===`md`?`size-8`:`size-7 [&_svg]:size-[14px]`,t&&`bg-active text-fg`,e),...i})});export{Ir as $,$s as A,x as At,Sa as B,gl as C,S as Ct,yc as D,oe as Dt,vc as E,ce as Et,G as F,ua as G,ga as H,W as I,qi as J,ca as K,za as L,Ds as M,h as Mt,Cs as N,c as Nt,gc as O,re as Ot,fs as P,k as Q,Oa as R,hl as S,se as St,Ic as T,ie as Tt,ha as U,va as V,ma as W,Bi as X,Ji as Y,A as Z,nu as _,we as _t,$h as a,yr as at,Pl as b,ae as bt,Ip as c,Jn as ct,Fu as d,$n as dt,Er as et,hu as f,Yn as ft,iu as g,bt as gt,au as h,Ft as ht,tg as i,E as it,Os as j,g as jt,ec as k,le as kt,Uf as l,Xn as lt,ou as m,sn as mt,sg as n,Ar as nt,zh as o,qn as ot,su as p,un as pt,Xi as q,rg as r,Or as rt,qp as s,er as st,og as t,Dr as tt,Cd as u,Kn as ut,Vl as v,ye as vt,Kc as w,ne as wt,El as x,ue as xt,q as y,de as yt,I as z};