ryugi-artifacts 1.108.7 → 1.110.1

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 (142) hide show
  1. package/dist/cli.cjs +210 -352
  2. package/dist/document-engine.cjs +1160 -301
  3. package/dist/loro_wasm_bg.wasm +0 -0
  4. package/dist/output-bootstrap.cjs +6 -3
  5. package/dist/runtime/icons/a.json +1 -0
  6. package/dist/runtime/icons/b.json +1 -0
  7. package/dist/runtime/icons/c.json +1 -0
  8. package/dist/runtime/icons/d.json +1 -0
  9. package/dist/runtime/icons/e.json +1 -0
  10. package/dist/runtime/icons/f.json +1 -0
  11. package/dist/runtime/icons/g.json +1 -0
  12. package/dist/runtime/icons/h.json +1 -0
  13. package/dist/runtime/icons/i.json +1 -0
  14. package/dist/runtime/icons/index.json +1 -0
  15. package/dist/runtime/icons/j.json +1 -0
  16. package/dist/runtime/icons/k.json +1 -0
  17. package/dist/runtime/icons/l.json +1 -0
  18. package/dist/runtime/icons/m.json +1 -0
  19. package/dist/runtime/icons/n.json +1 -0
  20. package/dist/runtime/icons/o.json +1 -0
  21. package/dist/runtime/icons/p.json +1 -0
  22. package/dist/runtime/icons/q.json +1 -0
  23. package/dist/runtime/icons/r.json +1 -0
  24. package/dist/runtime/icons/s.json +1 -0
  25. package/dist/runtime/icons/t.json +1 -0
  26. package/dist/runtime/icons/u.json +1 -0
  27. package/dist/runtime/icons/v.json +1 -0
  28. package/dist/runtime/icons/w.json +1 -0
  29. package/dist/runtime/icons/x.json +1 -0
  30. package/dist/runtime/icons/z.json +1 -0
  31. package/dist/runtime/ryugi-icons.js +1 -1
  32. package/dist/viewer/{AgentDock-fdzdI0YU.js → AgentDock-6un7g6EW.js} +1 -1
  33. package/dist/viewer/ArtboardLayout-DcLjfTW5.js +14 -0
  34. package/dist/viewer/{ArtifactList-D1Cv2wcz.js → ArtifactList-CguprV5S.js} +1 -1
  35. package/dist/viewer/{ArtifactModal-BRPuHjh3.js → ArtifactModal-BthavXPQ.js} +1 -1
  36. package/dist/viewer/{BottomSheet-DksTxPPS.js → BottomSheet-BFmMmz0e.js} +1 -1
  37. package/dist/viewer/Canvas-BQvfuFH9.js +1 -0
  38. package/dist/viewer/{CommentPopover-Bz3qXsBS.js → CommentPopover-wKdHWvEk.js} +1 -1
  39. package/dist/viewer/{DocumentExportMenu-Cb03PJdE.js → DocumentExportMenu-DXQAge-h.js} +1 -1
  40. package/dist/viewer/DocumentLayout-DPB6Byav.js +2 -0
  41. package/dist/viewer/DocumentPage-BStsS6oE.js +3 -0
  42. package/dist/viewer/{DraggablePanel-BlNQ_JOj.js → DraggablePanel-WnQa4WqJ.js} +1 -1
  43. package/dist/viewer/{DropdownMenu-DhVZ3e22.js → DropdownMenu-C-RgiXH5.js} +1 -1
  44. package/dist/viewer/{GroupVerdict-DkOR7Neo.js → GroupVerdict-BhUpCp5w.js} +1 -1
  45. package/dist/viewer/{HtmlLayout-BQS68lEe.js → HtmlLayout-Ykt8uvx5.js} +1 -1
  46. package/dist/viewer/{Input-YumXWTse.js → Input-C1Nrx6NW.js} +1 -1
  47. package/dist/viewer/{MenuSubmenuTrigger-DZ2Nb6Hm.js → MenuSubmenuTrigger-C3Y6EJ1a.js} +1 -1
  48. package/dist/viewer/{PhoneArtboardBar-CZKL18gK.js → PhoneArtboardBar-BMkMYKEH.js} +1 -1
  49. package/dist/viewer/{Popover-i0m3nwq7.js → Popover-cB2rLdue.js} +1 -1
  50. package/dist/viewer/{PreviewArtifactLayout-B4SZfLvw.js → PreviewArtifactLayout-H6NV96nq.js} +1 -1
  51. package/dist/viewer/{PreviewLayout-DiIQthoy.js → PreviewLayout-CFXMPAXR.js} +2 -2
  52. package/dist/viewer/{ReportLayout-DPnqWYPZ.js → ReportLayout-gDr83HaK.js} +1 -1
  53. package/dist/viewer/{RyugiMark-Ch2tF00h.js → RyugiMark-BxkKQ5lq.js} +1 -1
  54. package/dist/viewer/{Segmented-BV_iofkK.js → Segmented-Beqk813u.js} +1 -1
  55. package/dist/viewer/{SelectScrollUpArrow-BNSyHMPX.js → SelectScrollUpArrow-DuDh2HJ_.js} +1 -1
  56. package/dist/viewer/{SlidesLayout-CSeSindR.js → SlidesLayout-CWZjcfO3.js} +3 -3
  57. package/dist/viewer/{SnapshotDocument-TIzAsI0l.js → SnapshotDocument-B2cxzqyH.js} +1 -1
  58. package/dist/viewer/{SplitFrame-C3Mr0Ehv.js → SplitFrame-Czb4TISP.js} +1 -1
  59. package/dist/viewer/{StoryboardLayout-DZVJbnzc.js → StoryboardLayout-C1AqDRge.js} +1 -1
  60. package/dist/viewer/{StoryboardRender-DORxY44d.js → StoryboardRender-0BHiMypp.js} +1 -1
  61. package/dist/viewer/{ThreadView-CbKzFwUf.js → ThreadView-C7soHy8_.js} +1 -1
  62. package/dist/viewer/{Tooltip-81DgA1Zr.js → Tooltip-B0Ehf6Z5.js} +1 -1
  63. package/dist/viewer/{VerifyLayout--deiRi4o.js → VerifyLayout-9xD_W0-c.js} +1 -1
  64. package/dist/viewer/{VirtualizedEditor-uWe43zaI-1EQ0fdB8.js → VirtualizedEditor-uWe43zaI-DT4GAFpm.js} +1 -1
  65. package/dist/viewer/{VirtualizedRenderer-C_d95FXi-CixG8E4F.js → VirtualizedRenderer-C_d95FXi-ealkku86.js} +1 -1
  66. package/dist/viewer/{WarningsBadge-fEXkyk3t.js → WarningsBadge-BbJdjQpt.js} +1 -1
  67. package/dist/viewer/{WhiteboardEditor-cZ32fLqJ-BRt-wSEn.js → WhiteboardEditor-cZ32fLqJ-BfKRGbqm.js} +1 -1
  68. package/dist/viewer/{WhiteboardLayout-qGm-CExy.js → WhiteboardLayout-C-RLaui_.js} +1 -1
  69. package/dist/viewer/{WritingCursor-OdCSWg_M.js → WritingCursor-oPoIsKUb.js} +1 -1
  70. package/dist/viewer/{agentLook-EhrjbD1n.js → agentLook-D4riQJ8C.js} +1 -1
  71. package/dist/viewer/{artifact-list-D22lTyyh.js → artifact-list-CpPtgMEK.js} +1 -1
  72. package/dist/viewer/{auto-publish-BXmqx8BX.js → auto-publish-DVEHOTT5.js} +1 -1
  73. package/dist/viewer/channel-CVsrQP9s.js +4 -0
  74. package/dist/viewer/{crop-encode-Udgh8S7r.js → crop-encode-hNMFMj6m.js} +1 -1
  75. package/dist/viewer/{dist-DRmbQ1f0.js → dist--v3nH0C2.js} +1 -1
  76. package/dist/viewer/{dist-o-mpdm3Q.js → dist-B0ILD5bC.js} +1 -1
  77. package/dist/viewer/{dist-BNiHzkc8.js → dist-BHWbRf2s.js} +1 -1
  78. package/dist/viewer/{dist-R6N8uqUg.js → dist-BVmgdxIk.js} +1 -1
  79. package/dist/viewer/{dist-vjczWTJX.js → dist-Bqxw-VPi.js} +1 -1
  80. package/dist/viewer/{dist-C0Fbwkds.js → dist-CAMOMDy7.js} +1 -1
  81. package/dist/viewer/{dist-G4Vj4mFX.js → dist-CIggNRs9.js} +1 -1
  82. package/dist/viewer/{dist-DurHsNXj.js → dist-CKyjD35S.js} +1 -1
  83. package/dist/viewer/{dist-DD00JDtU.js → dist-CLk1Bth7.js} +1 -1
  84. package/dist/viewer/{dist-i-_vhfnL.js → dist-CNxdwhOg.js} +1 -1
  85. package/dist/viewer/{dist-B-RrlmaY.js → dist-CQ22WAIU.js} +1 -1
  86. package/dist/viewer/{dist-DKWARfq1.js → dist-CRi3Ep6t.js} +1 -1
  87. package/dist/viewer/{dist-rs8SY6NP.js → dist-CWG86Qx7.js} +1 -1
  88. package/dist/viewer/{dist-C4fPBi1f.js → dist-CyGunPGS.js} +1 -1
  89. package/dist/viewer/{dist-CjVeWopx.js → dist-DHHkE5Pc.js} +1 -1
  90. package/dist/viewer/{dist-CuWYFfBf.js → dist-DN1H79Ip.js} +1 -1
  91. package/dist/viewer/{dist-kzNj8Wks.js → dist-DXt-rGJU.js} +1 -1
  92. package/dist/viewer/{dist-DBnvEq5g.js → dist-Dc7UOYbo.js} +1 -1
  93. package/dist/viewer/dist-DiSjof8e.js +1 -0
  94. package/dist/viewer/{dist-DzmIJXNR.js → dist-Dk6bIGuf.js} +1 -1
  95. package/dist/viewer/{dist-DRUJxMS6.js → dist-DmKVt1TO.js} +1 -1
  96. package/dist/viewer/{dist-0JlH-iFk.js → dist-DuQFs8bS.js} +1 -1
  97. package/dist/viewer/{dist-C81vCo2L.js → dist-E38Xe3MQ.js} +1 -1
  98. package/dist/viewer/{dist-BMJWStKC.js → dist-H8MUbNB6.js} +1 -1
  99. package/dist/viewer/{editor-BabkJ7hH.js → editor-B_dmAT7r.js} +5 -5
  100. package/dist/viewer/fit-Dy3EIsBE.js +1 -0
  101. package/dist/viewer/{icons-8mizjIXE.js → icons-BurfZgbO.js} +1 -1
  102. package/dist/viewer/{imperative-iclc26pT.js → imperative-Cgz8hoz-.js} +1 -1
  103. package/dist/viewer/index.html +13 -13
  104. package/dist/viewer/index.js +2 -2
  105. package/dist/viewer/index4.css +1 -1
  106. package/dist/viewer/index5.css +4 -0
  107. package/dist/viewer/{local-DzHVL3fo.js → local-DXaScWD4.js} +1 -1
  108. package/dist/viewer/{local-split-host-DaeACaX5.js → local-split-host--Swu-YgH.js} +1 -1
  109. package/dist/viewer/plugin-_bGVeqI0-CTywTig9.js +2 -0
  110. package/dist/viewer/preview.html +4 -4
  111. package/dist/viewer/preview.js +1 -1
  112. package/dist/viewer/{printDocument-Bh1qUAf9.js → printDocument-CC2oNEVO.js} +1 -1
  113. package/dist/viewer/{ref-JbqCEGXp.js → ref-B-yJaA1I.js} +1 -1
  114. package/dist/viewer/{route-DdpUUY_w.js → route-McOpomU2.js} +4 -4
  115. package/dist/viewer/{route-messages-BMv2jmvl.js → route-messages-CVVJCGbw.js} +1 -1
  116. package/dist/viewer/{settings-wKTRexHi.js → settings-CiU-sro0.js} +1 -1
  117. package/dist/viewer/{snap-1DJNMR4r.js → snap-Dxg6-ulS.js} +1 -1
  118. package/dist/viewer/split-Dnd6CUMX.js +2 -0
  119. package/dist/viewer/{stable-CZy_447C.js → stable-D0V-nxn7.js} +1 -1
  120. package/dist/viewer/{styles-BHI9FTnz.js → styles-B6PpuJxT.js} +1 -1
  121. package/dist/viewer/{transport-Djlo7-HU.js → transport-Cs-vGiPz.js} +1 -1
  122. package/dist/viewer/types-BCsOeYI6.js +1 -0
  123. package/dist/viewer/{url-B_fuREEU.js → url-BO9cF4cS.js} +1 -1
  124. package/dist/viewer/{useArtifactFeed-B9RfhN8_.js → useArtifactFeed-CeKgpdgq.js} +1 -1
  125. package/dist/viewer/{useArtifactSocket-ns9zjgVa.js → useArtifactSocket-Dp2OBZFo.js} +1 -1
  126. package/dist/viewer/{useLayerZIndex-VAxAVO-V.js → useLayerZIndex-DzJy6vhi.js} +1 -1
  127. package/dist/viewer/{useStoryboardData-DCPDhUMO.js → useStoryboardData-C7PSl2I4.js} +1 -1
  128. package/dist/viewer/{view-DLrABahQ.js → view-BQdRX9O6.js} +1 -1
  129. package/dist/viewer/{viewport-CFJHn_Y6-B0Ka3uWP.js → viewport-CFJHn_Y6-Cz8ocWMP.js} +1 -1
  130. package/package.json +6 -4
  131. package/dist/server.cjs +0 -995
  132. package/dist/viewer/ArtboardLayout-CyP7z5iV.js +0 -14
  133. package/dist/viewer/Canvas-DA9wKktu.js +0 -1
  134. package/dist/viewer/DocumentLayout-16zcY3cg.js +0 -2
  135. package/dist/viewer/DocumentPage-B__O7sY3.js +0 -3
  136. package/dist/viewer/channel-CaUFZV2H.js +0 -4
  137. package/dist/viewer/dist-CY11yEtD.js +0 -1
  138. package/dist/viewer/fit-BJ0VxRML.js +0 -1
  139. package/dist/viewer/plugin-_bGVeqI0-BkU-g6bb.js +0 -2
  140. package/dist/viewer/split-BJA_5Rtf.js +0 -2
  141. package/dist/viewer/split-C1umM5Fz.css +0 -1
  142. package/dist/viewer/types-DAs-xbqr.js +0 -1
package/dist/server.cjs DELETED
@@ -1,995 +0,0 @@
1
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let l=require("node:child_process"),u=require("node:crypto");u=c(u,1);let d=require("node:fs");d=c(d,1);let f=require("node:os");f=c(f,1);let p=require("node:path");p=c(p,1);let m=require("node:net");m=c(m,1);let h=require("node:util"),g=require("node:http");g=c(g,1);let _=require("node:stream"),v=require("node:async_hooks");var y=`1.108.7`,b=`31077431aaa1`;const x=e=>{let t=process.env.RYUGI_PROCESS_TAG?.trim();return`Ryugi ${e} (${y}${t?` · ${t}`:``})`},S=process.platform!==`win32`;function C(e,...t){S&&(process.title=[x(e),...t].join(` `))}const w=e=>S?[`--title=${x(e)}`]:[];function T(e=process.env,t=process.platform,n=process.getuid?.()??-1,r=f.default.tmpdir()){return e.RYUGI_RUNTIME_DIR?p.default.join(e.RYUGI_RUNTIME_DIR,`servers`):t===`win32`?p.default.join(r,`ryugi`,`servers`):`/tmp/ryugi-${n}/servers`}const E=/^[a-z][a-z0-9_-]{0,31}$/,D=/^(?!\.\.?$)(?!.*\.\.)[\w.:-]{1,128}$/;function O(e=process.env,t=process.platform){if(e.RYUGI_HUB_SOCKET)return e.RYUGI_HUB_SOCKET;let n=e.RYUGI_SERVER_HOME?p.default.resolve(e.RYUGI_SERVER_HOME):null,r=n&&n!==p.default.join(f.default.homedir(),`.ryugi`,`server`)?`-${(0,u.createHash)(`sha256`).update(n).digest(`hex`).slice(0,12)}`:``;return t===`win32`?`\\\\.\\pipe\\ryugi-hub-${f.default.userInfo().username}${r}`:p.default.join(p.default.dirname(T(e,t)),`hub${r}.sock`)}const k=e=>new Promise(t=>{let n=m.default.connect(e);n.once(`connect`,()=>{n.destroy(),t(!0)}),n.once(`error`,()=>t(!1))});async function A(e){if(process.platform===`win32`)return;let t=p.default.dirname(e);if(d.default.existsSync(t)||d.default.mkdirSync(t,{recursive:!0,mode:448}),d.default.existsSync(e)){if(await k(e))throw Error(`another hub owns the agent socket ${e}`);d.default.rmSync(e,{force:!0})}}async function j(e){await A(e.socketPath);let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set,r=1,i=(e,t)=>{e.destroyed||e.write(`${JSON.stringify(t)}\n`)},a=m.default.createServer(a=>{n.add(a);let o=null,s=``,c=n=>{if(o)n.t===`delivered`?e.onDelivered(o,{id:n.id}):n.t===`unsubscribe`&&e.onUnsubscribe?.(o);else{if(n.t!==`hello`)return a.destroy();if(n.protocol!==1)return i(a,{t:`refuse`,reason:`version`}),a.end();let{host:s,session:c,agent:l,version:u}=n;if(typeof s!=`string`||!E.test(s)||typeof c!=`string`||!D.test(c)||typeof l!=`string`||!l)return i(a,{t:`refuse`,reason:`hello`}),a.end();for(let[e,n]of t)e.host===s&&e.session===c&&(t.delete(e),i(n,{t:`bye`,reason:`replaced`}),n.end());o={id:r++,host:s,session:c,agent:l,version:typeof u==`string`?u:``},t.set(o,a),i(a,{t:`welcome`,version:e.version}),e.onHello(o)}};a.on(`data`,e=>{if(s+=e.toString(`utf8`),s.length>1048576)return a.destroy();for(let e=s.indexOf(`
2
- `);e>=0;e=s.indexOf(`
3
- `)){let t=s.slice(0,e);s=s.slice(e+1);let n;try{n=JSON.parse(t)}catch{return a.destroy()}n&&typeof n==`object`&&c(n)}}),a.on(`error`,()=>a.destroy()),a.on(`close`,()=>{n.delete(a),o&&t.get(o)===a&&(t.delete(o),e.onClose(o))})});return await new Promise((t,n)=>{a.once(`error`,n),a.listen(e.socketPath,()=>{a.off(`error`,n),t()})}),process.platform!==`win32`&&d.default.chmodSync(e.socketPath,384),{connections:()=>[...t.keys()],send:(e,n)=>{let r=t.get(e);r&&i(r,n)},close:()=>new Promise(t=>{for(let e of n)e.destroy();a.close(()=>{process.platform!==`win32`&&d.default.rmSync(e.socketPath,{force:!0}),t()})})}}const ee=[27319,27320,27321],M={html:`text/html; charset=utf-8`,js:`text/javascript; charset=utf-8`,mjs:`text/javascript; charset=utf-8`,css:`text/css; charset=utf-8`,json:`application/json; charset=utf-8`,xml:`application/xml; charset=utf-8`,txt:`text/plain; charset=utf-8`,svg:`image/svg+xml`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,ico:`image/x-icon`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,otf:`font/otf`,mp4:`video/mp4`,webm:`video/webm`},N=M.json;function P(e){let t=e.slice(Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`))+1),n=t.lastIndexOf(`.`);return n>0&&M[t.slice(n+1).toLowerCase()]||`application/octet-stream`}const F=()=>u.default.randomBytes(24).toString(`base64url`);function I(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&u.default.timingSafeEqual(n,r)}function L(e){let t={};for(let n of(e??``).split(`;`)){let e=n.indexOf(`=`);e>0&&(t[n.slice(0,e).trim()]=n.slice(e+1).trim())}return t}function te(e){try{return d.default.readFileSync(e,`utf8`).trim()}catch{return``}}function R(e,t,n){return new Promise((r,i)=>{let a=t=>{e.off(`listening`,o),i(t)},o=()=>{e.off(`error`,a),r(e.address().port)};e.once(`error`,a),e.once(`listening`,o),e.listen(n,t)})}const ne=e=>e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e;function z(e,t,n,r={}){e.writeHead(t,{"Referrer-Policy":`no-referrer`,"Cache-Control":`no-store`,...r}),e.end(n)}function B(e,t,n){z(e,t,JSON.stringify(n),{"Content-Type":N})}function re(e,t){let n=e&&/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!n||!n[1]&&!n[2])return null;let r=n[1]?Number(n[1]):Math.max(0,t-Number(n[2])),i=n[1]&&n[2]?Math.min(Number(n[2]),t-1):t-1;return r>i||r>=t?`unsatisfiable`:{start:r,end:i}}function ie(e,t,n={},r){d.default.stat(t,(i,a)=>{if(i||!a.isFile()){z(e,404,`Not found`);return}let o={"Referrer-Policy":`no-referrer`,"Cache-Control":`no-store`,"Content-Type":P(t),"Accept-Ranges":`bytes`,...n},s=re(r,a.size);s===`unsatisfiable`?(e.writeHead(416,{...o,"Content-Range":`bytes */${a.size}`}),e.end()):(s?e.writeHead(206,{...o,"Content-Range":`bytes ${s.start}-${s.end}/${a.size}`,"Content-Length":String(s.end-s.start+1)}):e.writeHead(200,{...o,"Content-Length":String(a.size)}),d.default.createReadStream(t,s??{}).on(`error`,()=>e.destroy()).pipe(e))})}const ae=[27329,27330,27331];function oe(e,t){let n=t===`main`?e.RYUGI_ARTIFACTS_PORTS:e.RYUGI_ARTIFACTS_BOARD_PORTS,r=t===`main`?ee:ae;if(!n)return r;let i=n.split(`,`).map(e=>Number(e.trim()));return i.length&&i.every(e=>Number.isInteger(e)&&e>=0&&e<65536)?i:r}async function se(e,t,n){for(let r of n)try{return await R(e,t,r)}catch(e){if(e.code!==`EADDRINUSE`)throw e}throw Error(`Ports ${n.join(`, `)} are all in use; pick a free one with --port <n>`)}const ce=e=>e===`127.0.0.1`||e===`localhost`||e===`::1`;function le(e,t=[]){let n=e.ARTIFACTS_HOST||`127.0.0.1`,r=e.ARTIFACTS_URL_HOST||(ce(n)?`localhost`:n),i=t.find(e=>e.startsWith(`--artifacts-server-id=`)),a=t.find(e=>e.startsWith(`--port=`)),o=a?Number(a.slice(7)):NaN;return{host:n,urlHost:r,ports:Number.isInteger(o)&&o>=0&&o<65536?[o]:oe(e,`main`),boardPorts:oe(e,`board`),openCmd:e.ARTIFACTS_OPEN_CMD||null,serverId:i?i.slice(22):null,cloudOrigin:(e.RYUGI_CLOUD_ORIGIN||`https://ryugi.innei.dev`).replace(/\/+$/,``)}}function V(e,t){return e===`darwin`?{bin:`open`,args:[t]}:e===`win32`?{bin:`cmd`,args:[`/c`,`start`,`""`,t]}:e===`linux`||e===`freebsd`||e===`openbsd`?{bin:`xdg-open`,args:[t]}:null}const ue=(0,h.promisify)(l.execFile),de=String.raw`
4
- function run(urls) {
5
- function key(url) {
6
- return String(url).split(/[?#]/)[0].replace(/^(https?:\/\/)127\.0\.0\.1:/, '$1localhost:').replace(/\/$/, '');
7
- }
8
- var targets = urls.map(key);
9
- var ids = ['company.thebrowser.dia', 'com.google.Chrome', 'com.apple.Safari'];
10
- var unknown = false;
11
- for (var a = 0; a < ids.length; a++) {
12
- var app;
13
- try { app = Application(ids[a]); if (!app.running()) continue; } catch (e) { continue; }
14
- try {
15
- var windows = app.windows();
16
- for (var w = 0; w < windows.length; w++) {
17
- var tabs = windows[w].tabs();
18
- for (var t = 0; t < tabs.length; t++) {
19
- if (targets.indexOf(key(tabs[t].url())) === -1) continue;
20
- try {
21
- if (ids[a] === 'company.thebrowser.dia') app.focus(tabs[t]);
22
- else {
23
- if (ids[a] === 'com.apple.Safari') windows[w].currentTab = tabs[t];
24
- else windows[w].activeTabIndex = t + 1;
25
- windows[w].index = 1;
26
- }
27
- app.activate();
28
- } catch (e) { console.log('Could not focus the existing browser tab: ' + e.message); }
29
- return 'found';
30
- }
31
- }
32
- } catch (e) { unknown = true; }
33
- }
34
- return unknown ? 'unknown' : 'missing';
35
- }`;async function fe(e,t=[]){if(process.platform===`darwin`){let{stdout:n,stderr:r}=await ue(`osascript`,[`-l`,`JavaScript`,`-e`,de,e,...t],{timeout:5e3});if(r.trim()&&console.error(r.trim()),n.trim()===`found`)return;if(n.trim()!==`missing`)throw Error(`Could not inspect existing browser tabs; open the artifact link manually.`)}let n=V(process.platform,e);n&&await ue(n.bin,n.args)}const pe=e=>e>=11904;function me(e,t){let n=0;for(let r of e)n+=t*(pe(r.codePointAt(0))?1:.56);return n}function he(e,t,n){return e.split(`
36
- `).reduce((e,r)=>e+Math.max(1,Math.ceil(me(r,t)/n)),0)}function ge(e,t){let n=e.boards.map(e=>t[e]).filter(e=>!!e),r=n[0];if(!r)return null;let i=Math.min(...n.map(e=>e.x)),a=Math.min(...n.map(e=>e.y)),o=Math.max(...n.map(e=>e.x+e.w)),s=Math.max(...n.map(e=>e.y+e.h));return{page:r.page,x:i-48,y:a-144,w:o-i+96,h:s-a+144+48}}const _e=e=>Math.ceil(me(e,40)+80+28+16);function ve(e){if(e.kind===`condition`)return{x:e.x,y:e.y,w:_e(e.text),h:96};if(e.kind===`sticky`){let t=e.w??240,n=he(e.text,18,Math.max(1,t-32));return{x:e.x,y:e.y,w:t,h:n*27+32}}let t=ye(e),n=be(e);return n?{...t,w:e.w??Math.max(t.w,n.w),h:t.h+n.gap+n.h}:t}function ye(e){let t=e.size??96,n=t*1.15;return e.w===void 0?{x:e.x,y:e.y,w:me(e.text,t),h:n}:{x:e.x,y:e.y,w:e.w,h:he(e.text,t,e.w)*n}}function be(e){if(e.kind!==`title`||!e.description)return null;let t=e.size??96,n=Math.max(18,Math.round(t*.4)),r=Math.min(e.w??1/0,n*40),i=Math.max(...e.description.split(`
37
- `).map(e=>me(e,n)));return{size:n,maxWidth:r,gap:t*.25,w:Math.min(r,i),h:he(e.description,n,r)*n*1.5}}function xe(e,t){let n={minX:t.x,minY:t.y,maxX:t.x+t.w,maxY:t.y+t.h};return e?{minX:Math.min(e.minX,n.minX),minY:Math.min(e.minY,n.minY),maxX:Math.max(e.maxX,n.maxX),maxY:Math.max(e.maxY,n.maxY)}:n}function Se(e){let t={},n=e=>t[e]??={groups:{},notes:{},bounds:null};for(let t of e.pages)n(t.id);for(let t of Object.values(e.boards)){let e=n(t.page);e.bounds=xe(e.bounds,{...t,y:t.y-48,h:t.h+48})}for(let[t,r]of Object.entries(e.groups??{})){let i=ge(r,e.boards);if(!i)continue;let{page:a,...o}=i,s=n(a);s.groups[t]=o,s.bounds=xe(s.bounds,o)}for(let[t,r]of Object.entries(e.notes??{})){let e=ve(r),i=n(r.page);i.notes[t]=e,i.bounds=xe(i.bounds,e)}return{pages:t}}const Ce=(e,t)=>e.x<t.x+t.w&&t.x<e.x+e.w&&e.y<t.y+t.h&&t.y<e.y+e.h,we=[`artboard`,`document`,`html`,`whiteboard`,`verify`,`slides`,`report`,`storyboard`],H={artboard:`canvas.json`,document:`doc.xml`,html:`index.html`,whiteboard:`scene.excalidraw`,verify:`verify.xml`,slides:`index.html`,report:`report.tsx`,storyboard:`storyboard.xml`},Te={...H,verify:`report.xml`},Ee={artboard:[`comments.json`,`marks/`],document:[],html:[],whiteboard:[],verify:[],slides:[`comments.json`],report:[],storyboard:[]},De=[`html`,`image`,`video`],Oe=e=>e.type===`image`||e.type===`video`,ke=`data-report-comments`,Ae=[`x`,`y`,`w`,`h`],je=[`file`,`page`,...Ae],Me=[`src`,`page`,...Ae],Ne=e=>Oe(e)?e.src??``:e.file,Pe=e=>Oe(e)?`src`:`file`,Fe=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Ie(e){if(!Fe(e))return[`canvas.json must be a JSON object`];let t=[];if(Array.isArray(e.pages)||t.push(`"pages" must be an array`),Fe(e.boards)||t.push(`"boards" must be an object`),e.groups!==void 0&&!Fe(e.groups)&&t.push(`"groups" must be an object`),e.notes!==void 0&&!Fe(e.notes)&&t.push(`"notes" must be an object`),e.edges!==void 0&&!Fe(e.edges)&&t.push(`"edges" must be an object`),e.focus===void 0||Fe(e.focus)&&typeof e.focus.target==`string`||t.push(`"focus" must be { "target": <id>, "at": <time> }`),e.building!==void 0&&typeof e.building!=`boolean`&&t.push(`"building" must be a boolean`),e.writing===void 0||typeof e.writing==`string`&&e.writing||t.push(`"writing" must be a board id`),Fe(e.notes))for(let[n,r]of Object.entries(e.notes))Fe(r)&&r.color!==void 0&&(typeof r.color!=`string`||!/^#(?:[\da-f]{3}|[\da-f]{6})$/i.test(r.color))&&t.push(`note "${n}" color must be #RGB or #RRGGBB`);if(Fe(e.boards))for(let[n,r]of Object.entries(e.boards))Fe(r)&&r.trim!==void 0&&typeof r.trim!=`boolean`&&t.push(`board "${n}" field "trim" must be a boolean`),Fe(r)&&r.interactive!==void 0&&typeof r.interactive!=`boolean`&&t.push(`board "${n}" field "interactive" must be a boolean`),Fe(r)&&r.type!==void 0&&!De.includes(r.type)&&t.push(`board "${n}" field "type" must be "html", "image" or "video"`);if(Fe(e.edges))for(let[n,r]of Object.entries(e.edges))!Fe(r)||typeof r.from!=`string`||typeof r.to!=`string`?t.push(`edge "${n}" needs string "from" and "to"`):r.label!==void 0&&typeof r.label!=`string`&&t.push(`edge "${n}" field "label" must be a string`);if(Fe(e.groups))for(let[n,r]of Object.entries(e.groups)){Fe(r)&&r.verify!==void 0&&typeof r.verify!=`boolean`&&t.push(`group "${n}" field "verify" must be a boolean`);for(let e of[`from`,`capturedAt`])Fe(r)&&r[e]!==void 0&&typeof r[e]!=`string`&&t.push(`group "${n}" field "${e}" must be a string`);Fe(r)&&r.choose!==void 0&&typeof r.choose!=`boolean`&&t.push(`group "${n}" field "choose" must be a boolean`)}if(t.length>0)return t;e.pages.forEach((e,n)=>{Fe(e)&&typeof e.id==`string`&&typeof e.name==`string`||t.push(`pages[${n}] needs string "id" and "name"`)});for(let[n,r]of Object.entries(e.boards))if(!Fe(r))t.push(`board "${n}" must be an object`);else{for(let e of Oe(r)?Me:je)r[e]===void 0&&t.push(`board "${n}" is missing "${e}"`);for(let e of Ae)r[e]!==void 0&&typeof r[e]!=`number`&&t.push(`board "${n}" field "${e}" must be a number`);for(let e of[`file`,`src`,`page`])r[e]!==void 0&&typeof r[e]!=`string`&&t.push(`board "${n}" field "${e}" must be a string`)}for(let[n,r]of Object.entries(e.groups??{}))!Fe(r)||!Array.isArray(r.boards)||r.boards.some(e=>typeof e!=`string`)?t.push(`group "${n}" needs a "boards" array`):(r.recommend!==void 0&&!r.boards.includes(r.recommend)&&t.push(`group "${n}" recommends "${String(r.recommend)}", which is not one of its boards`),r.choose===!0&&r.verify===!0&&t.push(`group "${n}" cannot be both "choose" and "verify"`));for(let[n,r]of Object.entries(e.notes??{}))!Fe(r)||r.kind!==`title`&&r.kind!==`sticky`&&r.kind!==`condition`?t.push(`note "${n}" needs "kind" "title", "sticky" or "condition"`):typeof r.x!=`number`||typeof r.y!=`number`||typeof r.text!=`string`||typeof r.page!=`string`?t.push(`note "${n}" needs numeric "x", "y" and string "text", "page"`):r.description!==void 0&&r.kind!==`title`?t.push(`note "${n}" is a ${r.kind}: only a title takes "description"`):r.description!==void 0&&typeof r.description!=`string`&&t.push(`note "${n}" needs a string "description"`);return t}function Le(e){let t=[],n=Object.entries(e.edges??{}),r=e.notes??{},i=t=>e.boards[t]?.page??r[t]?.page,a=t=>!!e.boards[t]||r[t]?.kind===`condition`,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map;for(let[l,u]of n){let n=!0;for(let i of/* @__PURE__ */ new Set([u.from,u.to]))if(e.boards[i]&&r[i])t.push(`edge "${l}" end "${i}" names both a board and a note`),n=!1;else if(a(i))continue;else r[i]||e.groups?.[i]?(t.push(`edge "${l}" end "${i}" is not a board or condition`),n=!1):(t.push(`edge "${l}" references unknown board or condition "${i}"`),n=!1);if([...u.label??``].length>32&&t.push(`edge "${l}" label is longer than 32 characters`),!n)continue;if(u.from===u.to){t.push(`edge "${l}" starts and ends at "${u.from}"`);continue}if(i(u.from)!==i(u.to)){t.push(`edge "${l}" connects different pages`);continue}let d=JSON.stringify([u.from,u.to]),f=o.get(d);f===void 0?(o.set(d,l),s.set(u.to,(s.get(u.to)??0)+1),c.set(u.from,(c.get(u.from)??0)+1),r[u.from]?.kind===`condition`&&!u.label?.trim()&&t.push(`edge "${l}" leaves condition "${u.from}" and needs a "label"`)):t.push(`edges "${f}" and "${l}" both connect "${u.from}" to "${u.to}"`)}for(let[n,i]of Object.entries(r))i.kind!==`condition`||e.boards[n]||(s.get(n)||t.push(`condition "${n}" has no incoming edge`),(c.get(n)??0)<2&&t.push(`condition "${n}" needs at least two outgoing edges`));return t}function Re(e,t,n){return!n||!t||t.toLowerCase()!==n.toLowerCase()?null:`"${e}" must not repeat the artifact slug "${n}"`}function ze(e,t,n={}){let r=Ie(e);if(r.length>0)return r;let i=e,a=[],o=Re(`title`,typeof i.title==`string`?i.title.trim():``,n.artifact);o&&a.push(o);let s=new Set(i.pages.map(e=>e.id)),c=Object.entries(i.boards),l=Object.entries(i.groups??{}),u=Object.entries(i.notes??{});for(let[e,r]of c){s.has(r.page)||a.push(`board "${e}" uses unknown page "${r.page}"`);let i=Ne(r);i.startsWith(`pages/`)?t(i)||(n.pending?.add(e),n.allowPending||a.push(`board "${e}" file not found: ${i}`)):a.push(`board "${e}" ${Pe(r)} must start with "pages/": ${i}`)}for(let e=0;e<c.length;e++)for(let t=e+1;t<c.length;t++){let[n,r]=c[e],[i,o]=c[t];r.page===o.page&&Ce(r,o)&&a.push(`boards "${n}" and "${i}" overlap`)}let d=[];for(let[e,t]of l){for(let n of t.boards)i.boards[n]||a.push(`group "${e}" references unknown board "${n}"`);new Set(t.boards.map(e=>i.boards[e]?.page).filter(Boolean)).size>1?a.push(`group "${e}" spans several pages`):d.push([e,ge(t,i.boards)])}for(let e=0;e<d.length;e++)for(let t=e+1;t<d.length;t++){let[n,r]=d[e],[i,o]=d[t];r&&o&&r.page===o.page&&Ce(r,o)&&a.push(`groups "${n}" and "${i}" overlap`)}let f=new Set(l.flatMap(([,e])=>e.boards));for(let[e,t]of u){if(!s.has(t.page)){a.push(`note "${e}" uses unknown page "${t.page}"`);continue}t.kind===`title`&&me(t.text,1)>40&&a.push(`title "${e}" is too long: keep "text" to one short line (40 full-width or about 70 Latin characters) and move the rest to "description"`);let n=ve(t);if(t.kind===`title`)for(let[r,i]of d)i&&i.page===t.page&&Ce(n,i)&&a.push(`title "${e}" overlaps group "${r}"`);for(let[r,i]of c)t.kind===`title`&&f.has(r)||i.page===t.page&&Ce(n,i)&&a.push(`${t.kind} "${e}" covers board "${r}"`)}a.push(...Le(i)),i.activePage!==void 0&&!s.has(i.activePage)&&a.push(`activePage "${i.activePage}" is not a page`);let p=i.focus?.target;return i.writing!==void 0&&!i.boards[i.writing]&&a.push(`writing target "${i.writing}" is not a board`),p===void 0||i.boards[p]||i.groups?.[p]||i.notes?.[p]||a.push(`focus target "${p}" is not a board, group or note`),a}function Be(e,t=Date.now()){let n=[];for(let[r,i]of Object.entries(e.groups??{}))if(i.verify===!0){if(i.from?.trim()||n.push(`verify group "${r}" has no "from": say which environment and build its evidence came from`),!i.capturedAt?.trim())n.push(`verify group "${r}" has no "capturedAt": say when its evidence was captured`);else{let e=Date.parse(i.capturedAt);Number.isNaN(e)?n.push(`verify group "${r}" field "capturedAt" is not an ISO time`):e>t+6e4&&n.push(`verify group "${r}" field "capturedAt" is in the future`)}}return n}const Ve=`main`,He=`pages.json`,Ue=`pages`,We=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Ge=e=>typeof e==`string`&&e.length<=64&&We.test(e),Ke=e=>e===`main`?`scene.excalidraw`:`${Ue}/${e}.excalidraw`,qe=e=>{if(e===`scene.excalidraw`)return Ve;let t=/^pages\/([^/]+)\.excalidraw$/.exec(e);return t&&Ge(t[1])&&t[1]!==`main`?t[1]:null},Je=e=>e.filter(e=>!e.deleted),Ye=e=>{if(typeof e!=`object`||!e)return null;let{id:t,name:n,deleted:r}=e;return typeof t==`string`?{id:t,...typeof n==`string`&&n.trim()?{name:n.trim()}:{},...r===!0?{deleted:!0}:{}}:null};function Xe(e){if(e===null)return{pages:[]};let t;try{t=JSON.parse(e)}catch{return{pages:[],error:`pages.json is not valid JSON`}}let n=t?.pages;return Array.isArray(n)?{pages:n.map(Ye).filter(e=>e!==null)}:{pages:[],error:`pages.json needs a "pages" array`}}function Ze(e,t){let n=[],r=/* @__PURE__ */ new Set,i=[];for(let t of e)Ge(t.id)?r.has(t.id)?n.push(`pages.json: page ${t.id} is listed twice; only the first is kept`):(r.add(t.id),i.push(t)):n.push(`pages.json: page id "${t.id}" must be lowercase letters, digits and hyphens`);let a=i.findIndex(e=>e.id===Ve);i.length>0&&a!==0&&n.push(`pages.json: main is always the first page; it was moved to the top`);let o=a===-1?{id:Ve}:i.splice(a,1)[0];o.deleted&&n.push(`pages.json: main can’t be deleted; its "deleted" is ignored`);let{deleted:s,...c}=o,l=[c,...i];for(let e of t)Ge(e)&&e!==`main`&&!r.has(e)&&(r.add(e),l.push({id:e}),n.push(`pages/${e}.excalidraw is not in pages.json; add it there`));return l.length>50&&n.push(`pages.json lists ${l.length} pages; only the first 50 are used`),{pages:l.slice(0,50),warnings:n}}function Qe(e,t){let n=new Set(t.map(e=>e.id));return[...t,...e.filter(e=>!n.has(e.id))]}function $e(e,t){let n=e.findIndex(e=>e.id===t.id),r=e[n],i=t=>e.map((e,r)=>r===n?t:e);switch(t.op){case`add`:return!Ge(t.id)||n!==-1||Je(e).length>=50?null:[...e,Ye({id:t.id,name:t.name})];case`rename`:return r?i(Ye({...r,name:t.name})):null;case`move`:{if(!r||t.id===`main`)return null;let i=e.filter((e,t)=>t!==n),a=Math.min(Math.max(t.to,1),i.length);return[...i.slice(0,a),r,...i.slice(a)]}case`delete`:return r&&t.id!==`main`?i({...r,deleted:!0}):null;case`restore`:{if(!r?.deleted)return null;let{deleted:e,...t}=r;return i(t)}}}const et=e=>`${JSON.stringify({pages:e.map(e=>Ye(e))},null,2)}\n`;function tt(e,t){let n=p.default.resolve(e,`.${p.default.sep}${t}`);return!n.startsWith(e+p.default.sep)||p.default.relative(e,n).split(p.default.sep).some(e=>e.startsWith(`.`))?null:n}const nt=(e,t)=>e.toLowerCase().startsWith(`${t.toLowerCase()}${p.default.sep}`);function rt(e,t,n){let r=tt(e,t);if(!r)return null;let i,a;try{i=d.default.realpathSync(r),a=d.default.realpathSync(n)}catch{return null}return nt(i,a)&&d.default.statSync(i).isFile()?i:null}const it=(e,t)=>rt(e,t,p.default.join(e,`pages`)),at=(e,t)=>rt(e,t,p.default.join(e,`assets`)),ot=(e,t)=>rt(e,t,p.default.join(e,`evidence`)),st=(e,t)=>rt(e,t,e);function ct(e,t){let n=rt(e,t,e);return n?p.default.relative(d.default.realpathSync(e),n).toLowerCase()===`comments.json`?null:n:null}const lt=/* @__PURE__ */ new Set([`shots`,`assets`,`takes`,`audio`,`sound`,`cuts`]);function ut(e,t){let n=t.split(`/`)[0]??``;return lt.has(n)&&t.includes(`/`)?rt(e,t,p.default.join(e,n)):null}const dt=(e,t)=>ct(e,t),ft=(e,t)=>t===`pages.json`||qe(t)!==null?rt(e,t,e):null;function pt(e){let t;try{t=d.default.readFileSync(p.default.join(e,H.artboard),`utf8`)}catch{return{warning:`canvas.json not found`}}try{return{raw:JSON.parse(t)}}catch(e){return{warning:`canvas.json is not valid JSON: ${e.message}`}}}function mt(e,t){let n={},r,i=-1/0;for(let[a,o]of Object.entries(t.boards)){let t=it(e,o.file);if(!t)n[o.file]=0;else try{let e=d.default.statSync(t);if(Oe(o)){n[o.file]=e.size>0?e.mtimeMs:0;continue}let s=d.default.readFileSync(t,`utf8`),c=/<(?:!doctype|html)\b/i.test(s),l=s.trim().length>0&&(!c||/<\/html>\s*(?:<!--[\s\S]*?-->\s*)*$/i.test(s));n[o.file]=l?e.mtimeMs:0,!l&&e.mtimeMs>=i&&(r=a,i=e.mtimeMs)}catch{n[o.file]=0}}return{versions:n,writing:r}}function ht(e){let{raw:t,warning:n}=pt(e);if(n)return{canvas:null,warnings:[n],pending:[],layout:null,versions:{}};try{let n=Ie(t);if(n.length>0)return{canvas:null,warnings:n,pending:[],layout:null,versions:{}};let r={...t};r.boards=Object.fromEntries(Object.entries(r.boards).map(([e,t])=>[e,Oe(t)?{...t,file:t.src??``}:t]));let{versions:i,writing:a}=mt(e,r),o=/* @__PURE__ */ new Set;for(let[e,t]of Object.entries(r.boards))i[t.file]||o.add(e);return r.building=o.size>0,delete r.writing,a&&(r.writing=a),{canvas:r,warnings:ze(r,t=>it(e,t)!==null,{artifact:p.default.basename(e),pending:o,allowPending:!0}),pending:[...o].sort(),layout:Se(r),versions:i}}catch(e){return{canvas:null,warnings:[`canvas.json could not be checked: ${e.message}`],pending:[],layout:null,versions:{}}}}function U(e,t){d.default.mkdirSync(p.default.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;d.default.writeFileSync(n,`${JSON.stringify(t,null,2)}\n`,{mode:384}),d.default.renameSync(n,e)}function gt(e,t,n,r={}){let i=(/* @__PURE__ */ new Date()).toISOString(),a=p.default.join(e,t.type,t.id);U(p.default.join(a,`warnings.json`),{checkedAt:i,warnings:n.warnings,...n.pending?{pending:n.pending}:{},...r})}function _t(e=process.env){return e.RYUGI_TOKEN?.trim()||null}function vt(e,t,n=process.env,r){let i=r?.trim()||_t(n);if(i)return{origin:t,token:i,login:null,source:`env`};let a=bt(e,t);return a?{...a,source:`store`}:null}function yt(e,t,n){return t===`win32`&&e.APPDATA?p.default.join(e.APPDATA,`ryugi`,`credentials.json`):p.default.join(e.XDG_CONFIG_HOME||p.default.join(n,`.config`),`ryugi`,`credentials.json`)}function bt(e,t){let n;try{n=JSON.parse(d.default.readFileSync(e,`utf8`))}catch{return null}if(typeof n!=`object`||!n)return null;let{origin:r,token:i,login:a}=n;return typeof r!=`string`||typeof i!=`string`||typeof a!=`string`||r!==t?null:{origin:r,token:i,login:a}}function xt(e,t){d.default.mkdirSync(p.default.dirname(e),{recursive:!0,mode:448}),U(e,t)}function St(e){d.default.rmSync(e,{force:!0})}function Ct(e=process.env){return e.RYUGI_DAEMON_SOCKET?e.RYUGI_DAEMON_SOCKET:p.default.join(p.default.dirname(T(e)),`daemon.sock`)}function wt(e,{timeoutMs:t=5e3}={}){let n=(n,r)=>new Promise((i,a)=>{let o=m.default.connect(e),s=``,c=e=>{o.destroy(),a(e)},l=setTimeout(()=>c(/* @__PURE__ */ Error(`daemon ${n} timed out`)),t);o.on(`error`,e=>{clearTimeout(l),c(e)}),o.on(`connect`,()=>o.write(`${JSON.stringify({op:n,...r})}\n`)),o.on(`data`,e=>{if(s+=e.toString(`utf8`),s.length>4194304)return c(/* @__PURE__ */ Error(`daemon reply too large`));let t=s.indexOf(`
38
- `);if(!(t<0)){clearTimeout(l),o.end();try{let e=JSON.parse(s.slice(0,t));e.ok?i(e.data??null):a(Error(e.error||`daemon ${n} failed`))}catch{a(/* @__PURE__ */ Error(`daemon reply is not JSON`))}}})});return{call:n,available:()=>n(`status`,{}).then(()=>!0,()=>!1)}}const Tt=/* @__PURE__ */ new Set([`darwin-arm64`,`linux-x64`,`linux-arm64`]),Et=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/,Dt=e=>Et.test(e);async function Ot(e,t,n,r,i,a){let o=`${n.replace(/\/+$/,``)}/v${t}/${e}`,s=await r(o,{signal:i});if(!s.ok)throw Object.assign(/* @__PURE__ */ Error(`could not download ${e} ${t}: HTTP ${s.status}`),{status:s.status});let c=Number(s.headers.get(`content-length`))||void 0;a?.(0,c);let l=[],d=0,f=s.body?.getReader();for(let e=await f?.read();e&&!e.done;e=await f?.read())l.push(Buffer.from(e.value)),d+=e.value.length,a?.(d,c);let p=Buffer.concat(l),m=await r(`${o}.sha256`,{signal:i});if(!m.ok)throw Object.assign(/* @__PURE__ */ Error(`could not download the sha256 for ${e}: HTTP ${m.status}`),{status:m.status});if((await m.text()).trim().split(/\s+/)[0]?.toLowerCase()!==u.default.createHash(`sha256`).update(p).digest(`hex`))throw Error(`${e} failed its sha256 check; nothing was installed`);return p}function kt(e,t){d.default.mkdirSync(p.default.dirname(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;d.default.writeFileSync(n,t,{mode:493}),d.default.chmodSync(n,493),d.default.renameSync(n,e)}const At=e=>p.default.join(e,`.ryugi`,`hook`),jt=(e,t)=>p.default.join(At(e),t),Mt=(e,t)=>Tt.has(`${e}-${t}`)?`ryugi-hook-${e}-${t}`:null;function Nt(e){try{return d.default.statSync(e).isFile()&&!!(d.default.statSync(e).mode&73)}catch{return!1}}function Pt(e,t){try{let n=JSON.parse(d.default.readFileSync(e,`utf8`));return t-n.at<(n.status===404?5:60)*6e4}catch{return!1}}function Ft(e,t){try{return d.default.writeFileSync(e,String(process.pid),{flag:`wx`}),!0}catch{}try{return t-d.default.statSync(e).mtimeMs<3e5?!1:(d.default.rmSync(e,{force:!0}),d.default.writeFileSync(e,String(process.pid),{flag:`wx`}),!0)}catch{return!1}}async function It(e){let t=Mt(e.platform,e.arch);if(!t||!Dt(e.version))return{status:`skipped`};let n=e.now??Date.now(),r=jt(e.home,e.version),i=p.default.join(r,`ryugi-hook`);if(Nt(i))return{status:`present`};d.default.mkdirSync(r,{recursive:!0,mode:448});let a=p.default.join(r,`.failed`);if(!e.retry&&Pt(a,n))return{status:`skipped`,error:`the last download failed; it is retried later`};let o=p.default.join(r,`.lock`);if(!Ft(o,n))return{status:`skipped`,error:`another download is in progress`};let s=AbortSignal.timeout(e.timeoutMs??6e4);try{let n=process.env.RYUGI_HOOK_RELEASE_BASE||`https://github.com/Innei/ryugi/releases/download`;return kt(i,await Ot(t,e.version,n,e.fetch,s,e.onProgress)),d.default.rmSync(a,{force:!0}),{status:`installed`}}catch(t){let r=t.status??null;return d.default.writeFileSync(a,JSON.stringify({at:n,status:r})),{status:`failed`,error:s.aborted?`the download of ryugi-hook ${e.version} timed out`:t.message}}finally{d.default.rmSync(o,{force:!0})}}const Lt=`dev.ryugi.daemon`,Rt=`ryugi-daemon.service`,zt=`<key>ProcessType</key>
39
- <string>Background</string>`,Bt=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`);function Vt(e){return`<?xml version="1.0" encoding="UTF-8"?>
40
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
41
- <plist version="1.0">
42
- <dict>
43
- <key>Label</key>
44
- <string>${Lt}</string>
45
- <key>ProgramArguments</key>
46
- <array>
47
- <string>${Bt(e.binary)}</string>
48
- </array>
49
- <key>KeepAlive</key>
50
- <true/>
51
- <key>RunAtLoad</key>
52
- <true/>
53
- <key>ProcessType</key>
54
- <string>Standard</string>
55
- <key>EnvironmentVariables</key>
56
- <dict>
57
- <key>PATH</key>
58
- <string>${Bt(e.path)}</string>
59
- <key>RYUGI_HUB_START</key>
60
- <string>${Bt(JSON.stringify(e.hubStart))}</string>
61
- </dict>
62
- <key>StandardErrorPath</key>
63
- <string>${Bt(e.log)}</string>
64
- <key>StandardOutPath</key>
65
- <string>${Bt(e.log)}</string>
66
- </dict>
67
- </plist>
68
- `}const Ht=e=>`"${e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`).replaceAll(`%`,`%%`)}"`;function Ut(e){let t=e.log.replaceAll(`%`,`%%`);return`[Unit]
69
- Description=Ryugi daemon
70
-
71
- [Service]
72
- ExecStart=${Ht(e.binary)}
73
- Restart=always
74
- RestartSec=2
75
- KillMode=process
76
- Environment=${Ht(`PATH=${e.path}`)}
77
- Environment=${Ht(`RYUGI_HUB_START=${JSON.stringify(e.hubStart)}`)}
78
- StandardOutput=append:${t}
79
- StandardError=append:${t}
80
-
81
- [Install]
82
- WantedBy=default.target
83
- `}const Wt=(e,t)=>{if(e.status!==0)throw Error(`${t} failed: ${e.stderr.trim()}`)};function Gt(e){let t=`gui/${e.uid}/${Lt}`,n=p.default.join(e.home,`Library`,`LaunchAgents`,`${Lt}.plist`);return{file:n,kind:`agent`,check:()=>null,render:Vt,load:()=>{e.run(`launchctl`,[`bootout`,t]),Wt(e.run(`launchctl`,[`bootstrap`,`gui/${e.uid}`,n]),`launchctl bootstrap`)},migrate:()=>{let e=d.default.readFileSync(n,`utf8`);return e.includes(zt)?(d.default.writeFileSync(n,e.replace(zt,`<key>ProcessType</key>
84
- <string>Standard</string>`)),!0):!1},unload:()=>{e.run(`launchctl`,[`bootout`,t])},removed:()=>{},restart:()=>Wt(e.run(`launchctl`,[`kickstart`,`-k`,t]),`launchctl kickstart`),linger:()=>void 0}}function Kt(e){let t=(...t)=>e.run(`systemctl`,[`--user`,...t]),n,r=()=>n??=t(`show-environment`),i=()=>{let t=r();return t.status===0?/^XDG_CONFIG_HOME=(.+)$/m.exec(t.stdout??``)?.[1]??p.default.join(e.home,`.config`):e.configHome??p.default.join(e.home,`.config`)};return{get file(){return p.default.join(i(),`systemd`,`user`,Rt)},kind:`service`,check:()=>{let e=r();return e.status===0?null:`systemd user services are not available here (systemctl --user: ${e.stderr.trim()||`failed`}); ryugi daemon needs systemd on Linux`},render:Ut,load:()=>{Wt(t(`daemon-reload`),`systemctl --user daemon-reload`),Wt(t(`enable`,Rt),`systemctl --user enable ${Rt}`),Wt(t(`restart`,Rt),`systemctl --user restart ${Rt}`)},migrate:()=>!1,unload:()=>{t(`disable`,`--now`,Rt)},removed:()=>{t(`daemon-reload`)},restart:()=>Wt(t(`restart`,Rt),`systemctl --user restart ${Rt}`),linger:()=>{let t=e.run(`loginctl`,[`enable-linger`]);return t.status===0?{enabled:!0}:{enabled:!1,error:t.stderr.trim()||`exit ${t.status}`}}}}function qt(e){return e.platform===`darwin`?Gt(e):e.platform===`linux`?Kt(e):null}const Jt={darwin:[`arm64`],linux:[`x64`,`arm64`]},Yt=e=>({binary:p.default.join(e,`.ryugi`,`bin`,`ryugi-daemon`),log:p.default.join(e,`.ryugi`,`daemon`,`daemon.log`)});function Xt(e){return Ot(`ryugi-daemon-${e.platform}-${e.arch}`,e.version,process.env.RYUGI_DAEMON_RELEASE_BASE||`https://github.com/Innei/ryugi/releases/download`,e.fetch)}async function Zt(e,t,n){if(p.default.resolve(e.serverHome)!==p.default.join(e.home,`.ryugi`,`server`))return{status:`other-hub`};let r=Yt(e.home),i=qt(e);if(!i||!d.default.existsSync(i.file)||!d.default.existsSync(r.binary))return{status:`not-installed`};let a=await t.call(`status`,{}).catch(()=>null);if(!a?.version)return{status:`not-running`};if(e.daemonSource?a.source===e.daemonSource:a.version===e.version)return{status:`current`};let o=await Xt(e);return n?.(),kt(r.binary,o),i.migrate()?i.load():i.restart(),{status:`updated`,from:a.version,to:e.version}}const Qt=12096e5,$t=e=>p.default.join(At(e),`plugins.json`);function en(e){try{let t=JSON.parse(d.default.readFileSync($t(e),`utf8`));return Array.isArray(t?.plugins)?{complete:t.complete===!0,plugins:t.plugins.filter(e=>typeof e?.version==`string`&&Dt(e.version))}:null}catch{return null}}const tn=e=>{try{return d.default.statSync(e).mtimeMs}catch{return null}};function nn(e){let t=At(e.home),n=[],r=[];try{r=d.default.readdirSync(t)}catch{}for(let i of r){if(!Dt(i)||e.keep.has(i))continue;let r=p.default.join(t,i),a=tn(p.default.join(r,`last-used`)),o=tn(r),s=tn(p.default.join(r,`.lock`)),c=(t,n)=>t!==null&&e.now-t<n;c(a,Qt)||a===null&&c(o,Qt)||c(s,3e5)||(d.default.rmSync(r,{recursive:!0,force:!0}),n.push(i))}let i=p.default.join(t,`.legacy-removed`);if(!e.legacyInUse&&!d.default.existsSync(i)){let n=e.env.XDG_CACHE_HOME||p.default.join(e.home,`.cache`);d.default.rmSync(p.default.join(n,`ryugi`,`hook`),{recursive:!0,force:!0}),d.default.mkdirSync(t,{recursive:!0,mode:448}),d.default.writeFileSync(i,``)}return n}async function rn(e){if(p.default.resolve(e.serverHome)!==p.default.join(e.home,`.ryugi`,`server`))return{status:`other-hub`};let t=e.now??Date.now(),n=e.installed??en(e.home),r=n?.plugins??[],i=/* @__PURE__ */ new Set([e.version,...r.filter(e=>!e.legacy).map(e=>e.version)]),a=[],o=[],{progress:s}=e,c=await Promise.all([...i].map(n=>It({...e,version:n,now:t,onProgress:s&&((e,t)=>s(n,e,t))})));return[...i].forEach((e,t)=>{let n=c[t];n.status===`installed`&&a.push(e),(n.status===`failed`||n.status===`skipped`&&n.error)&&o.push({version:e,error:n.error??`failed`})}),{status:`done`,prefetched:a,failed:o,removed:e.cleanup?nn({env:e.env,home:e.home,keep:i,legacyInUse:!n?.complete||r.some(e=>e.legacy),now:t}):[]}}const an=/* @__PURE__ */ new Set([`localhost`,`::1`,`[::1]`]),on=e=>an.has(e)||/^127\.\d+\.\d+\.\d+$/.test(e),sn=e=>e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e;function cn({host:e,urlHost:t,ports:n,cloudOrigin:r}){let i=[...new Set([`localhost`,`127.0.0.1`,sn(e),sn(t)].map(e=>e.toLowerCase()))],a=new Set(n.flatMap(e=>i.map(t=>`${t}:${e}`))),o=n[0],s=new Set(i.map(e=>`http://${e}:${o}`));return{loopback:on(e),hosts:a,origins:s,cloudOrigin:r}}const ln=(e,t)=>!e.loopback||t!==void 0&&e.hosts.has(t.toLowerCase()),un=(e,t,{cloud:n=!1}={})=>t===void 0||e.origins.has(t)||n&&e.cloudOrigin!==void 0&&t===e.cloudOrigin,dn=e=>e===void 0||e===`none`||e===`same-origin`,fn=e=>(0,u.createHash)(`sha256`).update(JSON.stringify(e)).digest(`hex`),pn=(e,t)=>fn([e,t]);function mn(e){let t=e.messages.filter(e=>e.author===`human`).map(t=>({token:fn([e.id,`message`,t.id,t.at,t.editedAt,t.deleted,t.text]),at:t.editedAt??t.at}));return e.statusBy===`human`&&t.push({token:fn([e.id,`status`,e.statusAt,e.status]),at:e.statusAt}),t}function hn(e,t=[]){let n=new Set(t);return(e?.threads??[]).filter(e=>{let t=e.anchor;return t.ask===void 0&&t.choice===void 0&&t.submit===void 0&&mn(e).some(e=>!n.has(e.token))}).length}const gn=new Intl.Segmenter(void 0,{granularity:`grapheme`}),_n=e=>{let t=[...gn.segment(e)];return t.length>400?`${t.slice(0,400).map(e=>e.segment).join(``)}…`:e};function vn(e){try{return JSON.parse(d.default.readFileSync(e,`utf8`))}catch{return null}}const yn=e=>p.default.join(e,`.ryugi`,`artifacts`),bn=(e,t)=>t.startsWith(`preview/`)?p.default.join(e,`.ryugi`,t,`comments.json`):p.default.join(yn(e),t,`comments.json`),xn=(e,t,n)=>p.default.join(yn(e),`.state`,t,n),Sn=e=>e.anchor?.ask!==void 0||e.anchor?.submit!==void 0||e.anchor?.choice!==void 0;function Cn(e){if(!e||!Array.isArray(e.threads))return null;let t=/* @__PURE__ */ new Map;for(let n of e.threads){if(!n||typeof n.id!=`string`||!Array.isArray(n.messages))return null;if(!Sn(n)){for(let e of n.messages){if(!e||typeof e.id!=`string`)return null;e.author===`human`&&n.status!==`resolved`&&t.set(`${n.id}/message/${e.id}`,JSON.stringify([e.at,e.editedAt,e.text,e.deleted]))}n.statusBy===`human`&&n.status!==`resolved`&&t.set(`${n.id}/status`,JSON.stringify([n.status,n.statusAt]))}}return t}function wn(e,t){let n=vn(xn(e,t,`rounds.json`));return Array.isArray(n?.rounds)?n.rounds.filter(e=>e&&typeof e.id==`string`):[]}function Tn(e,t){let n=[],r=0,i=0;for(let a of e.threads??[]){if(!a||typeof a.id!=`string`||!Array.isArray(a.messages))continue;let e=[];for(let n of a.messages)n&&typeof n.id==`string`&&t.has(`${a.id}/message/${n.id}`)&&(i>=20?r++:(i++,e.push({id:n.id,at:n.at,name:typeof n.name==`string`&&n.name?n.name:`human`,text:_n(typeof n.text==`string`?n.text:``),...n.deleted===!0?{deleted:!0}:{}})));if(!e.length)continue;let o=a.anchor??{},s=[o.blockId,o.board,o.route].find(e=>typeof e==`string`&&e!==``);n.push({thread:a.id,status:a.status,...s?{block:s}:{},messages:e})}return{threads:n,omitted:r}}function En(e,t){let n=vn(xn(e,t,`asks.json`))?.latest;return n&&typeof n.id==`string`?{id:n.id,withdrawn:n.withdrawn===!0}:null}function Dn(e,t){let n;for(let r of e){if(!Array.isArray(r?.messages)||!t(r))continue;let e=String(r.messages[0]?.at??``);(!n||e>=n.at)&&(n={thread:r,at:e})}return n?.thread}function On(e,t){let n=Array.isArray(e?.threads)?e.threads:[],r=n.find(e=>e.id===t?.id)?.anchor?.asks;return Array.isArray(r)&&r.length?r.length:new Set(n.map(e=>e?.anchor).filter(e=>e&&typeof e.ask==`string`&&e.submit===void 0&&e.note!==!0).map(e=>e.ask)).size}const kn=(e,t,n)=>Dn(Array.isArray(e?.threads)?e.threads:[],e=>e.anchor?.round===t&&e.anchor?.submit===n),An=e=>typeof e?.id==`string`?e.id:null,jn=e=>String(e?.messages?.[0]?.at??``);function Mn(e,t){let n=kn(e,t,!0),r=kn(e,t,!1);return n&&!(r&&jn(r)>=jn(n))?An(n):null}function Nn(e,t,n){let r=vn(bn(e,t));if(!Cn(r))return null;let i=vn(p.default.join(yn(e),`.state`,`agent-review`,`agent-${pn(t,n)}.json`));return hn({threads:(r.threads??[]).filter(e=>e.status!==`resolved`&&!Sn(e))},i?.consumed??[])}const Pn=()=>({seen:{},rounds:null,submit:null,submitKnown:!1,notified:{}});function Fn(e){let{project:t,artifact:n,agent:r}=e,i=e.state??Pn(),a={seen:{...i.seen},rounds:i.rounds?{...i.rounds}:null,submit:i.submit,submitKnown:i.submitKnown,notified:{...i.notified}},o=[],s=vn(bn(t,n)),c=n.startsWith(`artboard/`)?wn(t,n):[],l=i.rounds,u=new Map(c.map(e=>[e.id,e.state??``]));(u.size>0||!l)&&(a.rounds=Object.fromEntries(u));for(let[e,r]of u){let i=l?.[e];if(!l||i===void 0||i===r)continue;let u=r===`submitted`;if(!u&&(i!==`submitted`||r!==`open`))continue;let d=Mn(s,e);if(u?d&&a.notified[e]===d:d)continue;u&&d&&(a.notified[e]=d);let f=c.find(t=>t.id===e),p=An(kn(s,e,!0));o.push({type:`ryugi-choices`,project:t,artifact:n,round:e,...u?{}:{withdrawn:!0},groups:Array.isArray(f?.groups)?f.groups.length:0,...p?{submit:p}:{}})}if(n.startsWith(`document/`)){let e=En(t,n),r=i.submitKnown?i.submit:void 0;a.submit=e,a.submitKnown=!0;let c=e&&r!==void 0&&e.id!==r?.id,l=e?.withdrawn&&r?.id===e.id&&r.withdrawn===!1;(c&&!e.withdrawn||l)&&o.push({type:`ryugi-answers`,project:t,artifact:n,...l?{withdrawn:!0}:{},...e?{submit:e.id}:{},questions:On(s,e)})}let d=Cn(s);if(!d)return{events:o,state:a};let f=/* @__PURE__ */ new Set;for(let[e,t]of d)a.seen[e]!==t&&f.add(e),a.seen[e]=t;if(!f.size)return{events:o,state:a};let p=Nn(t,n,r);if(!p)return{events:o,state:a};let m=Tn(s,f);return o.push({type:`ryugi-comments`,project:t,artifact:n,unread:p,threads:m.threads,...m.omitted?{omitted:m.omitted}:{}}),{events:o,state:a}}const In=(e,t)=>`${e}\n${t}`,Ln=e=>{let t=e?.type;return typeof t==`string`&&(t.endsWith(`-comments`)||t===`data-report-comments`)};function Rn(e){let t=/* @__PURE__ */ new Map,n=1,r=(e,n)=>[...t.values()].find(t=>t.conn.host===e&&t.conn.session===n),i=(t,n,r)=>e.store.subscriptions(t.conn.host,t.conn.session).some(e=>e.project===n&&e.artifact===r),a=n=>{for(let r of new Set(n)){let n=/* @__PURE__ */ new Set;for(let i of t.values())for(let t of e.store.subscriptions(i.conn.host,i.conn.session))t.project===r&&n.add(t.artifact);e.listening(r,n)}},o=(t,n)=>{e.store.saveDelivered(t.conn.host,t.conn.session,n.project,n.artifact,n.state)},s=(t,r,i)=>{let a=In(r,i);t.watches.has(a)||t.watches.set(a,e.watch(r,i));let o=t.states.get(a)??e.store.delivered(t.conn.host,t.conn.session,r,i),s=Fn({project:r,artifact:i,agent:t.conn.agent,state:o});if(t.states.set(a,s.state),!s.events.length){[...t.batches.values()].some(e=>e.project===r&&e.artifact===i)||e.store.saveDelivered(t.conn.host,t.conn.session,r,i,s.state);return}let c={project:r,artifact:i,state:s.state,events:/* @__PURE__ */ new Map};for(let r of s.events){let i=n++;c.events.set(i,r),t.batches.set(i,c),e.send(t.conn,{t:`event`,id:i,event:r})}},c=(t,n,r)=>{let i=[...new Set(t.batches.values())].filter(e=>e.project===n&&e.artifact===r&&[...e.events.values()].some(e=>e.type===`ryugi-comments`));if(i.length&&Nn(n,r,t.conn.agent)===0){e.send(t.conn,{t:`retract`,project:n,artifact:r,type:`ryugi-comments`});for(let e of i){for(let[n,r]of e.events)r.type===`ryugi-comments`&&(e.events.delete(n),t.batches.delete(n));e.events.size||o(t,e)}}},l=n=>{t.delete(n.conn.id);for(let e of n.watches.values())e();e.store.seen(n.conn.host,n.conn.session)};return{hello(n){let i=r(n.host,n.session);i&&l(i);let o={conn:n,states:/* @__PURE__ */ new Map,batches:/* @__PURE__ */ new Map,watches:/* @__PURE__ */ new Map};t.set(n.id,o),e.store.seen(n.host,n.session);let c=e.store.subscriptions(n.host,n.session);for(let e of c)s(o,e.project,e.artifact);a(c.map(e=>e.project))},close(n){let r=t.get(n.id);r&&(l(r),a(e.store.subscriptions(n.host,n.session).map(e=>e.project)))},unsubscribe(n){let r=e.store.subscriptions(n.host,n.session).map(e=>e.project);e.store.unsubscribe(n.host,n.session);let i=t.get(n.id);i&&l(i),a(r)},ack(n,r){let i=t.get(n.id);if(!i||typeof r!=`number`)return;let a=i.batches.get(r);if(!a)return;let s=a.events.get(r);a.events.delete(r),i.batches.delete(r),s.type===`ryugi-comments`&&e.delivered(a.project,a.artifact,n.host,n.session,s.threads.map(e=>e.thread)),a.events.size||o(i,a)},subscribe(t,n,i,o){if(e.store.subscribe(t,n,i,o),!e.store.delivered(t,n,i,o)){let{state:r}=Fn({project:i,artifact:o,agent:``,state:null});e.store.saveDelivered(t,n,i,o,{...r,seen:{}})}let c=r(t,n);c&&(s(c,i,o),a([i]))},trigger(e,n){for(let r of t.values())i(r,e,n)&&(c(r,e,n),s(r,e,n))},pinned:n=>[...t.values()].some(t=>e.store.subscriptions(t.conn.host,t.conn.session).some(e=>e.project===n)),connected:(e,t)=>!!r(e,t),closeAll(){let n=[...t.values()].flatMap(t=>e.store.subscriptions(t.conn.host,t.conn.session).map(e=>e.project));for(let e of t.values())l(e);a(n)}}}const zn=`[a-z0-9][a-z0-9-]*`,Bn=`(?:[\\w-]{21}|[a-f0-9]{32})`,Vn=`(?:${zn}|${Bn})`,Hn=RegExp(`^${zn}$`),Un=RegExp(`^${Bn}$`),Wn=/* @__PURE__ */ RegExp(`^[a-z0-9]{21}$`,`i`);function Gn(e){let t=``,n=new Uint8Array(e*2);for(;t.length<e;){crypto.getRandomValues(n);for(let r of n)if(!(r>=248)&&(t+=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[r%62],t.length===e))break}return t}const Kn=()=>Gn(21),qn=e=>Wn.test(e),Jn=e=>Hn.test(e),Yn=e=>Un.test(e),Xn=e=>Hn.test(e)||Un.test(e),Zn=e=>we.includes(e);function W(e,t,n){if(!Zn(t)||!Jn(n))return null;let r=p.default.join(e,t,n);try{return d.default.statSync(r).isDirectory()?r:null}catch{return null}}function Qn(e){let t=p.default.join(e,`.artifact-id`),n;try{n=d.default.readFileSync(t,`utf8`).trim()}catch(r){if(r.code!==`ENOENT`)throw r;n=Kn();try{d.default.writeFileSync(t,`${n}\n`,{flag:`wx`})}catch(t){if(t.code!==`EEXIST`)throw t;return Qn(e)}}if(!Yn(n))throw Error(`Invalid artifact ID in ${t}`);return n}function $n(e){try{return d.default.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function er(e){let t=[],n=[];for(let r of $n(e))if(!r.startsWith(`.`)){if(!Zn(r))n.push(`unknown artifact type directory: ${r}/ (known: ${we.join(`, `)})`);else for(let i of $n(p.default.join(e,r)))Jn(i)?t.push({type:r,id:i,dir:p.default.join(e,r,i)}):n.push(`invalid artifact id: ${r}/${i} (use lowercase letters, digits and hyphens)`)}return{artifacts:t,warnings:n}}function G(e,t=Jn){let[n,r]=e.split(`/`);return!n||!r||!Zn(n)||!t(r)?null:{type:n,id:r}}function tr(e,t,n){let r=i=>{let a;try{a=d.default.readdirSync(i,{withFileTypes:!0})}catch{return}for(let o of a){if(o.name.startsWith(`.`))continue;let a=t&&i===e?Ee[t]:[];if(a.includes(o.name)||o.isDirectory()&&a.includes(`${o.name}/`))continue;let s=p.default.join(i,o.name);try{let t=d.default.statSync(s);n(p.default.relative(e,s),t,o.isDirectory()),o.isDirectory()&&r(s)}catch{continue}}};r(e)}function nr(e,t){let n=0,r=0,i=[];tr(e,t,(e,t,a)=>{i.push(e),r=Math.max(r,t.mtimeMs),a||(n+=t.size)});let a=u.default.createHash(`sha1`).update(i.sort().join(`\0`)).digest(`hex`).slice(0,12);return`${i.length}:${n}:${r}:${a}`}function rr(e,t,n){let r=Number(n.split(`:`)[2]);if(!Number.isFinite(r))return[];let i=[];return tr(e,t,(e,t,n)=>{!n&&t.mtimeMs>r&&i.push(e.split(p.default.sep).join(`/`))}),i}function ir(e,t){let n=0,r;try{r=d.default.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let i of r){if(i.name.startsWith(`.`)||i.name===t)continue;let r=p.default.join(e,i.name);try{n=Math.max(n,i.isDirectory()?ir(r):d.default.statSync(r).mtimeMs)}catch{continue}}return n}function ar(e=process.env,t=f.default.homedir()){let n=e.RYUGI_SERVER_HOME||p.default.join(t,`.ryugi`,`server`);return{home:n,events:p.default.join(n,`hub-events.log`),pid:p.default.join(n,`server.pid`),serverId:p.default.join(n,`server-instance-id`),info:p.default.join(n,`server-info`),log:p.default.join(n,`server.log`),version:p.default.join(n,`server-version`),lock:p.default.join(n,`start.lock`),key:p.default.join(n,`key`),projects:p.default.join(n,`projects.json`),settings:p.default.join(n,`settings.json`),stopped:p.default.join(n,`server-stopped`)}}function or(e){d.default.mkdirSync(e,{recursive:!0,mode:448}),d.default.chmodSync(e,448)}const sr=e=>{try{return d.default.realpathSync(p.default.resolve(e))}catch{return p.default.resolve(e)}},cr=e=>{let t=e;return!!t&&typeof t.dir==`string`&&p.default.isAbsolute(t.dir)&&Number.isFinite(t.registeredAt)&&Number.isFinite(t.lastUsedAt)};function lr(e){try{let t=JSON.parse(d.default.readFileSync(e,`utf8`));return Array.isArray(t.projects)?t.projects.filter(cr):[]}catch{return[]}}function ur(e,t){or(p.default.dirname(e));let n=`${e}.${process.pid}.tmp`;d.default.writeFileSync(n,`${JSON.stringify({projects:t},null,2)}\n`,{mode:384}),d.default.renameSync(n,e)}function dr(e,t,n=Date.now()){let r=sr(t),i=lr(e),a=i.find(e=>e.dir===r);return a?a.lastUsedAt=n:i.push({dir:r,registeredAt:n,lastUsedAt:n}),ur(e,i),a??i.at(-1)}function fr(e,t){let n=sr(t),r=lr(e),i=r.filter(e=>e.dir!==n);i.length!==r.length&&ur(e,i)}const pr=e=>p.default.join(e,`.ryugi`,`artifacts`);function mr(e){let t=lr(e),n=t.filter(e=>d.default.existsSync(pr(e.dir)));return n.length!==t.length&&ur(e,n),n}const hr=(e,t=Date.now())=>t-e.lastUsedAt>6048e5,gr=e=>{try{let t=d.default.readFileSync(p.default.join(e,`.artifact-id`),`utf8`).trim();return Yn(t)?t:null}catch{return null}},_r=e=>{try{return d.default.statSync(e).mtimeMs}catch{return 0}};function vr(e,t={}){let n=t.rescanAfterMs??1e3,r=t.now??Date.now,i=[],a=-1/0,o=()=>{i=e().flatMap(e=>er(pr(e)).artifacts.map(t=>({project:e,type:t.type,id:t.id,address:gr(t.dir),mtimeMs:_r(t.dir)}))),a=r()},s=(t,n)=>{let r=e(),a=i.find(e=>e.type===t&&e.address===n);if(a)return a;let o=i.filter(e=>e.type===t&&e.id===n);return o.sort((e,t)=>r.indexOf(e.project)-r.indexOf(t.project)),o[0]??null};return{find(e,t){if(!Xn(t))return null;a===-1/0&&o();let i=s(e,t);return!i&&r()-a>=n&&(o(),i=s(e,t)),i?{project:i.project,id:i.id}:null},owners(e,t){let n=this.find(e,t);if(!n)return[];if(i.some(n=>n.type===e&&n.address===t))return[n.project];let r=i.filter(n=>n.type===e&&n.id===t).map(e=>e.project);return[...new Set(r)]},list(e=0){return r()-a>=e&&o(),i},rescan:o}}const yr=e=>e===null?null:u.default.createHash(`sha256`).update(e).digest(`hex`),br=/^[0-9a-f]{64}$/;function xr(e){if(typeof e!=`object`||!e)return!1;let{id:t,kind:n,message:r}=e;return typeof t==`string`&&(n===`signed-out`||n===`cap`||n===`failing`)&&typeof r==`string`}function Sr(e){try{let t=JSON.parse(d.default.readFileSync(e,`utf8`)).paused?.token;return typeof t==`string`&&!br.test(t)}catch{return!1}}function Cr(e){let t={};try{let n=JSON.parse(d.default.readFileSync(e,`utf8`));typeof n==`object`&&n&&(t=n)}catch{}let n=Array.isArray(t.dirty)?t.dirty.filter(e=>typeof e==`string`):[],r=t.paused,i=typeof t.parked==`object`&&t.parked!==null?Object.fromEntries(Object.entries(t.parked).filter(e=>typeof e[1]==`string`)):{},a=t.refused;return{dirty:n,held:Array.isArray(t.held)?t.held.filter(e=>typeof e==`string`):[],notice:xr(t.notice)?t.notice:null,parked:i,paused:r&&(typeof r.token==`string`||r.token===null)?{token:r.token===null||br.test(r.token)?r.token:yr(r.token)}:null,refused:a&&(typeof a.token==`string`||a.token===null)&&Array.isArray(a.keys)?{token:a.token,keys:a.keys.filter(e=>typeof e==`string`),until:typeof a.until==`number`?a.until:null}:null}}function wr(e){let{dirty:t,held:n,parked:r,paused:i,refused:a}=Cr(e);return!i&&t.some(e=>!(e in r)&&!n.includes(e)&&!a?.keys.includes(e))}function Tr(e){let t=Cr(e.stateFile),n=new Set(t.dirty),r=t.notice,i=t.paused,a=t.refused,o=e=>!!a?.keys.includes(e),s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Map,l=new Map(Object.entries(t.parked)),d=new Set(t.held),f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=e=>(m.get(e)??0)>Date.now(),g=t=>e.signatureOf?.(t)??``,_=()=>[...n].some(e=>!l.has(e)&&!d.has(e)&&!o(e)),v=()=>U(e.stateFile,{dirty:[...n],held:[...d],notice:r,parked:Object.fromEntries(l),paused:i,refused:a});Sr(e.stateFile)&&v();let y=(e,t,n)=>{r?.kind!==e&&(r={id:u.default.randomUUID(),kind:e,message:t,...n?{upgradeUrl:n}:{}})},b=null,x=null,S=()=>{b&&clearTimeout(b),x&&clearTimeout(x),b=x=null},C=()=>{b&&clearTimeout(b),b=setTimeout(()=>void O(),e.idleMs??3e5).unref(),x??=setTimeout(()=>void O(),e.maxWaitMs??9e5).unref()},w=()=>{if(m.size===0)return;let e=Math.min(...m.values());b=setTimeout(()=>void O(),Math.max(0,e-Date.now())).unref()},T=async t=>{if(S(),!e.enabled()||n.size===0)return;let u=e.token();if(i&&i.token===yr(u))return;i&&(i=null,r?.kind===`signed-out`&&(r=null));let _=yr(u);a&&(a.token!==_||a.until!==null&&Date.now()>=a.until)&&(a=null);let b=!1;for(let v of n){if(o(v)||t&&(h(v)||d.has(v)))continue;let x=g(v);if(l.has(v)){if(l.get(v)===x)continue;l.delete(v),f.delete(v)}s.delete(v);let S=await e.publish(v);if(console.error(JSON.stringify({type:`auto-publish`,key:v,outcome:S.kind,...`message`in S?{message:S.message}:{}})),S.kind===`failed`||S.kind===`not-ready`){let e=(c.get(v)??0)+1;c.set(v,e),S.kind===`not-ready`&&S.blocked?y(`failing`,`${v}: ${S.blocked}`):e>=3&&y(`failing`,`${v}: ${S.kind===`failed`?S.message:`not ready to publish; fix its warnings`}`)}else c.delete(v),c.size===0&&r?.kind===`failing`&&(r=null);if(S.kind===`signed-out`){i={token:yr(u)},y(`signed-out`,`auto-publish paused: the Ryugi Cloud sign-in expired`);break}if(S.kind!==`not-ready`&&f.delete(v),S.kind!==`not-ready`&&S.kind!==`cannot-create`&&d.delete(v),S.kind!==`failed`&&(p.delete(v),m.delete(v)),S.kind===`published`)s.has(v)?b=!0:n.delete(v),S.created&&r?.kind===`cap`&&(r=null);else if(S.kind===`opted-out`||S.kind===`gone`)n.delete(v);else if(S.kind===`cannot-create`)S.oversize?l.set(v,x):a={token:_,keys:[...a?.keys??[],v],until:S.until??a?.until??null},y(`cap`,S.message,S.upgradeUrl);else if(S.kind===`not-ready`){let e=(f.get(v)??0)+1;f.set(v,e),e>=3?d.add(v):b=!0}else{let e=(p.get(v)??0)+1;p.set(v,e),m.set(v,Date.now()+Math.min(3e5*2**(e-1),36e5))}}v(),b?C():w()},E=null,D=null,O=()=>k(!0),k=(e=!1)=>E?(D??=E.then(()=>(D=null,k(e))),D):(E=T(e).catch(e=>console.error(JSON.stringify({type:`auto-publish-error`,error:e.message}))).finally(()=>{E=null}),E);return _()&&C(),{changed(t){e.enabled()&&(d.delete(t),f.delete(t),n.add(t),s.add(t),v(),C())},removed(e){l.delete(e),d.delete(e),a&&={...a,keys:a.keys.filter(t=>t!==e)},n.delete(e)&&v()},flush:()=>k(),active:()=>E!==null||e.enabled()&&!(i&&i.token===yr(e.token()))&&[...n].some(e=>!l.has(e)&&!d.has(e)&&!o(e)&&!h(e)),close:S}}const Er={"X-Ryugi-Version":y},Dr=()=>f.default.hostname().replace(/\.local$/,``);var Or=class{origin;credentialsFile;version;stored;timer;starting=null;constructor(e,t,n){this.origin=e,this.credentialsFile=t,this.version=n,this.stored=this.read(),this.stored&&this.schedule(this.stored.interval)}get file(){return p.default.join(p.default.dirname(this.credentialsFile),`device-login.json`)}read(){try{let e=JSON.parse(d.default.readFileSync(this.file,`utf8`));return e.origin!==this.origin||Date.parse(e.expiresAt)<=Date.now()?(d.default.rmSync(this.file,{force:!0}),null):e}catch{return null}}save(e){if(this.stored=e,!e){d.default.rmSync(this.file,{force:!0});return}d.default.mkdirSync(p.default.dirname(this.file),{recursive:!0,mode:448});let t=`${this.file}.${process.pid}.tmp`;d.default.writeFileSync(t,JSON.stringify(e),{mode:384}),d.default.renameSync(t,this.file)}pending(){if(this.stored&&Date.parse(this.stored.expiresAt)<=Date.now()&&this.end(),!this.stored)return null;let{code:e,url:t,expiresAt:n}=this.stored;return{code:e,url:t,expiresAt:n}}async start(e){return this.pending()||(this.starting??=this.request(e).finally(()=>{this.starting=null}),this.starting)}async request(e){let t=await fetch(`${this.origin}/auth/device`,{method:`POST`,headers:{...Er,"Content-Type":`application/json`},body:JSON.stringify({name:Dr(),version:this.version,...e?{source:e}:{}})}),n=await t.json().catch(()=>({}));if(!t.ok||typeof n.deviceCode!=`string`||typeof n.userCode!=`string`||typeof n.verificationUriComplete!=`string`)throw Error(typeof n.error==`string`?n.error:`HTTP ${t.status}`);let r=typeof n.expiresIn==`number`?n.expiresIn:600,i={origin:this.origin,deviceCode:n.deviceCode,code:n.userCode,url:n.verificationUriComplete,expiresAt:new Date(Date.now()+r*1e3).toISOString(),interval:typeof n.interval==`number`?n.interval:5};return this.save(i),this.schedule(i.interval),this.pending()}schedule(e){clearTimeout(this.timer),this.timer=setTimeout(()=>void this.poll(),Math.max(e,.2)*1e3),this.timer.unref?.()}end(){clearTimeout(this.timer),this.timer=void 0,this.save(null)}async poll(){let e=this.stored;if(!e||this.pending()===null)return;let t;try{t=await fetch(`${this.origin}/auth/device/token`,{method:`POST`,headers:{...Er,"Content-Type":`application/json`},body:JSON.stringify({deviceCode:e.deviceCode})})}catch{this.schedule(Math.max(e.interval,5));return}if(this.stored!==e)return;let n=await t.json().catch(()=>({}));if(t.ok&&typeof n.token==`string`&&typeof n.login==`string`)xt(this.credentialsFile,{origin:this.origin,token:n.token,login:n.login}),this.end();else{if(n.code===`authorization_pending`)return this.schedule(e.interval);if(n.code===`slow_down`)return this.save({...e,interval:e.interval+5}),this.schedule(e.interval+5);if(n.code===`access_denied`||n.code===`expired_token`)return this.end();this.schedule(Math.max(e.interval,5))}}stop(){clearTimeout(this.timer),this.timer=void 0}};const kr=/* @__PURE__ */ new Map;function Ar(e,t,n){let r=`${e}\0${p.default.resolve(t)}`,i=kr.get(r);return i||kr.set(r,i=new Or(e,t,n)),i}function jr(){for(let e of kr.values())e.stop();kr.clear()}const Mr=20971520,Nr=e=>e===`preparing`||e===`uploading`||e===`publishing`,Pr=[`1d`,`7d`,`30d`,`never`],Fr=e=>Pr.includes(e),Ir=(e,t)=>t?`${e}#ryugi-host=${t}`:e,Lr=e=>e===`private`||e===`public`;function Rr(e){let t=e?.visibility??`private`,n=e?.cloud,r=!!n?.publishedAt;return{published:r,visibility:t,access:t===`private`&&n?.keyed?`key`:t,onProfile:n?.onProfile===!0,url:r?n.url:null,synced:!r||n.visibility===t}}const zr=()=>({version:1,artifacts:{}});function Br(e){try{let t=JSON.parse(d.default.readFileSync(e,`utf8`));if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Expected a config object`);return t}catch(e){if(e.code===`ENOENT`)return zr();throw e}}const Vr=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`);function Hr(e){if(typeof e!=`object`||!e)return!1;let{id:t,url:n,publishedAt:r,visibility:i}=e;return typeof t==`string`&&typeof n==`string`&&(typeof r==`string`||r===null)&&Lr(i)}function Ur({id:e,url:t,publishedAt:n,visibility:r,fingerprint:i,onProfile:a,keyed:o,modulesSynced:s,sourceHash:c,identitySynced:l}){return{id:e,url:t,publishedAt:n,visibility:r,...typeof i==`string`?{fingerprint:i}:{},...typeof a==`boolean`?{onProfile:a}:{},...o===!0?{keyed:o}:{},...Vr(s)?{modulesSynced:s}:{},...typeof c==`string`?{sourceHash:c}:{},...l===!0?{identitySynced:l}:{}}}function Wr(e){let t=zr();if(typeof e!=`object`||!e)return t;let n=e.output;n&&typeof n==`object`&&`format`in n&&[`brief`,`json`,`jsonl`].includes(String(n.format))&&(t.output={format:n.format});let{autoPublish:r,modulesSynced:i,space:a}=e;typeof r==`boolean`&&(t.autoPublish=r),typeof a==`string`&&a&&(t.space=a),typeof i==`string`&&(t.modulesSynced=i);let o=e.artifacts;if(typeof o!=`object`||!o)return t;for(let[e,n]of Object.entries(o)){if(typeof n!=`object`||!n)continue;let{visibility:r,cloud:i,autoPublish:a,modules:o,project:s}=n;if(r!==void 0&&!Lr(r))continue;let c={};r&&(c.visibility=r),Hr(i)&&(c.cloud=Ur(i)),a===!1&&(c.autoPublish=!1),Vr(o)&&(c.modules=o),typeof s==`string`&&s&&(c.project=s),t.artifacts[e]=c}return t}function Gr(e){let t;try{t=d.default.readFileSync(e,`utf8`)}catch{return{config:zr()}}try{return{config:Wr(JSON.parse(t))}}catch(e){return{config:zr(),warning:`config.json is not valid JSON: ${e.message}`}}}const Kr=[`config.json`,`artifacts/*`,`!artifacts/document/`,`artifacts/document/*/.artifact-id`];function qr(e){let t=p.default.join(e,`.gitignore`),n=``;try{n=d.default.readFileSync(t,`utf8`)}catch{}let r=new Set(n.split(/\r?\n/).map(e=>e.trim())),i=Kr.filter(e=>!r.has(e));i.length!==0&&d.default.writeFileSync(t,`${n}${n===``||n.endsWith(`
85
- `)?``:`
86
- `}${i.join(`
87
- `)}\n`)}function Jr(e){d.default.mkdirSync(p.default.dirname(e),{recursive:!0}),qr(p.default.dirname(e)),d.default.existsSync(e)||U(e,zr())}function Yr(e,t,n){let{config:r,warning:i}=Gr(e);if(i)throw Error(i);let a={...r.artifacts[t]};if(n.visibility&&(a.visibility=n.visibility),n.cloud===null)delete a.cloud;else if(n.cloud){let e=a.cloud?.id===n.cloud.id?a.cloud:void 0;a.cloud={...e?.modulesSynced?{modulesSynced:e.modulesSynced}:{},...e?.identitySynced?{identitySynced:e.identitySynced}:{},...n.cloud}}n.autoPublish===null?delete a.autoPublish:n.autoPublish===!1&&(a.autoPublish=!1),n.modules===null?delete a.modules:n.modules&&(a.modules=n.modules),n.project===null?delete a.project:n.project&&(a.project=n.project);let o=Br(e);o.artifacts??={};let s={...o.artifacts[t]};if(n.visibility&&(s.visibility=a.visibility),n.cloud){let e={...s.cloud?.id===n.cloud.id?s.cloud:{}};for(let t of Object.keys(Ur(e)))delete e[t];s.cloud={...e,...a.cloud}}return n.autoPublish===!1&&(s.autoPublish=!1),n.modules&&(s.modules=n.modules),n.project&&(s.project=n.project),n.project===null&&delete s.project,n.cloud===null&&delete s.cloud,n.autoPublish===null&&delete s.autoPublish,n.modules===null&&delete s.modules,o.artifacts[t]=s,U(e,o),a}function Xr(e,t){let n=Br(e);n.modulesSynced=t,d.default.mkdirSync(p.default.dirname(e),{recursive:!0}),U(e,n)}function Zr(e,t){let n=Br(e);t===null?delete n.autoPublish:n.autoPublish=t,d.default.mkdirSync(p.default.dirname(e),{recursive:!0}),U(e,n)}function Qr(e,t){let n=Br(e);n.space=t,d.default.mkdirSync(p.default.dirname(e),{recursive:!0}),U(e,n)}const $r=e=>p.default.join(p.default.dirname(e),`config.json`);function ei(e,t=!1){try{let n=JSON.parse(d.default.readFileSync(e,`utf8`));if(typeof n==`object`&&n&&!Array.isArray(n))return n;if(t)throw Error(`Expected a configuration object: ${e}`);return{}}catch(e){if(t&&e.code!==`ENOENT`)throw e;return{}}}function ti(e){let t=ei(e).autoPublish;return typeof t==`boolean`?t:void 0}function ni(e,t,n=()=>{}){let r=ei(e,!0);n(),d.default.mkdirSync(p.default.dirname(e),{recursive:!0,mode:448}),U(e,{...r,autoPublish:t})}function ri(e){let t=ei(e);return t.autoPublishPostponed===!0?(ni(e,!1),`off`):(d.default.mkdirSync(p.default.dirname(e),{recursive:!0,mode:448}),U(e,{...t,autoPublishPostponed:!0}),`postponed`)}function ii(e){ti(e)===void 0&&ni(e,!0)}function ai({globalFile:e,projectFile:t}){return Gr(t).config.autoPublish??ti(e)??!1}const oi=2400,si=e=>e.x+e.w/2,ci=e=>e.y+e.h/2,li=e=>e===`left`||e===`right`;function ui(e,t,n){let r=e.boards[n],i=e.notes?.[n];return r&&i?null:r?.page===t?{id:n,board:!0,rect:{x:r.x,y:r.y-48,w:r.w,h:r.h+48}}:i?.kind===`condition`&&i.page===t?{id:n,board:!1,rect:ve(i)}:null}function di(e,t){let n=[...Object.keys(e.boards),...Object.keys(e.notes??{})];return[...new Set(n)].flatMap(n=>ui(e,t,n)??[])}function fi(e,t,n){return t===`left`?{x:e.x,y:ci(e)+n}:t===`right`?{x:e.x+e.w,y:ci(e)+n}:t===`top`?{x:si(e)+n,y:e.y}:{x:si(e)+n,y:e.y+e.h}}function pi(e,t,n){let r=Math.min(e.x,t.x),i=Math.max(e.x,t.x),a=Math.min(e.y,t.y),o=Math.max(e.y,t.y);return a===o?a>n.y&&a<n.y+n.h&&r<n.x+n.w&&i>n.x:r>n.x&&r<n.x+n.w&&a<n.y+n.h&&o>n.y}function mi(e,t,n){return t.filter(t=>!n.has(t.id)&&e.some((n,r)=>r+1<e.length&&pi(n,e[r+1],t.rect))).map(e=>e.id)}function hi(e,t,n){let r=fi(e.from.rect,e.fromSide,t),i=fi(e.to.rect,e.toSide,n);if(li(e.fromSide)!==li(e.toSide))return[r,li(e.fromSide)?{x:i.x,y:r.y}:{x:r.x,y:i.y},i];if(li(e.fromSide)){if(Math.abs(r.y-i.y)<.5)return[r,{x:i.x,y:r.y}];let e=(r.x+i.x)/2;return[r,{x:e,y:r.y},{x:e,y:i.y},i]}if(Math.abs(r.x-i.x)<.5)return[r,{x:r.x,y:i.y}];let a=(r.y+i.y)/2;return[r,{x:r.x,y:a},{x:i.x,y:a},i]}function gi(e,t,n){let r=e.rect,i=t.rect,a=si(i)>=si(r),o=ci(i)>=ci(r);if(r.y<i.y+i.h&&i.y<r.y+r.h)return a?[`right`,`left`]:[`left`,`right`];if(r.x<i.x+i.w&&i.x<r.x+r.w)return o?[`bottom`,`top`]:[`top`,`bottom`];let s=[[a?`right`:`left`,o?`top`:`bottom`],[o?`bottom`:`top`,a?`left`:`right`]],c=/* @__PURE__ */ new Set([e.id,t.id]),l=([r,i],a)=>{let o=hi({from:e,to:t,fromSide:r,toSide:i},0,0),s=r===`top`&&e.board||i===`top`&&t.board,l=a===+!e.board;return mi(o,n,c).length*100+(s?10:0)+ +!l};return l(s[0],0)<=l(s[1],1)?s[0]:s[1]}function _i(e){let t=/* @__PURE__ */ new Map;for(let n of e)for(let[e,r,i,a]of[[`from`,n.from,n.fromSide,n.to],[`to`,n.to,n.toSide,n.from]]){let o=`${r.id}\n${i}`,s=li(i),c=t.get(o)??[];c.push({key:`${n.id}\n${e}`,edge:n.id,along:s?ci(a.rect):si(a.rect),length:s?r.rect.h:r.rect.w}),t.set(o,c)}let n=/* @__PURE__ */ new Map;for(let e of t.values()){e.sort((e,t)=>e.along-t.along||(e.edge<t.edge?-1:1));let t=e[0].length,r=Math.min(160,t/(e.length+1));e.forEach((i,a)=>{n.set(i.key,{offset:(a-(e.length-1)/2)*r,size:e.length,limit:t/2-r/2})})}return n}function vi(e,t,n){let r=e.label?.trim();if(!r)return null;let i=!e.from.board,a=i?28:32,o=Math.ceil(me(r,a)+32),s=Math.ceil(a*1.4),c=(e,t,r,i)=>{let a=r?i-48:oi,o={x:e-oi/2,y:t-s/2,w:oi,h:s};for(let{rect:t}of n){if(!Ce(o,t))continue;let n=t.x>=e?t.x-e:e>=t.x+t.w?e-(t.x+t.w):0;a=Math.min(a,n*2-24)}return Math.max(0,a)},l=t.slice(0,-1).map((e,n)=>{let r=t[n+1];return{a:e,b:r,flat:e.y===r.y,length:Math.abs(e.x-r.x)+Math.abs(e.y-r.y)}}).sort((e,t)=>t.length-e.length),u=null;for(let{a:e,b:t,flat:n,length:a}of l){let l=(e.x+t.x)/2,d=(e.y+t.y)/2,f=n||a>=s+48?c(l,d,n,a):0,p={text:r,branch:i,x:l,y:d,w:o,h:s,room:f};if(f>=o)return p;(!u||f>u.room)&&(u=p)}return u}function yi(e,t){let n=Object.entries(e.edges??{});if(n.length===0)return[];let r=di(e,t),i=[];for(let[a,o]of n){if(o.from===o.to)continue;let n=ui(e,t,o.from),s=ui(e,t,o.to);if(!n||!s)continue;let[c,l]=gi(n,s,r);i.push({id:a,from:n,to:s,fromSide:c,toSide:l,label:o.label})}let a=_i(i);return i.map(e=>{let t=a.get(`${e.id}\nfrom`),n=a.get(`${e.id}\nto`),i=t.offset,o=n.offset,s=li(e.fromSide);if(s===li(e.toSide)&&(s?Math.abs(ci(e.from.rect)-ci(e.to.rect))<.5:Math.abs(si(e.from.rect)-si(e.to.rect))<.5)&&i!==o){let e=t.size>=n.size,r=e?i:o;Math.abs(r)<=(e?n:t).limit&&(i=r,o=r)}let c=hi(e,i,o);return{id:e.id,points:c,label:vi(e,c,r)}})}function bi(e){let t=e.edges??{};if(Object.keys(t).length===0)return[];let n=[];for(let r of e.pages){let i=di(e,r.id).filter(e=>e.board);for(let a of yi(e,r.id)){let e=t[a.id];for(let t of mi(a.points,i,/* @__PURE__ */ new Set([e.from,e.to])))n.push(`edge "${a.id}" crosses board "${t}"`)}}return n}function xi(e,t,n){if(!Zn(t)||!Jn(n))throw Error(`Invalid artifact locator`);let r=p.default.join(e,t,n);return d.default.mkdirSync(r,{recursive:!0}),`/${t}/${Qn(r)}`}function Si(e,t,n){let r=er(e).artifacts.filter(e=>e.type===t&&Qn(e.dir)===n);if(r.length>1)throw Error(`Duplicate artifact ID: ${t}/${n} (${r.map(e=>e.id).join(`, `)})`);return r[0]??(W(e,t,n)?{type:t,id:n,dir:p.default.join(e,t,n)}:null)}const Ci=(e,t,{state:n})=>({required:!0,observed:n.ran}),wi=`comments.json`,Ti=/^marks\/[\w-]{1,100}-\d{1,2}\.jpg$/,Ei=2e3,Di=[`gap`,`inside`,`overlap`,`parent`,`size`],Oi=[`size`,`cross`],ki=[`bottom`,`left`,`right`,`top`],Ai=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ji=(e,t=100)=>typeof e==`string`&&e.length>0&&e.length<=t,Mi=e=>typeof e==`number`&&Number.isFinite(e);function Ni(e){return e===void 0?{}:ji(e,80)?{name:e}:null}function Pi(e){if(!Ai(e)||!ji(e.board)||!ji(e.path,Ei))return null;let t=Ni(e.name);return t&&{board:e.board,path:e.path,...t}}function Fi(e){return e===void 0?{}:ji(e,200)?{text:e}:null}function Ii(e){return e===void 0?{}:ji(e)?{board:e}:null}const Li=[`inside`,`above`,`below`,`left`,`right`];function Ri(e){if(!Ai(e))return null;let t={};for(let n of Li){if(e[n]===void 0)continue;let r=Pi(e[n]);if(!r)return null;t[n]=r}return t}function zi(e){let{x:t,y:n,w:r,h:i}=e;if(!Mi(t)||!Mi(n)||!Mi(r)||!Mi(i)||r<=0||i<=0)return null;let a=Fi(e.text),o=Ii(e.board);if(!a||!o)return null;let s={kind:`box`,...a,...o,x:t,y:n,w:r,h:i};if(e.nodes!==void 0){if(!Array.isArray(e.nodes)||e.nodes.length===0||e.nodes.length>20)return null;let t=e.nodes.map(Pi);if(t.some(e=>!e))return null;s.nodes=t}if(e.near!==void 0){let t=Ri(e.near);if(!t)return null;s.near=t}return Mi(e.t)&&e.t>=0&&(s.t=e.t),typeof e.crop==`string`&&Ti.test(e.crop)&&(s.crop=e.crop),s}function Bi(e){if(!Ai(e)||!Mi(e.x)||!Mi(e.y))return null;let t=Ii(e.board);if(!t)return null;let n={...t,x:e.x,y:e.y};if(e.box!==void 0){if(!Number.isInteger(e.box)||e.box<0||e.node!==void 0)return null;n.box=e.box}if(e.node!==void 0){if(!Ai(e.node)||!ji(e.node.path,Ei))return null;let t=Ni(e.node.name);if(!t)return null;n.node={path:e.node.path,...t}}return n}function Vi(e){let t=Fi(e.text),n=Bi(e.from),r=Bi(e.to);return t&&n&&r?{kind:`arrow`,...t,from:n,to:r}:null}function Hi(e){return Ai(e)&&Mi(e.x)&&Mi(e.y)?{x:e.x,y:e.y}:null}function Ui(e){if(!Ai(e))return null;let t=Hi(e.from),n=Hi(e.to);if(!t||!n||t.x!==n.x&&t.y!==n.y||!Mi(e.px)||e.px<0)return null;let r={from:t,to:n,px:e.px};return e.side===void 0?r:ki.includes(e.side)?{...r,side:e.side}:null}function Wi(e){if(!Ai(e)||!ji(e.path,Ei))return null;let t=Ni(e.name);return t&&{path:e.path,...t}}function Gi(e){let{source:t,relation:n}=e;if(!(t===`dom`?Di:t===`pixel`?Oi:null)?.includes(n)||!ji(e.board)||!Array.isArray(e.lines)||e.lines.length<1||e.lines.length>4)return null;let r=e.lines.map(Ui);if(r.some(e=>!e))return null;let i=Fi(e.text);if(!i)return null;let a={kind:`measure`,board:e.board,source:t,relation:n,lines:r,...i};if(e.size!==void 0){let t=Ai(e.size)?e.size:{};if(!Mi(t.w)||!Mi(t.h)||t.w<0||t.h<0)return null;a.size={w:t.w,h:t.h}}else if(n===`size`)return null;for(let n of[`from`,`to`]){if(e[n]===void 0)continue;let r=t===`dom`?Wi(e[n]):null;if(!r)return null;a[n]=r}if(e.tolerance!==void 0){let{tolerance:n}=e;if(t!==`pixel`||!Number.isInteger(n)||n<0||n>64)return null;a.tolerance=n}return a}function Ki(e){if(!Array.isArray(e)||e.length===0||e.length>12)return null;let t=[];for(let n of e){if(!Ai(n))return null;let e=n.kind===`box`?zi(n):n.kind===`arrow`?Vi(n):null;if(!e)return null;t.push(e)}let n=e=>e.box===void 0||t[e.box]?.kind===`box`;return t.every(e=>e.kind!==`arrow`||n(e.from)&&n(e.to))?t:null}function qi(e){if(!Array.isArray(e)||e.length===0||e.length>12)return null;let t=e.map(e=>Ai(e)&&e.kind===`measure`?Gi(e):null);return t.every(e=>e)?t:null}function Ji(e=[]){return e.flatMap(e=>e.kind===`measure`?[e.board]:e.kind===`box`?[...e.board?[e.board]:[],...(e.nodes??[]).map(e=>e.board)]:[e.from,e.to].flatMap(e=>e.board?[e.board]:[]))}function Yi(e,t){let n=e=>{let n=e.board?null:t(e.x,e.y);return n?{...e,x:e.x+n.dx,y:e.y+n.dy}:e};return e.map(e=>{if(e.kind===`measure`)return e;if(e.kind===`arrow`)return{...e,from:n(e.from),to:n(e.to)};let r=e.board?null:t(e.x+e.w/2,e.y+e.h/2);return r?{...e,x:e.x+r.dx,y:e.y+r.dy}:e})}function Xi(e,t){let n=JSON.stringify(e.comment??null).length<=262144?t(e.comment):null;if(!n)throw Error(`not a comment op`);return n}function Zi(e){return{version:1,threads:e.threads.filter(e=>!e.messages.every(e=>e.deleted)).map(e=>({...e,messages:e.messages.map(({avatar:e,...t})=>t)}))}}function Qi(e,t,n){let r=t.pages[n]?.notes??{};return Object.entries(e.notes??{}).filter(([e,t])=>t.page===n&&t.kind===`title`&&r[e]).map(([e,t])=>({id:e,text:t.text,rect:r[e]}))}function $i(e,t){return e.filter(e=>e.rect.y+e.rect.h<=t).sort((e,t)=>t.rect.y-e.rect.y)[0]}function ea(e,t){let n=[];for(let{id:r}of e.pages){let i=t.pages[r];if(!i)continue;let a=Qi(e,t,r),o=/* @__PURE__ */ new Map,s=Object.entries(e.groups??{}).map(([e,t])=>({id:e,group:t,rect:i.groups[e]})).filter(t=>!!t.rect&&t.group.boards.some(t=>e.boards[t]?.page===r)).sort((e,t)=>e.rect.y-t.rect.y||e.rect.x-t.rect.x);for(let{id:e,group:t,rect:n}of s){let r=$i(a,n.y),i=r?.id??null,s=o.get(i)??{title:r,choices:[]};t.choose===!0&&s.choices.push(e),o.set(i,s)}let c=e=>e?.rect.y??-1/0,l=Math.max(...[...o.values()].map(e=>c(e.title))),u=[...o.entries()].filter(([,e])=>e.choices.length>0).sort(([,e],[,t])=>c(e.title)-c(t.title));for(let[e,t]of u)n.push({id:e??`page:${r}`,page:r,title:t.title?.text??null,groups:t.choices,closed:c(t.title)<l})}return n}const ta=(e,t)=>e.find(e=>e.groups.includes(t));function na(e,t){let n={...e.boards},r=e.notes?{...e.notes}:void 0;for(let{kind:e,id:i,to:a}of t)e===`board`&&n[i]&&(n[i]={...n[i],x:a.x,y:a.y}),e===`note`&&r?.[i]&&(r[i]={...r[i],x:a.x,y:a.y});return{...e,boards:n,...r?{notes:r}:{}}}function ra(e){let t=[];for(let n of[...e].sort(([,e],[,t])=>e.y-t.y||e.x-t.x)){let e=t.find(e=>e.some(([,e])=>n[1].y<e.y+e.h&&e.y<n[1].y+n[1].h));e?e.push(n):t.push([n])}return t.flatMap(e=>e.sort(([,e],[,t])=>e.x-t.x).map(([e])=>e))}function ia(e,t){if(!e.groups)return e;let n=new Set(t),r={...e.groups};for(let[t,i]of Object.entries(r)){if(!i.boards.some(e=>n.has(e)))continue;let a=ra(i.boards.filter(t=>e.boards[t]).map(t=>[t,e.boards[t]])),o=i.boards.filter(t=>!e.boards[t]);r[t]={...i,boards:[...a,...o]}}return{...e,groups:r}}const aa=/ overlap$| overlaps group | covers board /;function oa(e){return ze(e,()=>!0).filter(e=>aa.test(e))}function sa(e){return JSON.stringify(ea(e,Se(e)).map(({id:e,groups:t,closed:n})=>[e,[...t].sort(),n]))}function ca(e){let t=new Set(oa(e)),n=sa(e);return e=>oa(e).every(e=>t.has(e))&&sa(e)===n}const la=(e,t)=>ca(e)(t),ua=e=>typeof e==`object`&&!!e&&Number.isFinite(e.x)&&Number.isFinite(e.y);function da(e){if(typeof e!=`object`||!e)return null;let{page:t,moves:n,undo:r}=e;if(typeof t!=`string`||!Array.isArray(n)||n.length===0||n.length>fa)return null;let i=[];for(let e of n){if(typeof e!=`object`||!e)return null;let{kind:t,id:n,from:r,to:a}=e;if(t!==`board`&&t!==`note`||typeof n!=`string`||!ua(r)||!ua(a))return null;i.push({kind:t,id:n,from:{x:r.x,y:r.y},to:{x:Math.round(a.x),y:Math.round(a.y)}})}return{page:t,moves:i,...r===!0?{undo:!0}:{}}}const fa=2e3,pa=(e,t)=>e.x===t.x&&e.y===t.y,ma=e=>(0,u.createHash)(`sha1`).update(e).digest(`hex`),ha=(e,t)=>`${e}:${t}`,ga=e=>`${JSON.stringify(e,null,2)}\n`;function _a(e,t,n){return t===`board`?e.boards[n]:e.notes?.[n]}function va(e,t){let n=[],r=/* @__PURE__ */ new Map;for(let{kind:i,id:a,from:o,to:s}of t){let t={x:s.x-o.x,y:s.y-o.y};i===`board`&&r.set(a,t);let c=i===`note`?e.notes?.[a]:void 0;c&&n.push({page:c.page,dx:t.x,dy:t.y,rect:ve(c),except:[]})}for(let t of Object.values(e.groups??{})){let i=r.get(t.boards[0]??``),a=ge(t,e.boards);if(!i||!a||!t.boards.every(e=>r.has(e)&&pa(r.get(e),i)))continue;let{page:o,...s}=a;n.push({page:o,dx:i.x,dy:i.y,rect:s,except:t.boards.map(t=>{let{x:n,y:r,w:i,h:a}=e.boards[t];return{x:n,y:r,w:i,h:a}})})}return n.filter(e=>e.dx!==0||e.dy!==0)}const ya=e=>typeof e==`object`&&!!e&&ua(e.to)&&Array.isArray(e.left)&&e.left.every(ua);function ba(e){let t={items:{},notices:[],seen:null};try{let n=JSON.parse(d.default.readFileSync(e,`utf8`));if(typeof n!=`object`||!n)return t;let r=typeof n.items==`object`&&n.items!==null?n.items:{};return{items:Object.fromEntries(Object.entries(r).filter(([,e])=>ya(e))),notices:Array.isArray(n.notices)?n.notices.filter(e=>typeof e==`string`):[],seen:typeof n.seen==`string`?n.seen:null}}catch{return t}}function xa({root:e,stateDir:t,shiftPins:n}){let r=/* @__PURE__ */ new Map,i=e=>p.default.join(t,`artboard`,e,`arrangement.json`),a=e=>{let t=r.get(e);return t||(t=ba(i(e)),r.set(e,t)),t},o=e=>U(i(e),a(e)),s=t=>{let n=W(e,`artboard`,t);if(!n)return null;let r=p.default.join(n,`canvas.json`);try{let e=d.default.readFileSync(r,`utf8`),t=JSON.parse(e);return Ie(t).length>0?null:{file:r,text:e,canvas:t}}catch{return null}},c=(e,t,n)=>{U(t,n),a(e).seen=ma(ga(n))};function l(e,{page:t,moves:r,undo:i}){let l=s(e);l&&ma(l.text)!==a(e).seen&&u(e);let d=s(e);if(!d||r.length===0)return{ok:!1,reason:`unknown`};let{canvas:f,file:p}=d;for(let{kind:e,id:n,from:i}of r){let r=_a(f,e,n);if(!r||r.page!==t||!pa(r,i))return{ok:!1,reason:`stale`}}let m=na(f,r);if(!i&&!la(f,m))return{ok:!1,reason:`invalid`};let h=r.filter(e=>e.kind===`board`).map(e=>e.id),g=va(f,r);c(e,p,ia(m,h)),g.length>0&&n(e,g);let _=a(e);for(let{kind:e,id:t,from:n,to:i}of r){let r=ha(e,t),a=[..._.items[r]?.left??[],n].filter((e,t,n)=>!pa(e,i)&&n.findIndex(t=>pa(t,e))===t);_.items[r]={to:i,left:a.slice(-50)}}return o(e),{ok:!0}}function u(e){let t=a(e),n=s(e);if(!n||t.seen===ma(n.text))return!1;let{canvas:r,file:i}=n,l=[],u=[];for(let[e,n]of Object.entries(t.items)){let i=e.slice(0,e.indexOf(`:`)),a=e.slice(e.indexOf(`:`)+1),o=_a(r,i,a);o&&pa(o,n.to)||(!o||!n.left.some(e=>pa(e,o))?delete t.items[e]:(l.push({kind:i,id:a,from:{x:o.x,y:o.y},to:n.to}),u.push(`${i} "${a}" was moved by your human partner; your write put it back, so their position was kept. Re-read canvas.json before editing.`)))}if(t.notices=u,t.seen=ma(n.text),l.length>0){let t=l.filter(e=>e.kind===`board`).map(e=>e.id);c(e,i,ia(na(r,l),t))}return o(e),l.length>0}function f(e,t){try{return l(e,t)}catch{return{ok:!1,reason:`unknown`}}}function m(e){try{return u(e)}catch{return!1}}return{apply:f,guard:m,notices:e=>a(e).notices}}const Sa=/^[a-z0-9][a-z0-9-]{0,63}$/,Ca=e=>e===null||typeof e==`string`&&e.length<=2e4;function wa(e){let t={};if(e.ask!==void 0){if(typeof e.ask!=`string`||!Sa.test(e.ask))return null;t.ask=e.ask}if(e.choice!==void 0){if(!Ca(e.choice))return null;t.choice=e.choice}if(e.answer!==void 0){if(!Ca(e.answer))return null;t.answer=e.answer}if(e.note!==void 0){if(e.note!==!0)return null;t.note=!0}if(e.submit!==void 0){if(typeof e.submit!=`boolean`)return null;t.submit=e.submit}if(e.asks!==void 0){if(!Array.isArray(e.asks)||!e.asks.every(e=>typeof e==`string`))return null;t.asks=e.asks}if(e.remote!==void 0){if(e.remote!==!0)return null;t.remote=!0}if(e.of!==void 0){if(typeof e.of!=`string`)return null;t.of=e.of}return t}const Ta=(e,t)=>JSON.stringify(wa(e))===JSON.stringify(wa(t)),Ea=e=>e.anchor.ask!==void 0||e.anchor.submit!==void 0,Da=e=>e.messages.find(e=>!e.deleted);function Oa(e,t){return e.map((e,t)=>({thread:e,index:t,message:Da(e)})).filter(e=>e.message&&t(e.thread.anchor)).sort((e,t)=>e.message.at.localeCompare(t.message.at)||e.index-t.index)}function ka(e){let t=new Set(Oa(e,e=>e.submit===!1&&e.of!==void 0).map(e=>e.thread.anchor.of));return Oa(e,e=>e.submit===!0).map(({thread:e,message:n})=>({id:e.id,at:n.at,asks:e.anchor.asks??[],withdrawn:t.has(e.id)}))}const Aa=e=>ka(e).at(-1)??null;function ja(e,t){let n=new Set(ka(t).filter(e=>!e.withdrawn).flatMap(e=>e.asks)),r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;for(let{thread:e,message:n}of Oa(t,e=>e.ask!==void 0&&e.note===void 0))e.anchor.remote?i.set(e.anchor.ask,[...i.get(e.anchor.ask)??[],{anchor:e.anchor,name:n.name}]):r.set(e.anchor.ask,e.anchor);let a=/* @__PURE__ */ new Set;for(let[e,t]of i){if(r.has(e))continue;let n=t[0].anchor;t.every(({anchor:e})=>(e.choice??null)===(n.choice??null)&&(e.answer??null)===(n.answer??null))&&(r.set(e,t.at(-1).anchor),a.add(e))}let o=/* @__PURE__ */ new Map;for(let{thread:e,message:n}of Oa(t,e=>e.ask!==void 0&&e.note===!0))o.set(e.anchor.ask,{text:n.text,by:n.name});let s=new Set(e.map(e=>e.id)),c=[.../* @__PURE__ */ new Set([...r.keys(),...i.keys(),...o.keys()])].filter(e=>!s.has(e)).map(e=>({id:e,blockId:``,options:[]}));return[...e,...c].map(e=>{let t=r.get(e.id),c=o.get(e.id),l=!s.has(e.id),u=new Set(e.options.map(e=>e.value)),d=t?.choice??null,f=d!==null&&(l||u.has(d))?d:null,p=t?.answer?.trim()?t.answer:null,m=f!==null||p!==null,h=!m&&e.recommend!==void 0,g=m?f:e.recommend??null,_=l?`orphan`:c?`settled`:n.has(e.id)||a.has(e.id)?`submitted`:`draft`,v=i.get(e.id)?.map(({anchor:e,name:t})=>({...t?{name:t}:{},choice:e.choice??null,text:e.answer?.trim()?e.answer:null}));return{id:e.id,blockId:e.blockId,state:_,...e.recommend?{recommend:e.recommend}:{},...e.placeholder?{placeholder:e.placeholder}:{},options:e.options,choice:g,text:p,byRecommendation:h,changed:m&&(p!==null||f!==e.recommend),...c?{note:c.text,...c.by?{noteBy:c.by}:{}}:{},...d!==null&&f===null?{staleChoice:d}:{},...v?{others:v}:{}}})}function Ma(e,t){let n=e.find(e=>e.id===t.ask);if(!n)throw Error(`no question ${t.ask} in this document`);if(t.choice!==null&&!n.options.some(e=>e.value===t.choice))throw Error(`"${t.choice}" is not an option of ${t.ask}`)}function Na(e,t,n){Ma(e,n);let r=ja(e,t).find(e=>e.id===n.ask).state;if(r!==`draft`)throw Error(`${n.ask} is already ${r}; comment on it to change the answer`)}function Pa(e,t){let n=ja(e,t).filter(e=>e.state===`draft`).map(e=>e.id);if(!n.length)throw Error(`nothing to submit: every question is already submitted`);return{blockId:`*`,quote:``,submit:!0,asks:n}}function Fa(e){let t=Aa(e);if(!t||t.withdrawn)throw Error(`there is no submit to withdraw`);if(Oa(e,e=>e.note===!0&&e.ask!==void 0&&t.asks.includes(e.ask)).some(e=>e.message.at>=t.at))throw Error(`the agent has already written a note on this submit`);return{blockId:`*`,quote:``,submit:!1,of:t.id}}const Ia=e=>typeof e==`string`&&e.length>0&&e.length<=200;function La(e){if(typeof e!=`object`||!e)return null;let t=e;return t.kind===`node`?Ia(t.id)?{kind:`node`,id:t.id}:null:t.kind===`edge`&&Ia(t.from)&&Ia(t.to)&&typeof t.index==`number`&&Number.isSafeInteger(t.index)&&t.index>=0?{kind:`edge`,from:t.from,to:t.to,index:t.index}:null}function Ra(e,t){return!e||!t?e===t:e.kind===`node`?t.kind===`node`&&e.id===t.id:t.kind===`edge`&&e.from===t.from&&e.to===t.to&&e.index===t.index}const za=e=>e.blockIds??[e.blockId],Ba=()=>({version:1,threads:[]}),Va=e=>typeof e==`object`&&!!e,Ha={read:e=>{if(!Va(e)||typeof e.blockId!=`string`||!e.blockId)return null;let{blockIds:t,textRanges:n}=e,r=e.diagram===void 0?void 0:La(e.diagram);if(r===null||r&&(t!==void 0||n!==void 0)||t!==void 0&&(!Array.isArray(t)||!t.length||t[0]!==e.blockId||!t.every(e=>typeof e==`string`&&e.length>0&&e.length<=100)||new Set(t).size!==t.length))return null;let i=wa(e);if(!i)return null;let a=t??[e.blockId];return n!==void 0&&(!Array.isArray(n)||n.length!==a.length||!n.every((e,t)=>Va(e)&&e.blockId===a[t]&&typeof e.quote==`string`&&e.quote.length<=2e4&&typeof e.start==`number`&&Number.isSafeInteger(e.start)&&e.start>=0&&Number.isSafeInteger(e.start+e.quote.length)))?null:{blockId:e.blockId,...t?{blockIds:t}:{},...r?{diagram:r}:{},quote:typeof e.quote==`string`?e.quote:``,...n?{textRanges:n.map(({blockId:e,quote:t,start:n})=>({blockId:e,quote:t,start:n}))}:{},...i}},same:(e,t)=>Ta(e,t)&&e.quote===t.quote&&Ra(e.diagram,t.diagram)&&za(e).length===za(t).length&&za(e).every((e,n)=>e===za(t)[n])&&e.textRanges?.length===t.textRanges?.length&&(e.textRanges??[]).every((e,n)=>{let r=t.textRanges?.[n];return e.blockId===r?.blockId&&e.quote===r.quote&&e.start===r.start}),missing:`a new thread needs anchor.blockId; dropped it`};function Ua(e){let t=JSON.parse(e);if(!Va(t))throw Error(`comments.json must be an object`);if(!Array.isArray(t.threads))throw Error(`threads must be an array`);return t.threads.forEach((e,t)=>{if(!Va(e))throw Error(`threads[${t}] must be an object`);if(e.messages!==void 0&&!Array.isArray(e.messages))throw Error(`threads[${t}].messages must be an array`);if(!e.id&&!Va(e.anchor))throw Error(`threads[${t}] needs an anchor`)}),t}const Wa=e=>!!e.id&&(e.author===`human`||e.author===`agent`)&&typeof e.text==`string`&&typeof e.at==`string`;function Ga(e,t=Ha){let n=[];for(let r of e.threads){let e=t.read(r.anchor);if(!r.id||!e||!r.statusAt||r.status!==`open`&&r.status!==`resolved`)continue;let i=(r.messages??[]).filter(Wa),a=r.statusBy===`human`||r.statusBy===`agent`?{statusBy:r.statusBy}:{};n.push({id:r.id,anchor:e,status:r.status,statusAt:r.statusAt,...a,messages:i})}return{version:1,threads:n}}const Ka=e=>e.editedAt??e.at;function qa(e,t,n,r,i){if(e.deleted)return e;let a=t.editedAt??t.at??e.at;if(a<Ka(e))return e;let o=t.text!==void 0&&t.text!==e.text,s=t.deleted===!0;return!o&&!s?e:e.author===`human`&&n===`agent`?(i.push(`message ${e.id}: the agent cannot change a human message; kept the original`),e):s?{...e,text:``,deleted:!0,editedAt:r}:{...e,text:t.text,editedAt:a===Ka(e)?r:a}}const Ja=e=>({...e?.name?{name:e.name}:{},...e?.avatar?{avatar:e.avatar}:{}});function Ya(e,t,n,r,i,a,o){let s=[...e.messages];for(let c of t.messages??[]){let t=c.id?s.findIndex(e=>e.id===c.id):-1;if(t>=0){s[t]=qa(s[t],c,n,r,a);continue}let l=c.author??n;(c.id||!s.some(e=>e.author===l&&e.text===c.text))&&(n===`agent`&&l===`human`?a.push(`thread ${e.id}: the agent cannot write human messages; dropped one`):typeof c.text==`string`&&c.text.length!==0&&s.push({id:c.id??i(),author:l,...Ja({name:o}),text:c.text,at:c.at??r}))}s.sort((e,t)=>e.at<t.at?-1:+(e.at>t.at));let{status:c,statusAt:l,statusBy:u}=e;if(t.status&&t.status!==e.status){let i=t.statusAt&&t.statusAt!==e.statusAt?t.statusAt:r;i>=e.statusAt&&(c=t.status,l=i,u=n)}return{...e,status:c,statusAt:l,...u?{statusBy:u}:{},messages:s}}function Xa(e,t,n){let r=n.read(t.anchor);return!!r&&n.same(e.anchor,r)&&e.messages[0]?.text===t.messages?.[0]?.text}function Za(e,t,n,r,i,a,o=Ha){let s=[],c=[...e.threads];for(let e of t.threads){let t=e.id?c.findIndex(t=>t.id===e.id):c.findIndex(t=>Xa(t,e,o));if(t>=0){c[t]=Ya(c[t],e,n,r,i,s,a);continue}let l=o.read(e.anchor);if(!l){s.push(o.missing);continue}let u={id:e.id??i(),anchor:l,status:`open`,statusAt:r,statusBy:n,messages:[]};c.push(Ya(u,{...e,status:e.status??`open`},n,r,i,s,a))}return{file:{version:1,threads:c},warnings:s}}const Qa=(e,t,n)=>({...e,threads:e.threads.map(e=>e.id===t?n(e):e)}),$a=(e,t,n)=>({...e,messages:e.messages.map(e=>e.id===t&&e.author===`human`&&!e.deleted?n(e):e)});function eo(e,t,n,r,i,a){return{id:i(),anchor:e,status:`open`,statusAt:r,statusBy:t,messages:[{id:i(),author:t,...Ja(a),text:n,at:r}]}}function to(e,t,n,r,i){return t.op===`create`?{...e,threads:[...e.threads,eo(Ha.read(t),`human`,t.text,n,r,i)]}:no(e,t,n,r,i)}function no(e,t,n,r,i){switch(t.op){case`reply`:return Qa(e,t.threadId,e=>({...e,messages:[...e.messages,{id:r(),author:`human`,...Ja(i),text:t.text,at:n}]}));case`edit`:return Qa(e,t.threadId,e=>$a(e,t.messageId,e=>({...e,text:t.text,editedAt:n})));case`delete`:return Qa(e,t.threadId,e=>$a(e,t.messageId,e=>({...e,text:``,deleted:!0,editedAt:n})));case`resolve`:case`reopen`:return Qa(e,t.threadId,e=>({...e,status:t.op===`resolve`?`resolved`:`open`,statusAt:n,statusBy:`human`}))}}function ro(e){if(e.status===`resolved`)return null;let t=e.messages.filter(e=>!e.deleted).at(-1);return t?t.author===`human`?`agent`:`human`:null}const io=e=>(e.statusBy??`human`)===`human`;function ao(e){let t=e.messages.filter(e=>e.author===`human`).map(Ka);return io(e)?[...t,e.statusAt]:t}function oo(e,t){let n=/* @__PURE__ */ new Set,r=[];return e.messages.forEach((e,i)=>{if(e.author!==`human`)return;let a=e.at>t;e.deleted?!a&&Ka(e)>t&&n.add(`deleted`):a?(n.add(i===0?`new-thread`:`new-message`),r.push(e.id)):Ka(e)>t&&(n.add(`edited`),r.push(e.id))}),!n.has(`new-thread`)&&io(e)&&e.statusAt>t&&e.messages.some(e=>e.at<=t)&&n.add(e.status===`resolved`?`resolved`:`reopened`),{changes:[...n],messageIds:r}}function so(e){let t=e.messages.filter(e=>!e.deleted),n=t.map(e=>e.author).lastIndexOf(`agent`)+1;return{changes:[t.length===1?`new-thread`:`new-message`],messageIds:t.slice(n).map(e=>e.id)}}function co(e,t){let n=[],r=t;for(let i of e.threads){for(let e of ao(i))(!r||e>r)&&(r=e);let e=t===null?ro(i)===`agent`?so(i):null:oo(i,t);e&&e.changes.length>0&&n.push({...i,...e})}return{threads:n,newest:r}}function lo(e,t,n,r,i){if(t.op===`add`){let a=eo(Ha.read(t),`agent`,t.text,n,r,{name:i});return{file:{...e,threads:[...e.threads,a]},threadId:a.id,messageId:a.messages[0].id}}return uo(e,t,n,r,i)}function uo(e,t,n,r,i){if(!e.threads.some(e=>e.id===t.threadId))throw Error(`no thread ${t.threadId}`);if(t.op===`resolve`)return{file:Qa(e,t.threadId,e=>({...e,status:`resolved`,statusAt:n,statusBy:`agent`})),threadId:t.threadId};let a={id:r(),author:`agent`,...Ja({name:i}),text:t.text,at:n};return{file:Qa(e,t.threadId,e=>({...e,messages:[...e.messages,a]})),threadId:t.threadId,messageId:a.id}}const fo=(e,t)=>e.at<t.at?-1:+(e.at>t.at),po=e=>({id:e.id,author:`human`,name:e.author.login,...e.author.avatarUrl?{avatar:e.author.avatarUrl}:{},text:e.text,at:e.at});function mo(e,t){return t({blockId:(Va(e.anchor)?e.anchor:{}).blockId,quote:``,ask:e.askId,choice:e.answer?.choice??null,answer:e.answer?.answer??null,remote:!0})}function ho(e,t,n){let r=[...e.threads],i=[];for(let e of t){let t=r.find(t=>t.id===e.threadId);if(e.kind===`thread`){let a=n(e.anchor);!t&&a&&r.push({id:e.threadId,anchor:a,status:`open`,statusAt:e.at,statusBy:`human`,messages:[po(e)]}),(t||a)&&i.push(e.id)}else if(e.kind===`answer`){let a=mo(e,n);!t&&a&&r.push({id:e.threadId,anchor:a,status:`open`,statusAt:e.at,statusBy:`human`,messages:[po(e)]}),(t||a)&&i.push(e.id)}else e.kind===`reply`&&t&&(t.messages.some(t=>t.id===e.id)||(r=r.map(n=>n===t?{...n,messages:[...n.messages,po(e)].sort(fo)}:n)),i.push(e.id))}return{file:{...e,threads:r},applied:i}}const go=e=>e.anchor.choice!==void 0||e.anchor.submit!==void 0,_o=(e,t=100)=>typeof e==`string`&&e.length>0&&e.length<=t,vo=e=>typeof e==`number`&&Number.isFinite(e),yo=e=>vo(e)&&e>=0&&e<=1;function bo(e){if(!Array.isArray(e)||e.length===0||e.length>50)return null;let t=[];for(let n of e){if(!Va(n)||!_o(n.board)||!_o(n.path,2e3))return null;let e=Ni(n.name);if(!e)return null;t.push({board:n.board,path:n.path,...e})}return t}function xo(e){if(!Va(e)||Array.isArray(e))return null;let t=Object.entries(e);return t.length>50||!t.every(([e,t])=>_o(e)&&_o(t))?null:Object.fromEntries(t)}function So(e){if(!Va(e)||!_o(e.page)||!vo(e.x)||!vo(e.y))return null;let t={page:e.page,x:e.x,y:e.y};if(e.board!==void 0){if(!_o(e.board))return null;t.board=e.board}if(e.group!==void 0){if(!_o(e.group))return null;t.group=e.group}if(e.verdict!==void 0){if(!t.group||e.verdict!==`pass`&&e.verdict!==`reject`)return null;t.verdict=e.verdict}if(e.choice!==void 0){if(!t.group||e.choice!==null&&!_o(e.choice))return null;t.choice=e.choice}if(e.round!==void 0){if(!_o(e.round))return null;t.round=e.round}if(e.submit!==void 0){if(!t.round||typeof e.submit!=`boolean`)return null;t.submit=e.submit}if(e.nodes!==void 0){let n=bo(e.nodes);if(!n)return null;t.nodes=n}if(e.offset!==void 0){let n=e.offset;if(!t.nodes||!Va(n)||!yo(n.x)||!yo(n.y))return null;t.offset={x:n.x,y:n.y}}if(e.marks!==void 0){let n=Ki(e.marks);if(!n)return null;t.marks=n}if(e.measures!==void 0){let n=qi(e.measures);if(!n||(t.marks?.length??0)+n.length>12)return null;t.measures=n}if(e.hashes!==void 0){let n=xo(e.hashes);if(!n)return null;t.hashes=n}return t}const Co=e=>[...e.marks??[],...e.measures??[]],wo={read:So,same:(e,t)=>e.page===t.page&&e.board===t.board&&e.group===t.group&&e.verdict===t.verdict&&e.choice===t.choice&&e.round===t.round&&e.submit===t.submit&&e.x===t.x&&e.y===t.y,missing:`a new thread needs a board anchor (page, x, y); dropped it`},To=()=>({version:1,threads:[]}),Eo=e=>Ga(e,wo),Do=(e,t,n,r,i,a)=>Za(e,t,n,r,i,a,wo);function Oo(e,t,n){if(t.anchor.verdict!==`pass`)return{...e,threads:[...e.threads,t]};let r={status:`resolved`,statusAt:n,statusBy:t.statusBy},i=e=>e.anchor.group===t.anchor.group&&e.anchor.verdict===`reject`&&e.status===`open`;return{...e,threads:[...e.threads.map(e=>i(e)?{...e,...r}:e),{...t,...r}]}}function ko(e,t,n){return{...e,threads:e.threads.map(e=>e.id===t.threadId?{...e,messages:e.messages.map(e=>e.id===t.messageId&&!e.deleted?{...e,text:``,deleted:!0,editedAt:n}:e)}:e)}}function Ao(e,t,n,r,i){if(t.op===`delete`&&e.threads.find(e=>e.id===t.threadId)?.anchor.verdict)return ko(e,t,n);if(t.op!==`create`)return no(e,t,n,r,i);let a=eo(t.anchor,`human`,t.text,n,r,i);return go(a)?{...e,threads:[...e.threads,{...a,status:`resolved`,statusAt:n,statusBy:`human`}]}:Oo(e,a,n)}function jo(e,t,n,r,i){if(t.op===`resolve`&&e.threads.find(e=>e.id===t.threadId)?.anchor.verdict===`reject`)throw Error(`a reject closes only when your human partner passes the group`);if(t.op===`add`){let a=eo(t.anchor,`agent`,t.text,n,r,{name:i}),o=go(a)?{...a,status:`resolved`,statusAt:n,statusBy:`agent`}:a;return{file:Oo(e,o,n),threadId:o.id,messageId:o.messages[0].id}}return uo(e,t,n,r,i)}const Mo=e=>e.messages.find(e=>!e.deleted);function No(e,t){let n;for(let r of e){let e=Mo(r);e&&t(r)&&(!n||e.at>=n.at)&&(n={thread:r,at:e.at,by:e.author===`agent`?`agent`:`human`})}return n}function Po(e,t,n){let r=No(e,e=>e.anchor.group===t&&e.anchor.choice!==void 0),i=r?.thread.anchor.choice??null;if(i)return{choice:i,byRecommendation:!1,at:r.at,by:r.by};let a=r?{at:r.at,by:r.by}:{};return n?{choice:n,byRecommendation:!0,...a}:{choice:null,byRecommendation:!1,...a}}function Fo(e,t){let n=No(e,e=>e.anchor.round===t&&e.anchor.submit!==void 0);return n?{submitted:n.thread.anchor.submit===!0,at:n.at,by:n.by}:{submitted:!1}}const Io=(e,t)=>`${Math.round(e)},${Math.round(t)}`;function Lo(e){let t=e.path.split(`>`).pop().trim();return e.name?`${/^[a-z][\w-]*/i.exec(t)?.[0]??t} "${e.name}"`:t}const Ro=e=>e?` — "${e}"`:``,zo=(e,t)=>`${e.t===void 0?``:` · at t=${e.t.toFixed(1)}s`}${e.crop?` · crop ${t(e.crop)}`:``}`,Bo=[[`inside`,`inside`],[`above`,`below`],[`below`,`above`],[`left`,`right of`],[`right`,`left of`]];function Vo(e,t,n){let r=`${Io(e.x,e.y)} ${Math.round(e.w)}×${Math.round(e.h)}`;if(!e.board){let i=Object.entries(t).filter(([,t])=>t.page===n&&t.x<e.x+e.w&&t.x+t.w>e.x&&t.y<e.y+e.h&&t.y+t.h>e.y).map(([e])=>e);return`box on page at ${r}${i.length?` over ${i.join(`, `)}`:``}`}let i=Bo.flatMap(([t,n])=>e.near?.[t]?[`${n} ${Lo(e.near[t])}`]:[]);if(e.nodes?.length){let t=e.near?.inside?`, inside ${Lo(e.near.inside)}`:``;return`box on ${e.board} around ${e.nodes.map(Lo).join(`, `)}${t}`}return`box on ${e.board} at ${r}${i.length?`, empty, ${i.join(`, `)}`:``}`}function Ho(e){return e.box===void 0?e.board&&e.node?`${e.board}: ${Lo(e.node)}`:`${e.board??`page`} at ${Io(e.x,e.y)}`:String(e.box+1)}const Uo={bottom:`below`,top:`above`,left:`left of`,right:`right of`},Wo=[`left`,`top`,`right`,`bottom`],Go=e=>Wo.flatMap(t=>e.filter(e=>e.side===t).map(e=>`${t} ${Math.round(e.px)}px`)).join(`, `),Ko=e=>`${Math.round(e.w)}×${Math.round(e.h)}`;function qo(e){if(e.source===`pixel`){let t=e.tolerance===void 0?``:`, tolerance ${e.tolerance}`,n=`measure on ${e.board} (screenshot${t}):`;if(e.relation===`size`&&e.size){let t=e.lines.flatMap(e=>[e.from,e.to]),r=Math.min(...t.map(e=>e.x)),i=Math.min(...t.map(e=>e.y));return`${n} size ${Ko(e.size)} at ${Io(r,i)}`}return`${n} ${e.lines.map(e=>`${e.from.y===e.to.y?`horizontal`:`vertical`} ${Math.round(e.px)}px from ${Io(e.from.x,e.from.y)} to ${Io(e.to.x,e.to.y)}`).join(`; `)}`}let t=e.from?Lo(e.from):`element`,n=e.to?Lo(e.to):`element`,r=`measure on ${e.board}:`,i=e.size&&e.relation!==`size`?`, hovered ${Ko(e.size)}`:``;switch(e.relation){case`gap`:return`${r} gap ${e.lines.map(e=>`${Math.round(e.px)}px ${e.side?Uo[e.side]:`from`}`).join(` and `)} ${t} to ${n}${i}`;case`inside`:return`${r} ${t} inside ${n}: ${Go(e.lines)}${i}`;case`overlap`:return`${r} ${t} overlaps ${n}: ${Go(e.lines)}${i}`;case`parent`:return`${r} ${t} in its parent ${n}: ${Go(e.lines)}${i}`;default:return`${r} size of ${t} ${e.size?Ko(e.size):``}`.trimEnd()}}function Jo(e,t,n,r=e=>e){return e.map((e,i)=>e.kind===`measure`?`${i+1} ${qo(e)}${Ro(e.text)}`:e.kind===`box`?`${i+1} ${Vo(e,t,n)}${Ro(e.text)}${zo(e,r)}`:`arrow ${Ho(e.from)} → ${Ho(e.to)}${Ro(e.text)}`)}const Yo=e=>e.messages[0]?.at??e.statusAt;function Xo(e,t,n){let r=e.filter(e=>e.anchor.group===t&&e.anchor.verdict&&e.messages.some(e=>!e.deleted)).sort((e,t)=>Yo(e)<Yo(t)?-1:+(Yo(e)>Yo(t))),i=r.filter(e=>e.anchor.verdict===`reject`&&e.status===`open`).length,a=r.at(-1);if(!a)return{state:`pending`,evidenceUpdated:!1,rejectThreads:i};let o=Yo(a);if(n.has(a.id))return{state:`pending`,at:o,evidenceUpdated:!0,rejectThreads:i};let s=a.messages[0]?.author===`agent`?{by:`agent`}:{};return a.anchor.verdict===`pass`?{state:`pass`,at:o,...s,evidenceUpdated:!1,rejectThreads:i}:a.status===`open`?{state:`reject`,at:o,...s,evidenceUpdated:!1,rejectThreads:i}:{state:`pending`,at:o,evidenceUpdated:!1,rejectThreads:i}}const Zo=(e,t,n=`document`)=>p.default.join(e,n,t,`comment-cursors.json`);function Qo(e){try{let t=JSON.parse(d.default.readFileSync(e,`utf8`));return typeof t!=`object`||!t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`string`))}catch{return{}}}function $o(e,t=`document`){return{get:(n,r)=>Qo(Zo(e,n,t))[r]??null,set:(n,r,i)=>{let a=Zo(e,n,t),o=Qo(a);o[r]!==i&&U(a,{...o,[r]:i})}}}const es=/^data:image\/jpeg;base64,([A-Za-z0-9+/]+={0,2})$/;function ts(e,t,n,r=1){let i=`marks/${t}-${r}.jpg`,a=p.default.join(e,i);try{d.default.mkdirSync(p.default.dirname(a),{recursive:!0});let e=`${a}.${process.pid}.tmp`;return d.default.writeFileSync(e,n),d.default.renameSync(e,a),i}catch{return null}}function ns(e,t,n,r=1){let i=es.exec(n)?.[1];if(!i)return null;let a=Buffer.from(i,`base64`);return a.length>184320||a[0]!==255||a[1]!==216||a[2]!==255?null:ts(e,t,a,r)}function rs(e,t,n){let r=p.default.join(e,`marks`),i;try{i=d.default.readdirSync(r)}catch{return}for(let e of i){if(n){let t=/^(.+)-\d+\.jpg$/.exec(e)?.[1];if(!t||n.has(t))continue}else if(t.has(e))continue;try{d.default.rmSync(p.default.join(r,e),{force:!0})}catch{}}}function is(e){let t=0;for(;t<e.length;){let n=Math.min(t+65536,e.length);crypto.getRandomValues(e.subarray(t,n)),t=n}}function as(e){if(e|=0,e<0)throw RangeError(`Wrong ID size`);let t=Buffer.allocUnsafe(e);return is(t),t}function os(e,t,n){let r=256-256%e.length;if(r===256){let r=e.length-1;return(i=t)=>{if(!i)return``;let a=``;for(;;){let t=n(i),o=i|=0;for(;o--;)if(a+=e[t[o]&r],a.length>=i)return a}}}return(i=t)=>{if(!i)return``;let a=``,o=Math.ceil(409.6*i/r);for(;;){let t=n(o),s=o;for(;s--;)if(t[s]<r&&(a+=e[t[s]%e.length],a.length>=i))return a}}}function ss(e,t=21){if(typeof e!=`string`||!e||e.length>256)return os(e,t,as);for(let n=0;n<e.length;n++)if(e.charCodeAt(n)>255)return os(e,t,as);let n=Uint8Array.from(e,e=>e.charCodeAt(0)),r=e.length,i=(2<<31-Math.clz32(r-1|1))-1,a=``,o=0,s=0;return(e=t)=>{if(e|=0,e<0)throw RangeError(`Wrong ID size`);if(e===0)return``;if(o+e>a.length){let t=Math.max(s,e);s=Math.min(t*16,32768);let c=Buffer.allocUnsafe(t);if(i===r-1){is(c);for(let e=0;e<t;e++)c[e]=n[c[e]&i]}else{let e=Buffer.allocUnsafe(Math.ceil(1.6*(i+1)*t/r)),a=0;for(;a<t;){is(e);for(let o=0;o<e.length;o++){let s=e[o]&i;if(s<r&&(c[a++]=n[s],a===t))break}}}a=c.toString(`latin1`),o=0}return o+=e,a.substring(o-e,o)}}const cs=ss(`57X6y3wQZNzYjJB2L_10pxbackgroundhimselfUTF-8DEMOGRAPHICSVqvt4KW9`),ls=e=>(0,u.createHash)(`sha256`).update(e).digest(`hex`);function us(e,t){try{d.default.mkdirSync(e,{recursive:!0}),d.default.writeFileSync(p.default.join(e,ls(t)),``);let n=d.default.readdirSync(e);if(n.length<=40)return;let r=n.map(t=>({name:t,at:d.default.statSync(p.default.join(e,t)).mtimeMs})).sort((e,t)=>t.at-e.at);for(let{name:t}of r.slice(20))d.default.rmSync(p.default.join(e,t),{force:!0})}catch{return}}const ds=(e,t)=>e!==void 0&&d.default.existsSync(p.default.join(e,ls(t))),fs=(e,t=2e4)=>typeof e==`string`&&e.length<=t,ps=e=>fs(e,100)&&e.length>0;function ms(e){if(typeof e!=`object`||!e)return null;let t=e;switch(t.op){case`create`:{let e=Ha.read(t);return e&&ps(t.blockId)&&fs(t.quote)&&fs(t.text)&&t.text.length>0?{op:`create`,...e,text:t.text}:null}case`reply`:return ps(t.threadId)&&fs(t.text)&&t.text.length>0?{op:`reply`,threadId:t.threadId,text:t.text}:null;case`edit`:return ps(t.threadId)&&ps(t.messageId)&&fs(t.text)&&t.text.length>0?{op:`edit`,threadId:t.threadId,messageId:t.messageId,text:t.text}:null;case`delete`:return ps(t.threadId)&&ps(t.messageId)?{op:`delete`,threadId:t.threadId,messageId:t.messageId}:null;case`resolve`:case`reopen`:return ps(t.threadId)?{op:t.op,threadId:t.threadId}:null;default:return null}}function hs(e){if(typeof e!=`object`||!e)return null;let t=e;switch(t.op){case`add`:{let e=Ha.read(t);return e&&ps(t.blockId)&&(t.quote===void 0||fs(t.quote))&&fs(t.text)&&t.text.length>0?{op:`add`,...e,text:t.text}:null}case`reply`:return ps(t.threadId)&&fs(t.text)&&t.text.length>0?{op:`reply`,threadId:t.threadId,text:t.text}:null;case`resolve`:return ps(t.threadId)?{op:`resolve`,threadId:t.threadId}:null;default:return null}}const gs={human:()=>void 0,agent:()=>void 0},_s=e=>{let t=p.default.dirname(e);try{let n=(0,l.execFileSync)(`git`,[`hash-object`,e],{cwd:t,encoding:`utf8`,timeout:2e3,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return(0,l.execFileSync)(`git`,[`cat-file`,`-e`,n],{cwd:t,timeout:2e3,stdio:`ignore`}),!0}catch{return!1}};function vs(e,t,n=gs,{artifact:r,now:i=()=>(/* @__PURE__ */ new Date()).toISOString(),newId:a=()=>cs(10),savesDir:o}={}){let s=()=>r?n.agent(r):void 0,c=t.empty(),l=null,u=[],f=()=>{o&&us(o,`${JSON.stringify(c,null,2)}\n`),U(e,c),l=d.default.readFileSync(e,`utf8`)},p=()=>{let n;try{n=d.default.readFileSync(e,`utf8`)}catch{return l=null,!1}if(n===l)return!1;let r=l===null;l=n;try{let l=Ua(n),d=r||ds(o,n)||_s(e)?t.saved(l):c,p=t.merge(d,l,`agent`,i(),a,s());c=p.file,u=p.warnings,`${JSON.stringify(c,null,2)}\n`!==n&&f()}catch(e){u=[`comments.json is not valid: ${e.message} (left as written; fix it)`]}return!0};return p(),{current:()=>c,warnings:()=>u,sync:p,apply:e=>(p(),c=t.human(c,e,i(),a,n.human()),f(),c),update:e=>{p(),c=e(c),f()},applyAgent:(e,n)=>{p();let r=t.agent(c,e,i(),a,n??s());return c=r.file,f(),r}}}const ys=/* @__PURE__ */ new Map,bs=/* @__PURE__ */ new Map;function xs(e,t){t.size?ys.set(e,new Set(t)):ys.delete(e)}const Ss=e=>ys.get(e)??/* @__PURE__ */ new Set;function Cs(e,t){return bs.set(e,t),()=>{bs.get(e)===t&&bs.delete(e)}}const ws=e=>bs.get(e)??null;function Ts(e){let t=Ss(e);return e=>t.has(e)}function Es(e,t){return Ss(e).has(t)}function Ds(e){try{let t=JSON.parse(d.default.readFileSync(p.default.join(e,`canvas.json`),`utf8`));return!Array.isArray(t.pages)||typeof t.boards!=`object`||!t.boards?{canvas:null,rounds:[]}:{canvas:t,rounds:ea(t,Se(t))}}catch{return{canvas:null,rounds:[]}}}function Os(e,t){return e.closed?`closed`:Fo(t,e.id).submitted?`submitted`:`open`}function ks(e,t){return e.rounds.map(n=>{let r=Fo(t,n.id);return{id:n.id,page:n.page,...n.title?{title:n.title}:{},state:Os(n,t),...r.submitted&&r.at?{submitted:r.at}:{},groups:n.groups,boards:n.groups.flatMap(t=>e.canvas?.groups?.[t]?.boards??[])}})}const As=(e,t)=>{let n=/* @__PURE__ */ new Set([...t.board?[t.board]:[],...(t.nodes??[]).map(e=>e.board)]);return Object.entries(e.canvas?.groups??{}).filter(([e,r])=>e===t.group||r.boards.some(e=>n.has(e))).map(([e])=>e)};function js(e,t){return e.rounds.flatMap(n=>n.groups.map(r=>{let i=e.canvas.groups[r],a=t.filter(t=>!go(t)&&t.messages.some(e=>!e.deleted)&&As(e,t.anchor).includes(r));return{id:r,kind:`choose`,page:n.page,round:n.id,...i.title?{title:i.title}:{},...i.recommend?{recommend:i.recommend}:{},...Po(t,r,i.recommend),threads:a.length,boards:i.boards}}))}function Ms(e,t,n){let r=e.canvas?.groups?.[t];if(!r?.choose)throw Error(`${t} is not a choice group`);if(n!==null&&!r.boards.includes(n))throw Error(`${n} is not a board of ${t}`);let i=ta(e.rounds,t);if(!i)throw Error(`${t} is not on the canvas`);return i}function Ns(e,t){let n=e.rounds.find(e=>e.id===t);if(!n)throw Error(`no round ${t} with choice groups`);return n}function Ps(e,t,n){if(t.choice!==void 0){let r=Ms(e,t.group,t.choice),i=Os(r,n);if(i!==`open`)throw Error(`round ${r.id} is ${i}`)}if(t.submit!==void 0){let n=Ns(e,t.round);if(n.closed)throw Error(`round ${n.id} is closed`)}}function Fs(e,t,n){let r=Ms(e,t,n);if(r.closed)throw Error(`round ${r.id} is closed`);return{page:r.page,x:0,y:0,group:t,choice:n}}function Is(e,t,n){let r=Ns(e,t);if(r.closed)throw Error(`round ${r.id} is closed`);return{page:r.page,x:0,y:0,round:t,submit:n}}const Ls={empty:To,saved:Eo,merge:Do,human:(e,t,n,r,i)=>Ao(e,t,n,r,i),agent:jo},Rs=e=>{if(e.kind!==`box`||e.crop===void 0)return e;let{crop:t,...n}=e;return n},zs=e=>e.marks?{...e,marks:e.marks.map(Rs)}:e,Bs=({hashes:e,...t})=>zs(t),Vs=/^data:image\/jpeg;base64,([A-Za-z0-9+/]+={0,2})$/,Hs=/^\d{1,2}$/;function Us(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=Object.entries(e).filter(e=>Hs.test(e[0])&&typeof e[1]==`string`);return t.length?Object.fromEntries(t):void 0}function Ws(e,t){let n=[],r=0;for(let i of Object.keys(t).sort((e,t)=>Number(e)-Number(t))){let a=Number(i),o=e.marks?.[a];if(o?.kind!==`box`||!o.board)continue;let s=Vs.exec(t[i])?.[1];if(!s)continue;let c=Buffer.from(s,`base64`);c[0]===255&&c[1]===216&&c[2]===255&&(r+c.length>184320||(r+=c.length,n.push({bytes:c,index:a})))}return n}const Gs=({hashes:e,group:t,verdict:n,choice:r,round:i,submit:a,...o})=>o;function Ks(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.op!==`create`){let t=ms(e);return t&&t.op!==`create`?t:null}let n=So(t.anchor);if(!n||!fs(t.text)||t.text.length===0)return null;let r=Us(t.crops);return{op:`create`,anchor:Bs(n),text:t.text,...r?{crops:r}:{}}}function qs(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.op===`add`){let e=So(t.anchor);return e&&fs(t.text)&&t.text.length>0?{op:`add`,anchor:zs(Gs(e)),text:t.text}:null}return t.op===`reply`?ps(t.threadId)&&fs(t.text)&&t.text.length>0?{op:`reply`,threadId:t.threadId,text:t.text}:null:t.op===`resolve`&&ps(t.threadId)?{op:`resolve`,threadId:t.threadId}:null}function Js(e){try{return JSON.parse(d.default.readFileSync(p.default.join(e,`canvas.json`),`utf8`))}catch{return{}}}function Ys(e){return Object.fromEntries(Object.entries(Js(e).boards??{}).flatMap(([e,t])=>{let n=Oe(t??{})?t.src:t?.file;return typeof n==`string`?[[e,{file:n,page:typeof t.page==`string`?t.page:``,x:typeof t.x==`number`?t.x:0,y:typeof t.y==`number`?t.y:0,w:typeof t.w==`number`?t.w:0,h:typeof t.h==`number`?t.h:0}]]:[]}))}function Xs(e){return Object.fromEntries(Object.entries(Js(e).groups??{}).flatMap(([e,t])=>Array.isArray(t?.boards)?[[e,{...typeof t.title==`string`?{title:t.title}:{},...typeof t.from==`string`?{from:t.from}:{},...typeof t.capturedAt==`string`?{capturedAt:t.capturedAt}:{},boards:t.boards.filter(e=>typeof e==`string`),verify:t.verify===!0}]]:[]))}const Zs=e=>Object.fromEntries(Object.entries(Ys(e)).map(([e,t])=>[e,t.file]));function Qs(e,t){if(typeof e!=`object`||!e)return null;let n=e;if(n.op!==`add`||typeof n.board!=`string`||n.anchor!==void 0)return null;let r=t[n.board];return r?qs({op:`add`,anchor:{page:r.page,board:n.board,x:n.x??r.w,y:n.y??0},text:n.text}):{error:`no board ${n.board}`}}const $s=/* @__PURE__ */ new Map;function ec(e,t){let n=it(e,t);if(!n)return null;try{let e=d.default.statSync(n),t=`${e.size}:${e.mtimeMs}`,r=$s.get(n);if(r?.stamp===t)return r.hash;let i=u.default.createHash(`sha1`).update(d.default.readFileSync(n)).digest(`hex`).slice(0,12);return $s.set(n,{stamp:t,hash:i}),i}catch{return null}}function tc(e){return Object.fromEntries(Object.entries(Zs(e)).flatMap(([t,n])=>{let r=ec(e,n);return r?[[t,r]]:[]}))}const nc=(e,t={})=>[.../* @__PURE__ */ new Set([...e.board?[e.board]:[],...(e.nodes??[]).map(e=>e.board),...Ji(Co(e)),...e.group?t[e.group]?.boards??[]:[]])];function rc(e,t,n={}){let r=nc(e,n);return r.length?{...Bs(e),hashes:Object.fromEntries(r.map(e=>[e,t[e]??`missing`]))}:Bs(e)}const ic=(e,t)=>{let n=e.anchor.group;return!n||Object.keys(e.anchor.hashes??{}).sort().join(`
88
- `)===[...t[n]?.boards??[]].sort().join(`
89
- `)},ac=(e,t,n)=>!go(e)&&(!ic(e,n)||Object.entries(e.anchor.hashes??{}).some(([e,n])=>t[e]!==n));function oc(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=t=>Es(e.stateDir,`artboard/${t}`),o=$o(e.stateDir,`artboard`),s=t=>p.default.join(e.root,`artboard`,t),c=n=>{let r=t.get(n);return r||(r=vs(p.default.join(s(n),`comments.json`),Ls,e.names,{artifact:`artboard/${n}`,savesDir:p.default.join(e.stateDir,`artboard`,n,`comment-saves`)}),t.set(n,r)),r},l=t=>{let r=n.get(t);return r||(r=tc(s(t)),e.evidenceHash&&(r=Object.fromEntries(Object.entries(r).map(([n,r])=>[n,e.evidenceHash(t,n,r)]))),n.set(t,r)),r},u=e=>{let t=l(e),n=Xs(s(e));return c(e).current().threads.filter(e=>ac(e,t,n)).map(e=>e.id)},f=(t,n=a(t))=>{let o=u(t);r.set(t,JSON.stringify(o)),i.set(t,n),e.broadcast({type:`board-comments`,artifact:`artboard/${t}`,comments:c(t).current(),stale:o,listening:n})},m=e=>(n.delete(e),l(e)),h=t=>p.default.join(e.stateDir,`artboard`,t,`rounds.json`),g=e=>{let t=Ds(s(e));if(!t.canvas)return;let n=ks(t,c(e).current().threads);(n.length!==0||d.default.existsSync(h(e)))&&U(h(e),{rounds:n})},_=(e,t,n)=>{let r=/* @__PURE__ */ new Map;for(let{bytes:i,index:a}of n){let n=ts(s(e),t,i,a+1);n&&r.set(a,n)}r.size!==0&&c(e).update(e=>({...e,threads:e.threads.map(e=>e.id===t&&e.anchor.marks?{...e,anchor:{...e.anchor,marks:e.anchor.marks.map((e,t)=>e.kind===`box`&&r.has(t)?{...e,crop:r.get(t)}:e)}}:e)}))},v=e=>{if(c(e).warnings().length)return;let t=new Set(c(e).current().threads.filter(e=>e.messages.some(e=>!e.deleted)).map(e=>e.id));rs(s(e),/* @__PURE__ */ new Set,t)},y=p.default.basename(e.root)===`artifacts`&&p.default.basename(p.default.dirname(e.root))===`.ryugi`?p.default.dirname(p.default.dirname(e.root)):null,b=e=>t=>{let n=p.default.join(s(e),t);return y?p.default.relative(y,n):n},x=(e,t)=>{let n=Ys(s(e)),r=Object.fromEntries(Object.entries(n).map(([e,t])=>[e,t.file])),i=Xs(s(e));return a=>({...a,stale:t.has(a.id),waitingOn:ro(a),...Co(a.anchor).length?{marked:Jo(Co(a.anchor),n,a.anchor.page,b(e))}:{},files:Object.fromEntries(nc(a.anchor,i).flatMap(e=>r[e]?[[e,r[e]]]:[])),messages:a.messages.map(({avatar:e,...t})=>t)})};return{comments:e=>c(e).current(),mergeRemote:(e,t)=>{let n=[];return c(e).update(e=>{let r=ho(e,t,So);return n=r.applied,r.file}),f(e),n},listening:a,refreshListening:(n=Ts(e.stateDir))=>{for(let e of t.keys()){let t=n(`artboard/${e}`);t!==i.get(e)&&f(e,t)}},stale:u,warnings:e=>c(e).warnings(),shiftPins:(e,t)=>{let n=(e,t,n)=>t>=e.x&&t<=e.x+e.w&&n>=e.y&&n<=e.y+e.h;c(e).update(e=>({...e,threads:e.threads.map(e=>{let{anchor:r}=e,i=(e,i)=>t.find(t=>t.page===r.page&&n(t.rect,e,i)&&!t.except.some(t=>n(t,e,i))),a=r.board||r.group||r.round||r.nodes?.length?void 0:i(r.x,r.y),o=r.marks&&Yi(r.marks,i),s=o?.some((e,t)=>e!==r.marks[t]);return!a&&!s?e:{...e,anchor:{...r,...a?{x:r.x+a.dx,y:r.y+a.dy}:{},...s?{marks:o}:{}}}})})),f(e)},apply:(e,t)=>{let n=Xs(s(e));if(t.op===`create`&&t.anchor.verdict&&!n[t.anchor.group]?.verify)throw Error(`no verify group ${t.anchor.group} in artboard/${e}`);let r=t.op===`create`?null:c(e).current().threads.find(e=>e.id===t.threadId);if(r&&go(r))throw Error(`a choice record changes only through the radios and the submit bar`);let i=t.op===`create`&&go(t);i&&Ps(Ds(s(e)),t.anchor,c(e).current().threads);let{crops:o,...l}=t.op===`create`?t:{...t,crops:void 0},d=l.op===`create`&&!i?{...l,anchor:rc(l.anchor,m(e),n)}:l,p=new Set(c(e).current().threads.map(e=>e.id));if(c(e).apply(d),d.op===`delete`&&v(e),d.op===`create`&&o){let t=c(e).current().threads.find(e=>!p.has(e.id));t&&_(e,t.id,Ws(d.anchor,o))}return f(e),g(e),{comments:c(e).current(),stale:u(e),listening:a(e)}},applyAgent:(e,t,n)=>{let r=t.op===`add`?{...t,anchor:rc(t.anchor,m(e))}:t,{threadId:i,messageId:a}=c(e).applyAgent(r,n);return f(e),{threadId:i,...a?{messageId:a}:{}}},agentChoose:(e,t,n,r)=>{let i=Fs(Ds(s(e)),t,n),a=n?`Chose ${n}`:`Cleared the choice in ${t}`,{threadId:o}=c(e).applyAgent({op:`add`,anchor:i,text:a},r);return f(e),g(e),{threadId:o}},agentSubmit:(e,t,n,r)=>{let i=Is(Ds(s(e)),t,n),a=n?`Submitted ${t}`:`Withdrew ${t}`,{threadId:o}=c(e).applyAgent({op:`add`,anchor:i,text:a},r);return f(e),g(e),{threadId:o}},agentVerdict:(e,t,n)=>{let r=Xs(s(e)),i=Ys(s(e)),a=c(e).current().threads,o=new Set(u(e)),l=t.group===null?Object.keys(r).filter(e=>r[e].verify&&Xo(a,e,o).state!==`pass`):[t.group],d=l.map(n=>{if(!r[n]?.verify)throw Error(`no verify group ${n} in artboard/${e}`);let a=r[n].boards.flatMap(e=>i[e]??[]);if(!a.length)throw Error(`verify group ${n} has no boards`);return{page:a[0].page,x:Math.max(...a.map(e=>e.x+e.w)),y:Math.min(...a.map(e=>e.y)),group:n,verdict:t.verdict}}),p=m(e),h=d.map(i=>c(e).applyAgent({op:`add`,anchor:rc(i,p,r),text:t.text},n).threadId);return h.length&&f(e),{groups:l,threadIds:h}},rounds:e=>ks(Ds(s(e)),c(e).current().threads).map(({boards:e,...t})=>t),list:(e,t,n)=>{let r=c(e).sync();v(e),r&&f(e);let i=c(e).current(),a=x(e,new Set(u(e))),s=e=>!go(e);if(n)return i.threads.filter(e=>s(e)&&!e.messages.every(e=>e.deleted)).map(a);let{threads:l,newest:d}=co(i,o.get(e,t));return d&&o.set(e,t,d),l.filter(s).map(a)},groups:e=>{let t=Ys(s(e)),n=c(e).current().threads,r=new Set(u(e));return[...Object.entries(Xs(s(e))).filter(([,e])=>e.verify).map(([e,i])=>{let{state:a,...o}=Xo(n,e,r);return{id:e,kind:`verify`,page:i.boards.map(e=>t[e]?.page).find(Boolean)??``,...i.title?{title:i.title}:{},verdict:a,...i.from?{from:i.from}:{},...i.capturedAt?{capturedAt:i.capturedAt}:{},...o,boards:i.boards}}),...js(Ds(s(e)),n)]},sync:e=>{let t=c(e).sync();v(e),t&&f(e),g(e)},boardsChanged:e=>{m(e),g(e),(t.has(e)||d.default.existsSync(p.default.join(s(e),`comments.json`)))&&JSON.stringify(u(e))!==(r.get(e)??`[]`)&&f(e)}}}function sc(e){return u.default.createHash(`sha1`).update(e+`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest(`base64`)}function cc(e,t){let n=t.length,r;return n<126?r=Buffer.from([128|e,n]):n<65536?(r=Buffer.alloc(4),r[0]=128|e,r[1]=126,r.writeUInt16BE(n,2)):(r=Buffer.alloc(10),r[0]=128|e,r[1]=127,r.writeBigUInt64BE(BigInt(n),2)),Buffer.concat([r,t])}const lc=e=>cc(1,Buffer.from(e));function uc(e,t){e.write(`HTTP/1.1 101 Switching Protocols\r
90
- Upgrade: websocket\r
91
- Connection: Upgrade\r
92
- Sec-WebSocket-Accept: ${sc(t)}\r\n\r\n`)}function dc(e,t,n){e.end(`HTTP/1.1 ${t} ${n}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)}function fc(e,t){let n=Buffer.alloc(0);e.on(`data`,r=>{for(n=Buffer.concat([n,r]);n.length>=2;){let r=!!(n[0]&128),i=n[0]&15,a=n[1]&127,o=2;if(a===126){if(n.length<4)return;a=n.readUInt16BE(2),o=4}else if(a===127){if(n.length<10)return;let t=n.readBigUInt64BE(2);if(t>BigInt(8388608)){e.destroy();return}a=Number(t),o=10}let s=o+4+a;if(n.length<s)return;let c=n.subarray(o,o+4),l=Buffer.from(n.subarray(o+4,s));for(let e=0;e<l.length;e++)l[e]=l[e]^c[e%4];if(n=n.subarray(s),i===8){e.end(cc(8,Buffer.alloc(0)));return}if(i===9)e.write(cc(10,l));else if(i===1&&r)try{t?.(l.toString(`utf8`))}catch(e){console.error(JSON.stringify({type:`client-message-error`,error:e.message}))}}})}function pc(e,t,{artifact:n,request:r,...i}){if(typeof r!=`number`||typeof n!=`string`)return;let a=G(n),o=a?.type===`artboard`&&n===`artboard/${a.id}`?da(i):null,s=a&&o?e.arranges.apply(a.id,o):{ok:!1,reason:`unknown`};t.write(lc(JSON.stringify({type:`arrange-result`,artifact:n,request:r,...s})))}async function mc(e,t,n){if(!e.cloud||!n)return 0;let r=`${t.type}/${t.id}`,i=await e.cloud.inbox(r);if(i.length===0)return 0;let a=n(e,t.id,i);return await e.cloud.delivered(r,a),a.length}async function hc(e,t){if(!t)return null;try{let n=await fetch(`${e}/api/inbox`,{headers:{...Er,Authorization:`Bearer ${t}`}});if(!n.ok)return null;let r=(await n.json()).ids;return Array.isArray(r)?new Set(r.filter(e=>typeof e==`string`)):null}catch{return null}}const gc=/* @__PURE__ */ new WeakMap;async function _c(e,t,n){let r=`${t.type}/${t.id}`,i=gc.get(e)??/* @__PURE__ */ new Map;gc.set(e,i);let a=Date.now();a-(i.get(r)??-1/0)<3e4||(i.set(r,a),await mc(e,t,n).catch(()=>0))}async function vc(e,t){let n=[],r=0;for await(let i of e){if(r+=i.length,r>t)return null;n.push(i)}return Buffer.concat(n)}const yc=async(e,t=262144)=>{let n=[],r=0;for await(let i of e)r+=i.length,r<=t&&n.push(i);if(r>t)return null;try{return JSON.parse(Buffer.concat(n).toString(`utf8`))}catch{return null}},bc=e=>typeof e.agent==`string`&&e.agent.length>0&&e.agent.length<=100?e.agent:void 0,xc=/^\/api\/agent\/artboard\/([^/]+)\/comments$/,Sc=/^\/api\/artboard\/([^/]+)\/comments$/,Cc=(e,t,n)=>e.boardComments.mergeRemote(t,n);function wc(e){let t=e.verdict;if(t!==`pass`&&t!==`reject`)throw Error(`verdict needs {verdict: "pass" | "reject"}`);if(e.all!==!0&&!ps(e.group))throw Error(`verdict needs {group} or {all: true}`);let n=typeof e.text==`string`?e.text.trim():``;if(t===`reject`&&!n)throw Error(`a reject needs a reason: pass {text}`);return{group:e.all===!0?null:e.group,verdict:t,text:n||`Pass`}}async function Tc(e,t,n,r){let{root:i,boardComments:a}=n,o=W(i,`artboard`,r);if(!o){B(t,404,{error:`artboard/${r} not found`});return}let s=await yc(e),c=typeof s==`object`&&s?s:{},l=bc(c);if(c.op===`list`){await _c(n,{type:`artboard`,id:r},Cc);let e=a.list(r,l??`Agent`,c.all===!0);B(t,200,{type:`comments`,artifact:`artboard/${r}`,threads:e,groups:a.groups(r),rounds:a.rounds(r)});return}if(c.op===`choose`||c.op===`submit`){try{if(c.op===`choose`){if(!ps(c.group)||c.board!==null&&!ps(c.board))throw Error(`choose needs {group, board} with board a board id or null`);B(t,200,a.agentChoose(r,c.group,c.board,l))}else{if(!ps(c.round)||typeof c.submit!=`boolean`)throw Error(`submit needs {round, submit: true | false}`);B(t,200,a.agentSubmit(r,c.round,c.submit,l))}}catch(e){B(t,400,{error:e.message})}return}if(c.op===`verdict`){try{B(t,200,a.agentVerdict(r,wc(c),l))}catch(e){B(t,400,{error:e.message})}return}let u=Qs(s,Ys(o));if(u&&`error`in u){B(t,400,{error:`${u.error} in artboard/${r}`});return}let d=u??qs(s);if(!d)B(t,400,{error:`not an agent comment op: use list, add {anchor: {page, board, x, y}, text}, reply {threadId, text} or resolve {threadId}; text must not be empty`});else if(d.op===`add`&&d.anchor.board&&!(d.anchor.board in Zs(o)))B(t,400,{error:`no board ${d.anchor.board} in artboard/${r}`});else try{B(t,200,a.applyAgent(r,d,l))}catch(e){B(t,400,{error:e.message})}}const Ec={path:xc,methods:[`POST`],auth:`agent`,handle:(e,t,n,{match:r})=>Tc(e,t,n,r[1])};async function Dc(e,t,n,r){if(!W(n.root,`artboard`,r)){B(t,404,{error:`artboard/${r} not found`});return}let i=Ks(await yc(e));if(!i)B(t,400,{error:`not a comment op`});else if(n.verdictPreparing(r,i))B(t,409,{error:`The recording evidence is still being prepared`});else try{B(t,200,n.boardComments.apply(r,i))}catch(e){B(t,400,{error:e.message})}}const Oc={path:Sc,methods:[`POST`],auth:`same-origin`,handle:(e,t,n,{match:r})=>Dc(e,t,n,r[1])},kc={threads:async(e,t,n)=>{await _c(e,{type:`artboard`,id:t},Cc);let r=new Map(e.boardComments.list(t,n,!0).map(e=>[e.id,e]));return e.boardComments.comments(t).threads.filter(e=>!go(e)).map(e=>({...e,...r.get(e.id),messages:e.messages.map(({avatar:e,...t})=>t)}))},sections:{groups:(e,t)=>{let n=e.boardComments.groups(t).map(e=>({...e})),r=new Set(e.boardComments.rounds(t).filter(e=>e.state===`submitted`).map(e=>e.id));return{items:n,actionable:e=>e.kind===`verify`?e.verdict===`reject`:r.has(e.round)}},rounds:(e,t)=>({items:e.boardComments.rounds(t).map(e=>({...e})),actionable:e=>e.state===`open`||e.state===`submitted`})}},Ac=e=>Array.isArray(e)?e:[],jc=e=>e===`comments.json`||e.startsWith(`marks/`),Mc=e=>e.length===0||e.some(e=>!jc(e)),Nc={read:ht,readLive:(e,t,n,{recordings:r,runtimeSession:i})=>({...r.project(t,e,n),runtimeVersion:`${i}:${nr(e,`artboard`)}`}),runtimeWarnings:(e,t)=>e.artboardRefWarnings(t),threads:(e,t)=>e.boardComments.comments(t).threads,meta:(e,t)=>({comments:e.boardComments.comments(t),staleThreads:e.boardComments.stale(t),listening:e.boardComments.listening(t)}),backlinksAs:`artboard`,localMeta:(e,t)=>e.boardPort?{boardPort:e.boardPort,boardPath:`/c${xi(e.root,`artboard`,t)}/`}:{},state:(e,t,n,r)=>({extra:{...`canvas`in r?{...e.artboardRuntime.state(t,n,r),...`recordings`in r?{recordings:r.recordings}:{}}:{},...e.artboardHints(t)},files:{"layout.json":(`layout`in r?r.layout:void 0)??{pages:{}}}}),onChangedOrGone:(e,t,n)=>{Mc(n)&&e.documents.artboardChanged(t)},onFilesChanged:(e,t,n,r)=>{(r.includes(`canvas.json`)||r.length===0)&&e.arranges.guard(t),r.includes(`comments.json`)&&e.boardComments.sync(t),Mc(r)&&e.boardComments.boardsChanged(t)},acceptReport:(e,t,n,{type:r,board:i,version:a,message:o})=>{let s={type:`artboard`,id:t},c=e.readArtifact(n,s);`canvas`in c&&e.artboardRuntime.accept(t,n,c,{type:r,board:i,version:a,message:o})&&e.writeState(s,n)},check:{settle:async e=>{await e.documents.opening()},evidence:(e,t,{payload:n,state:r})=>({required:`canvas`in n&&Object.values(n.canvas?.boards??{}).some(e=>!Oe(e)),observed:r.ran}),answer:(e,t,{payload:n,state:r})=>({pending:[...Ac(r.pending),...Ac(r.browserPending)],...`canvas`in n&&n.canvas?{provenance:[...Be(n.canvas),...bi(n.canvas),...e.arranges.notices(t)]}:{}})},socketMessages:{"canvas-arrange":pc},mergeRemote:Cc,pull:{publishedRecordings:!0},standIn:(e,t,n)=>e.recordings.resolve(t,n),relayOps:{arrange:(e,t,n)=>{let r=da(n.arrange);return r?e.arranges.apply(t,r):{ok:!1,reason:`unknown`}},comment:(e,t,n)=>{let r=Xi(n,Ks);if(e.verdictPreparing(t,r))throw Error(`The recording evidence is still being prepared`);return e.boardComments.apply(t,r)}},publishExtras:(e,t)=>({comments:e.boardComments.comments(t)}),publish:(e,t,n,r,{comments:i})=>{let{canvas:a,layout:o,versions:s}=r,c=Zi(i);return{canvas:a,layout:o,versions:s,...c.threads.length?{comments:c}:{}}},cloudPage:e=>e.endsWith(`.html`)?{inspector:!0}:null,opensOnRegister:!0,review:kc,routes:[Ec,Oc],resolveFile:it,pageRuntime:()=>({inspector:!0}),isPage:e=>e.endsWith(`.html`),keepsLocal:jc},Pc=`sandbox allow-scripts allow-modals allow-forms allow-popups allow-downloads`,Fc=`sandbox; default-src 'none'`,Ic=`worker-src 'none'`;function Lc(e,t,n){return e===`html`||e===`slides`?Pc:e===`report`?t===`index.html`?`sandbox allow-scripts allow-modals; default-src 'none'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'`:Fc:e===`storyboard`?t.endsWith(`.html`)?`sandbox allow-scripts; default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self' data:; connect-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'`:Fc:e===`document`?t.endsWith(`.html`)?Pc:Fc:n?Ic:`sandbox allow-scripts`}const Rc=/^\/c\/artboard\/([^/]+)\/(.+)$/,zc=/^\/c\/(runtime|symbols)\/(.+)$/,Bc=e=>[.../* @__PURE__ */ new Set([`localhost`,`127.0.0.1`,e.includes(`:`)?`[${e}]`:e])],Vc=(e,t)=>Bc(e).map(e=>`http://${e}:${t}`);function Hc(e,t,n){let r=[...Vc(e,t),...n?[n]:[]];return`${Ic}; frame-ancestors ${r.join(` `)}`}function Uc(e,t){if(e.method!==`GET`&&e.method!==`HEAD`)return{kind:`none`};if(t===`/robots.txt`)return{kind:`robots`};let n=zc.exec(t);if(n)return{kind:`runtime`,rest:`${n[1]}/${n[2]}`};let r=Rc.exec(t);return r&&Yn(r[1])?{kind:`board`,address:r[1],rest:r[2]}:{kind:`none`}}function Wc(e,t,n,r,{type:i,file:a,message:o}){t.accepts(a)&&(i===`loaded`?t.loaded(n.id,r,a)&&e.writeState(n,r):i===`runtime-error`&&typeof o==`string`&&(o.length===0||o.length>2048||t.report(n.id,r,a,o)&&(e.writeState(n,r),e.broadcast({type:`change`,artifact:`${n.type}/${n.id}`,files:[]}))))}const Gc={settle:async(e,t,n)=>{let r=await e.documents.open(t),i=await d.default.promises.readFile(p.default.join(n,`doc.xml`),`utf8`).catch(()=>null);if(!r||i===null)return!1;r.onFileText(i);let a=new Promise(e=>setTimeout(()=>e(`timeout`),6e4).unref());return await Promise.race([r.settled(),a])===`timeout`}},Kc=/<(\/?)([a-zA-Z][\w-]*)\b([^>]*?)(\/?)>/g,qc=/\bid="([^"]+)"/,Jc=e=>e.replaceAll(/<[^>]+>/g,``).replaceAll(`&lt;`,`<`).replaceAll(`&gt;`,`>`).replaceAll(`&quot;`,`"`).replaceAll(`&apos;`,`'`).replaceAll(`&amp;`,`&`).replaceAll(/\s+/g,` `).trim();function Yc(e,t){let n=Jc(t);if(/^h[1-6]$/.test(e))return n;let r=Array.from(n);return r.length>30?`${r.slice(0,30).join(``)}…`:n}function Xc(e){let t=e.replaceAll(/<!\[CDATA\[[\s\S]*?\]\]>/g,``).replaceAll(/<ask\b[^>]*\/>|<ask\b[\s\S]*?<\/ask>/g,``),n={},r=0,i=null;for(let e of t.matchAll(Kc)){let[a,o,s,c,l]=e;if(o){--r,r===1&&i&&(n[i.id]=Yc(i.tag,t.slice(i.start,e.index)),i=null);continue}let u=r===1?qc.exec(c)?.[1]:void 0;l?u&&(n[u]=``):(u&&(i={id:u,start:e.index+a.length,tag:s}),r+=1)}return n}const Zc=/<h[1-6]\b[^>]*>([\s\S]*?)<\/h[1-6]>/i;function Qc(e,t){let n;try{n=d.default.readFileSync(p.default.join(e,H.document),`utf8`)}catch{return{title:t,blocks:{},warnings:[`doc.xml not found`],version:ir(e)}}return{title:Zc.exec(n)?.[1]?.replaceAll(/<[^>]+>/g,``).trim()||t,blocks:Xc(n),warnings:[],version:ir(e)}}const $c=[`claude`,`codex`],el=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:null,tl=e=>typeof e==`string`&&e.length>0&&e.length<=200,nl=e=>$c.includes(e);function rl(e){let t=el(e);if(!t||!tl(t.deviceId))return null;let n=t.deviceId;switch(t.op){case`tasks.create`:{let{project:e,text:r,harness:i}=t;if(!tl(e)||!nl(i)||typeof r!=`string`||!r.trim()||r.length>8e3)return null;let a=typeof t.content==`string`&&t.content.trim()&&t.content.length<=32e3?t.content:void 0;return{op:`tasks.create`,deviceId:n,project:e,text:r,harness:i,...a?{content:a}:{}}}case`sessions.list`:return{op:`sessions.list`,deviceId:n};case`sessions.screen`:return tl(t.sessionId)?{op:`sessions.screen`,deviceId:n,sessionId:t.sessionId}:null;default:return null}}const il=`prompt.json`;function al(e,t){d.default.writeFileSync(p.default.join(e,il),`${JSON.stringify(t,null,2)}\n`)}function ol(e){try{let t=JSON.parse(d.default.readFileSync(p.default.join(e,il),`utf8`));return typeof t.xml!=`string`||typeof t.markdown!=`string`||typeof t.at!=`number`||!nl(t.harness)?null:{xml:t.xml,markdown:t.markdown,at:t.at,harness:t.harness}}catch{return null}}function sl({maxEntries:e=512,maxBytes:t=8388608}={}){let n=[],r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=()=>{let e=n.at(-1);if(!e)throw Error(`no document engine is running`);return e},o=n=>{let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=0,l=e=>{a.delete(e)&&(c-=e.length)},u=(n,r)=>{for(l(n),a.set(n,r),c+=n.length;a.size>1&&(a.size>e||c>t);)l(a.keys().next().value)},d=e=>{let t=[...new Set(e)].filter(e=>!a.has(e)&&!s.has(e));if(t.length){let e=Promise.resolve().then(()=>n(t)).then(e=>{let n=/* @__PURE__ */ new Set;t.forEach((t,r)=>{u(t,e[r]);for(let e of o.get(t)??[])n.add(e);o.delete(t)}),n.size&&r.forEach(e=>e([...n]))}).finally(()=>{t.forEach(e=>s.delete(e)),i.delete(e)});i.add(e);for(let n of t)s.set(n,e)}return Promise.all(e.map(e=>s.get(e))).then(()=>void 0)};return{ensure:d,get:(e,t)=>{if(a.has(e)){let t=a.get(e);return u(e,t),t}if(t){let n=o.get(e);n||o.set(e,n=/* @__PURE__ */ new Set),n.add(t)}d([e]).catch(()=>void 0)}}},s=o(e=>a().trees(e)),c=o(e=>a().checkCharts(e));return{use:e=>(n.push(e),()=>{let t=n.lastIndexOf(e);t!==-1&&n.splice(t,1)}),tree:s.get,ensure:s.ensure,chart:c.get,ensureCharts:c.ensure,idle:()=>Promise.all([...i].map(e=>e.catch(()=>void 0))).then(()=>void 0),onReady:e=>(r.add(e),()=>r.delete(e)),taskPrompt:e=>a().taskPrompt(e),open:e=>a().open(e),read:(e,t)=>a().read(e,t)}}const cl=sl(),ll=e=>d.default.readFileSync(p.default.join(e,`doc.xml`),`utf8`),ul=/* @__PURE__ */ new Map;function dl(e){let t=cl.tree(e);if(!t)throw Error(`the document engine has not read this document yet`);if(`error`in t)throw Error(t.error);return t.state}async function fl(e){let t=ol(e),n=ll(e);await cl.ensure([n,...t?[t.xml]:[]]),ul.set(e,n)}function pl(e){let t=ll(e);return cl.tree(t)?t:ul.get(e)??t}function ml(e,t,n,r,{comments:i}){let a=ol(e);return{title:n,state:dl(pl(e)),comments:Zi(i),...a?{prompt:{state:dl(a.xml),markdown:a.markdown,at:a.at,harness:a.harness}}:{}}}async function hl(e,t){let n=await e.documents.open(t);if(!n)throw Error(`document/${t} has no doc.xml`);return n}const gl={state:async(e,t)=>e.documentState(t,await hl(e,t)),update:async(e,t,n)=>{let r=await hl(e,t),i=typeof n.bytes==`string`?Buffer.from(n.bytes,`base64`):null;if(!i)throw Error(`update needs bytes`);if(i.length>8388608)throw Error(`update too large`);let a=Array.isArray(n.features)?n.features.filter(e=>typeof e==`string`):[];return await r.importUpdate(new Uint8Array(i),a),null},comment:async(e,t,n)=>({comments:await e.documents.applyCommentOp(t,Xi(n,ms))})},_l={threads:[`id`,`status`,`waitingOn`,`anchor`,`stale`,`changes`,`messages`,`preview`,`messageCount`,`omittedMessages`],asks:[`id`,`state`,`choice`,`text`,`byRecommendation`,`staleChoice`,`note`],groups:[`id`,`kind`,`verdict`,`choice`,`by`,`byRecommendation`,`round`,`threads`,`evidenceUpdated`,`rejectThreads`,`title`,`from`,`capturedAt`],rounds:[`id`,`state`,`title`,`groups`,`submitted`]},vl={threads:[`id`,`status`,`waitingOn`],asks:[`id`,`state`],groups:[`id`,`kind`,`verdict`,`choice`],rounds:[`id`,`state`]},yl=e=>e.startsWith(`document/`)?[`threads`,`asks`]:[`threads`,`groups`,`rounds`];function bl(e,t){return e.section?`Choose section or sections, not both.`:!e.sections.length||new Set(e.sections).size!==e.sections.length||e.sections.some(e=>!yl(t).includes(e))?`Choose distinct review sections supported by this artifact.`:e.fields||e.cursor||e.snapshot||e.thread||e.filters&&Object.values(e.filters).some(e=>e!==void 0)?`Fields, filters, thread, cursor and snapshot require a single --section. Follow each collection continuation separately.`:null}function xl(e){let{section:t,filters:n}=e;if(!t&&(e.detail||e.cursor||e.fields||n&&Object.values(n).some(Boolean)))return`Choose a section before requesting detail, fields, filters or a cursor.`;if(t&&!(t in _l))return`Unknown review section.`;if(n&&Object.keys(n).some(e=>![`status`,`waitingOn`,`kind`,`choiceState`].includes(e)))return`Unknown review filter.`;if(n?.waitingOn&&(t!==`threads`||![`agent`,`human`,`any`].includes(n.waitingOn)))return`waitingOn applies to threads and must be agent, human or any.`;let r=t===`threads`?[`open`,`resolved`]:t===`asks`?[`draft`,`submitted`,`settled`,`orphan`]:t===`groups`?[`pending`,`pass`,`reject`]:[`open`,`submitted`,`closed`];return n?.status&&!r.includes(n.status)?`Invalid status for this section.`:n?.kind&&(t!==`groups`||![`choose`,`verify`].includes(n.kind))?`kind applies to groups.`:t===`groups`&&n?.status&&n.kind!==`verify`?`Verify status requires kind=verify.`:n?.choiceState&&(t!==`groups`||n.kind!==`choose`||![`chosen`,`empty`].includes(n.choiceState))?`choiceState requires a choice group.`:t&&e.fields?.some(e=>!_l[t].includes(e))?`Unknown field for this section.`:null}var Sl=class extends Error{code;status;constructor(e,t,n=400){super(t),this.code=e,this.status=n}};const Cl=e=>u.default.createHash(`sha256`).update(JSON.stringify(e)).digest(`hex`),wl=e=>{let t=[...new Intl.Segmenter(void 0,{granularity:`grapheme`}).segment(e)];return t.length>160?t.slice(0,160).map(e=>e.segment).join(``)+`…`:e};function Tl(e){let t=/* @__PURE__ */ new Map,n=0;for(let r of e.split(`
93
- `)){if(r.startsWith(`@@`)){n++;continue}if(!r.startsWith(`+`)&&!r.startsWith(`-`)||r.startsWith(`+++`)||r.startsWith(`---`))continue;let e=/\bid="([^"]+)"/.exec(r)?.[1],i=e??`hunk:${n}`,a=t.get(i)??{id:i,kind:e?`block`:`hunk`,additions:0,deletions:0,preview:``};r.startsWith(`+`)?a.additions++:a.deletions++,(!a.preview||r.startsWith(`+`))&&(a.preview=wl(r.slice(1))),t.set(i,a)}return[...t.values()]}function El(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=n.kind===`choose`?n.choice?`chosen`:`empty`:String(n.state??n.verdict??n.status??`unknown`);t.set(e,(t.get(e)??0)+1),n.waitingOn===`agent`&&t.set(`waitingOnAgent`,(t.get(`waitingOnAgent`)??0)+1)}return Object.fromEntries(t)}function Dl(e,t={}){let n=p.default.join(e,`agent-review`),r=t.now??Date.now,i=(e,t)=>p.default.join(n,`${e}-${t}.json`),a=-1/0,o=[];function s(){if(!o.length){if(r()-a<6e4||!d.default.existsSync(n))return;a=r(),o=d.default.readdirSync(n).filter(e=>/^(snapshot|cursor|receipt)-[\da-f-]{36}\.json$/.test(e))}for(let e=0;e<64&&o.length;e++){let e=p.default.join(n,o.pop());try{let t=JSON.parse(d.default.readFileSync(e,`utf8`));typeof t.expires==`number`&&t.expires<=r()&&d.default.unlinkSync(e)}catch{}}}function c(e){if(!d.default.existsSync(e))return null;try{return JSON.parse(d.default.readFileSync(e,`utf8`))}catch{throw new Sl(`E_REVIEW_STATE_INVALID`,`Review state could not be read; no cursor was changed.`,500)}}function l(e,t){d.default.mkdirSync(n,{recursive:!0,mode:448}),U(e,t)}let f=e=>i(`agent`,pn(e.artifact,e.agent));function m(e){return c(f(e))??{...e,consumed:[],frontiers:null}}function h(e,t,n){if(!/^[\da-f-]{36}$/.test(t))throw new Sl(`E_CURSOR_INVALID`,`Invalid review token.`);let a=c(i(e,t));if(!a||a.expires<=r())throw new Sl(`E_CURSOR_EXPIRED`,`Review token expired; restart the read.`,410);if(a.agent!==n.agent||a.artifact!==n.artifact)throw new Sl(`E_CURSOR_MISMATCH`,`Review token belongs to another agent or artifact.`);return a}function g(e,t,n){s();let a=u.default.randomUUID();return l(i(e,a),{...n,artifact:t.artifact,agent:t.agent,expires:r()+864e5}),a}function _(e,t){return Cl([t,!!e.all,e.filters??{}])}function v(e){return Cl(e.fields?[...e.fields].sort():null)}function y(e,t,n){let r=e.snapshot,i=0;if(e.cursor){let t=h(`cursor`,e.cursor,e);if(r&&r!==t.snapshot)throw new Sl(`E_CURSOR_MISMATCH`,`Cursor and snapshot differ.`);if(t.projection!==v(e))throw new Sl(`E_CURSOR_MISMATCH`,`Cursor projection differs; restart the read.`);r=t.snapshot,i=t.offset}r||=g(`snapshot`,e,{...n(),kind:t,descriptor:_(e,t),all:!!e.all});let a=h(`snapshot`,r,e);if(a.kind!==t||!e.thread&&a.descriptor!==_(e,t))throw new Sl(`E_CURSOR_MISMATCH`,`Cursor filters or projection differ; restart the read.`);return{id:r,value:a,offset:i}}function b(e,t,n){let r=e.thread?1:e.limit??10;if(!Number.isInteger(r)||r<1||r>100)throw new Sl(`E_ARGUMENT_INVALID`,`limit must be between 1 and 100.`);let i=t.value.items??[];if(e.thread&&(i=i.filter(t=>t.id===e.thread),!i.length))throw new Sl(`E_THREAD_NOT_FOUND`,`Thread not found in this snapshot.`,404);let a=e.thread?0:t.offset,o=i.slice(a,a+r),s=a+o.length<i.length?g(`cursor`,e,{snapshot:t.id,offset:a+o.length,projection:v(e)}):null,c;if(n&&!e.all&&!t.value.all&&!e.fields&&t.value.kind===`threads`&&o.length){let n=o.flatMap(e=>t.value.tokens?.[String(e.id)]??[]);n.length&&(c=g(`receipt`,e,{kind:`threads`,tokens:n}))}let l=o.map(e=>{if(n||t.value.kind!==`threads`)return e;let r=e,i=r.messages.filter(e=>!e.deleted),a=i.filter(e=>e.author===`human`).at(-1)??i.at(-1);return{id:r.id,status:r.status,waitingOn:ro(r),anchor:r.anchor,stale:e.stale??!1,...e.orphan===!0?{orphan:!0}:{},...typeof e.page==`string`?{page:e.page}:{},preview:wl(a?.text??(r.messages.some(e=>e.deleted)?`[deleted]`:``)),messageCount:r.messages.length,omittedMessages:r.messages.length}}),u=t.value.kind===`changes`?[`id`]:vl[t.value.kind],d=e.fields?l.map(t=>Object.fromEntries(Object.entries(t).filter(([t])=>e.fields.includes(t)||u.includes(t)))):l;return{items:d,summary:t.value.counts??El(i),snapshot:t.id,...c?{receipt:c}:{},page:{returned:d.length,total:i.length,hasMore:s!==null,nextCursor:s,offset:a,scope:t.value.all?`historical`:t.value.kind===`threads`?e.thread?`thread`:`unread`:`current_state`,snapshot:t.id}}}return{threads(e){let t=m(e),n=new Set(t.consumed);return b(e,y(e,`threads`,()=>{let t=e.threads.filter(t=>(e.all||e.thread||mn(t).some(e=>!n.has(e.token)))&&(!e.filters?.status||t.status===e.filters.status)&&(!e.filters?.waitingOn||e.filters.waitingOn===`any`||ro(t)===e.filters.waitingOn));return t.sort((e,t)=>{let n=mn(e).map(e=>e.at).sort().at(-1)??``,r=mn(t).map(e=>e.at).sort().at(-1)??``;return n.localeCompare(r)||e.id.localeCompare(t.id)}),{items:t.map(e=>({...e,waitingOn:ro(e)})),tokens:Object.fromEntries(t.map(e=>[e.id,mn(e).map(e=>e.token)]))}}),!!e.detail||!!e.thread)},state(e){let t=!(e.all||e.filters?.status||e.filters?.choiceState)&&e.actionable?e.actionable:()=>!0;return b(e,y(e,e.section,()=>({counts:El(e.items),items:e.items.filter(n=>t(n)&&(!e.filters?.status||n.state===e.filters.status||n.verdict===e.filters.status)&&(!e.filters?.kind||n.kind===e.filters.kind)&&(!e.filters?.choiceState||(e.filters.choiceState===`chosen`?!!n.choice:!n.choice)))})),!!e.detail)},ack(e){let t=h(`receipt`,e.receipt,e);if(t.kind!==e.kind)throw new Sl(`E_RECEIPT_INVALID`,`Receipt is for a different kind of evidence.`);if(t.acknowledged)return{status:`unchanged`};let n=m(e);if(t.kind===`threads`)n.consumed=[.../* @__PURE__ */ new Set([...n.consumed,...t.tokens??[]])];else{let e=/* @__PURE__ */ new Map;for(let r of[...n.frontiers??[],...t.to??[]])e.set(r.peer,Math.max(e.get(r.peer)??-1,r.counter));n.frontiers=[...e].map(([e,t])=>({peer:e,counter:t}))}return l(f(e),n),l(i(`receipt`,e.receipt),{...t,acknowledged:!0}),{status:`acknowledged`,...t.to?{to:t.to}:{}}},async changes(e){let t=m(e),n=e.snapshot;if(!n&&!e.cursor){let r=await e.load(e.all?null:t.frontiers);n=g(`snapshot`,e,{kind:`changes`,descriptor:_(e,`changes`),all:!!e.all,...r})}let r=y({...e,snapshot:n},`changes`,()=>({})),i=Tl(r.value.diff??``),a=e.detail?void 0:b(e,{...r,value:{...r.value,items:i.map(e=>({...e}))}},!1),o=a?new Set(a.items.map(e=>e.id)):void 0,s;return!e.detail||e.all||r.value.all||e.fields||r.value.empty||(s=g(`receipt`,e,{kind:`changes`,to:r.value.to})),{snapshot:r.id,empty:!!r.value.empty,blocks:o?i.filter(e=>o.has(e.id)):i,...a?{page:{...a.page,scope:`human_changes`}}:{},...e.detail?{diff:r.value.diff??``}:{},...s?{receipt:s}:{}}}}}var Ol=class extends Error{};const kl=/^\/api\/document\/([^/]+)\/state$/,Al=/^\/api\/document\/([^/]+)\/(update|comments)$/,jl=/^\/api\/agent\/document\/([^/]+)\/comments$/,Ml=/^\/api\/agent\/document\/([^/]+)\/changes$/,Nl=(e,t,n)=>e.documents.mergeRemote(t,n);async function Pl(e,t,n){let r=W(t.root,`document`,n)?await t.documents.open(n):null;r?B(e,200,await t.documentState(n,r)):B(e,404,{error:`document/${n} has no doc.xml`})}async function Fl(e,t,n,r){if(!W(n.root,`document`,r)){B(t,404,{error:`document/${r} not found`});return}let i=ms(await yc(e));if(!i)B(t,400,{error:`not a comment op`});else try{B(t,200,{comments:await n.documents.applyCommentOp(r,i)})}catch(e){B(t,400,{error:e.message})}}async function Il(e,t,n,r){let i=W(n.root,`document`,r)?await n.documents.open(r):null;if(!i){B(t,404,{error:`document/${r} has no doc.xml`});return}if(Number(e.headers[`content-length`]??0)>8388608){e.resume(),z(t,413,`Update too large`);return}let a=[],o=0;for await(let t of e)o+=t.length,o<=8388608&&a.push(t);if(o>8388608){z(t,413,`Update too large`);return}let s=e.headers[`x-ryugi-document-features`],c=typeof s==`string`?s.split(`,`).map(e=>e.trim()):[];try{await i.importUpdate(new Uint8Array(Buffer.concat(a)),c),z(t,204,``)}catch(e){B(t,e instanceof Ol?409:400,{error:e.message})}}const Ll={path:kl,auth:`viewer`,handle:(e,t,n,{match:r})=>Pl(t,n,r[1])},Rl={path:Al,methods:[`POST`],auth:`same-origin`,handle:(e,t,n,{match:r})=>r[2]===`comments`?Fl(e,t,n,r[1]):Il(e,t,n,r[1])},zl=async(e,t)=>{let n=await e.documents.open(t);return await n?.flush(),new Set(n?.summary().blocks??[])};async function Bl(e,t,n,r){let{root:i,documents:a}=n;if(!W(i,`document`,r)){B(t,404,{error:`document/${r} not found`});return}let o=await yc(e),s=typeof o==`object`&&o?o:{},c=bc(s);if(s.op===`list`){await _c(n,{type:`document`,id:r},Nl),B(t,200,{type:`comments`,artifact:`document/${r}`,threads:a.listComments(r,c??`Agent`,s.all===!0),...await a.asks(r)});return}if(s.op===`answer`||s.op===`submit`||s.op===`note`){try{B(t,200,await a.agentAsk(r,Hl(s),c))}catch(e){B(t,400,{error:e.message})}return}let l=hs(o);if(!l)B(t,400,{error:`not an agent comment op: use list, add {blockId, text}, reply {threadId, text} or resolve {threadId}; text must not be empty`});else{if(l.op===`add`){let e;try{e=await zl(n,r)}catch(e){B(t,400,{error:`doc.xml could not be read: ${e.message}`});return}let i=(l.blockIds??[l.blockId]).find(t=>!e.has(t));if(i){B(t,400,{error:`no block ${i} in document/${r}`});return}}try{B(t,200,a.applyAgentCommentOp(r,l,c))}catch(e){B(t,400,{error:e.message})}}}const Vl=e=>typeof e==`string`&&e.trim()?e:null;function Hl(e){if(e.op===`submit`){if(typeof e.submit!=`boolean`)throw Error(`submit needs {submit: true | false}`);return{op:`submit`,submit:e.submit}}if(!ps(e.ask))throw Error(`${String(e.op)} needs {ask}`);if(e.op===`note`){let t=Vl(e.text);if(!t)throw Error(`a note needs {text}`);return{op:`note`,ask:e.ask,text:t}}return{op:`answer`,ask:e.ask,choice:Vl(e.choice),answer:Vl(e.answer)}}async function Ul(e,t,n,r){if(!W(n.root,`document`,r)){B(t,404,{error:`document/${r} not found`});return}let i=await yc(e),a=typeof i==`object`&&i?i:{},o=await n.documents.changes(r,bc(a)??`Agent`,a.all===!0);o?B(t,200,{type:`changes`,artifact:`document/${r}`,...o}):B(t,404,{error:`document/${r} not found`})}const Wl={read:Qc,runtimeWarnings:(e,t,n)=>[...e.documents.warnings(t),...e.dynamicBlocks.state(t,n).warnings],threads:(e,t)=>e.documents.comments(t).threads,backlinksAs:`document`,state:(e,t,n)=>({extra:{dynamic:e.dynamicBlocks.state(t,n).dynamic}}),onFilesChanged:(e,t,n,r)=>{(r.includes(`doc.xml`)||r.length===0)&&e.documents.fileChanged(t),r.includes(`comments.json`)&&e.documents.commentsChanged(t)},acceptReport:(e,t,n,r)=>Wc(e,e.dynamicBlocks,{type:`document`,id:t},n,r),check:Gc,mergeRemote:Nl,pull:{threads:!0},review:{threads:async(e,t,n)=>{await _c(e,{type:`document`,id:t},Nl);let r=new Map(e.documents.listComments(t,n,!0).map(e=>[e.id,e]));return e.documents.comments(t).threads.filter(e=>!Ea(e)).map(e=>({...e,...r.get(e.id),messages:e.messages.map(({avatar:e,...t})=>t)}))},sections:{asks:async(e,t)=>({items:(await e.documents.asks(t)).asks.map(e=>({...e})),actionable:e=>e.state===`submitted`})},changes:{load:async(e,t)=>{let n=await e.documents.open(t);if(!n)throw new Sl(`E_ARTIFACT_NOT_FOUND`,`Document not found.`,404);return e=>n.changesSince(e)}}},relayOps:gl,preparePublish:fl,publishSession:(e,t)=>e.documents.open(t),publishExtras:(e,t)=>({comments:e.documents.comments(t)}),publish:ml,cloudPage:e=>e.endsWith(`.html`)?{embedded:!0}:null,opensOnRegister:!0,routes:[{path:jl,methods:[`POST`],auth:`agent`,handle:(e,t,n,{match:r})=>Bl(e,t,n,r[1])},{path:Ml,methods:[`POST`],auth:`agent`,handle:(e,t,n,{match:r})=>Ul(e,t,n,r[1])},Ll,Rl],resolveFile:at,pageRuntime:()=>({embedded:!0}),isPage:e=>e.endsWith(`.html`),keepsLocal:e=>e===wi},Gl=/^#[\da-f]{6}$/i,Kl=/* @__PURE__ */ new Set([`block`,`control`,`media`,`text`]),ql=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)?Math.round(Math.min(n,Math.max(t,e))*10)/10:null;function Jl(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=typeof t.bg==`string`&&Gl.test(t.bg)?t.bg:null;if(!n||!Array.isArray(t.boxes))return null;let r=typeof t.ink==`string`&&Gl.test(t.ink)?t.ink:void 0,i=[];for(let e of t.boxes.slice(0,64)){if(!e||typeof e!=`object`||Array.isArray(e))continue;let t=e,n=ql(t.x,-20,620),r=ql(t.y,-20,380),a=ql(t.w,1,620),o=ql(t.h,1,380);if(n===null||r===null||a===null||o===null)continue;let s=ql(t.r,0,48),c=typeof t.bg==`string`&&Gl.test(t.bg)?t.bg:void 0,l=typeof t.border==`string`&&Gl.test(t.border)?t.border:void 0,u=typeof t.kind==`string`&&Kl.has(t.kind)?t.kind:void 0;(c||l)&&i.push({x:n,y:r,w:a,h:o,...s?{r:s}:{},...c?{bg:c}:{},...l?{border:l}:{},...u?{kind:u}:{}})}return i.length>0?{bg:n,...r?{ink:r}:{},boxes:i}:null}const Yl=e=>e.replaceAll(/<[^>]+>/g,` `).replaceAll(/&nbsp;/gi,` `).replaceAll(/&amp;/gi,`&`).replaceAll(/&lt;/gi,`<`).replaceAll(/&gt;/gi,`>`).replaceAll(/&quot;/gi,`"`).replaceAll(/&#39;|&apos;/gi,`'`).replaceAll(/\s+/g,` `).trim();function Xl(e){let t=e.slice(0,2e5).replaceAll(/<!--[\s\S]*?-->/g,``).replaceAll(/<script\b[^>]*>[\s\S]*?<\/script>/gi,``).replaceAll(/<style\b[^>]*>[\s\S]*?<\/style>/gi,``),n=/<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(t),r=n?n[1]:t,i=/<(?:nav|header)\b/i.test(r),a=/<aside\b/i.test(r)||/\b(?:class|id)=["'][^"']*\b(?:sidebar|sidenav|toc)\b/i.test(r),o=/<h[12]\b[^>]*>([\s\S]*?)<\/h[12]>/i.exec(r),s=o&&Yl(o[1]).slice(0,120)||void 0,c=[],l=e=>{c.length>=4||c.at(-1)!==e&&c.push(e)},u=/<(table|pre|form|canvas|svg|ul|ol|p|article|section|div)\b([^>]*)>/gi,d=0,f;for(;(f=u.exec(r))!==null&&c.length<4;){let e=f[1].toLowerCase(),t=f[2]??``;e===`table`?l(`table`):e===`pre`?l(`code`):e===`form`?l(`form`):e===`canvas`||e===`svg`?e!==`canvas`&&/\b(?:width|height)=["']?(?:1[0-9]|2[0-4])\b/i.test(t)||l(`chart`):e===`ul`||e===`ol`?l(`list`):e===`article`?(d+=1,d>=2&&l(`cards`)):e===`section`||e===`div`?/\b(?:grid|cards?|bento|columns?|kpi|metrics?|stats?)\b/i.test(t)?l(`cards`):/\b(?:chart|graph|plot|sparkline)\b/i.test(t)?l(`chart`):/\b(?:code|editor|terminal|console)\b/i.test(t)&&l(`code`):e===`p`&&l(`text`)}return c.length===0&&(/<(?:input|select|textarea|button)\b/i.test(r)?c.push(`form`):c.push(`text`)),{...i?{hasNav:!0}:{},...a?{hasSidebar:!0}:{},...s?{heading:s}:{},blocks:c}}function Zl(e,{artifact:t,snapshot:n}){if(typeof t!=`string`)return;let{root:r}=e,i=G(t,Xn);if(!i||i.type!==`html`)return;let a;try{a=Si(r,i.type,i.id)}catch{a=null}if(!a)return;let o=Jl(n);if(!o)return;let s=p.default.join(e.stateDir,`html`,a.id);try{d.default.mkdirSync(s,{recursive:!0}),d.default.writeFileSync(p.default.join(s,`dom-skeleton.json`),JSON.stringify(o))}catch{}}const Ql=/<title[^>]*>([\s\S]*?)<\/title>/i;function $l(e,t){let n;try{n=d.default.readFileSync(p.default.join(e,H.html),`utf8`)}catch{return{title:t,warnings:[`index.html not found`],version:ir(e)}}return{title:Ql.exec(n)?.[1]?.trim()||t,warnings:[],version:ir(e)}}function eu(e,t,n){let r;try{r=Xl(d.default.readFileSync(p.default.join(e,`index.html`),`utf8`))}catch{r=void 0}let i=null;try{let n=p.default.join(p.default.dirname(p.default.dirname(e)),`.state`,`html`,t,`dom-skeleton.json`);i=Jl(JSON.parse(d.default.readFileSync(n,`utf8`)))}catch{i=null}return{title:n,...r?{skeleton:r}:{},...i?{domSnapshot:i}:{}}}const tu={read:$l,runtimeWarning:e=>`runtime: ${e}`,noAgent:!0,listedStateFile:`dom-skeleton.json`,backlinksAs:`html`,state:(e,t,n,r)=>({extra:`version`in r?{ran:e.ranVersions.get(`html/${t}`)===r.version}:{}}),clientMessages:{"html-skeleton":Zl},check:{evidence:Ci},publish:eu,cloudPage:e=>e===`index.html`?{}:null,opensOnRegister:!0,resolveFile:st,pageRuntime:()=>({capture:!0}),isPage:e=>e===`index.html`,keepsLocal:()=>!1},nu=(0,h.promisify)(l.execFile),ru=/^[a-z0-9]+(?:\.[a-z0-9]+)*$/,iu=/^(.+?)(?:@(\d{1,2}))?\.png$/;function au(e){let t=iu.exec(e),n=t?.[1];if(!n||n.length>80||!ru.test(n))return null;let r=t[2]===void 0?20:Number(t[2]);return r>=8&&r<=96?{name:n,size:r}:null}const ou=`ObjC.import('AppKit');
94
- function run(argv) {
95
- const [name, out, size] = argv;
96
- const base = $.NSImage.imageWithSystemSymbolNameAccessibilityDescription(name, $.NSString.string);
97
- if (base.isNil()) return 'missing';
98
- const image = base.imageWithSymbolConfiguration(
99
- $.NSImageSymbolConfiguration.configurationWithPointSizeWeightScale(Number(size), 0, 2));
100
- const s = image.size;
101
- const w = Math.ceil(s.width * 3);
102
- const h = Math.ceil(s.height * 3);
103
- const rep = $.NSBitmapImageRep.alloc.initWithBitmapDataPlanesPixelsWidePixelsHighBitsPerSampleSamplesPerPixelHasAlphaIsPlanarColorSpaceNameBytesPerRowBitsPerPixel(
104
- null, w, h, 8, 4, true, false, $('NSDeviceRGBColorSpace'), 0, 0);
105
- const context = $.NSGraphicsContext.graphicsContextWithBitmapImageRep(rep);
106
- $.NSGraphicsContext.saveGraphicsState;
107
- $.NSGraphicsContext.setCurrentContext(context);
108
- image.drawInRectFromRectOperationFraction($.NSMakeRect(0, 0, w, h), $.NSZeroRect, 2, 1);
109
- context.flushGraphics;
110
- $.NSGraphicsContext.restoreGraphicsState;
111
- rep.representationUsingTypeProperties(4, $.NSDictionary.dictionary).writeToFileAtomically(out, true);
112
- return 'ok';
113
- }
114
- `,su=u.default.createHash(`sha256`).update(ou).digest(`hex`).slice(0,12),cu=/* @__PURE__ */ new Map;function lu(e,t,{platform:n=process.platform,cacheDir:r}){if(n!==`darwin`||!ru.test(e))return Promise.resolve(null);let i=p.default.join(r,su),a=p.default.join(i,`${e}@${t}.png`);if(d.default.existsSync(a))return Promise.resolve(a);let o=cu.get(a);if(o)return o;let s=uu(e,t,a,i).finally(()=>cu.delete(a));return cu.set(a,s),s}async function uu(e,t,n,r){d.default.mkdirSync(r,{recursive:!0});let i=p.default.join(r,`render.js`);d.default.existsSync(i)||d.default.writeFileSync(i,ou);try{let{stdout:r}=await nu(`osascript`,[`-l`,`JavaScript`,i,e,n,String(t)],{timeout:1e4});return r.trim()===`ok`&&d.default.existsSync(n)?n:null}catch{return null}}const du=[`desktop`,`laptop`,`tablet`,`mobile`],fu=/* @__PURE__ */ new Set([`localhost`,`127.0.0.1`,`[::1]`,`::1`]),pu=4096;function mu(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t||t.length>256)return null;let n;try{n=new URL(t)}catch{return null}if(n.protocol!==`http:`||n.username||n.password||n.search||n.hash||n.pathname!==`/`&&n.pathname!==``)return null;let r=n.hostname.toLowerCase();if(!fu.has(r))return null;let i=n.port?Number(n.port):80;return!Number.isInteger(i)||i<1||i>65535?null:{origin:n.origin,host:n.host,hostname:r===`[::1]`?`::1`:r,port:i}}function hu(e){let t=e.trim();if(!t||t.length>1024)return null;let n=/^https?:\/\//i.test(t)?t:`http://${t}`,r;try{r=new URL(n)}catch{return null}let i=mu(r.origin);if(!i)return null;let a=`${r.pathname||`/`}${r.search}${r.hash}`;return{url:i.origin,path:a}}function gu(e){if(typeof e==`string`)return du.includes(e)?e:null;if(typeof e==`object`&&e&&!Array.isArray(e)){let{w:t,h:n}=e;if(typeof t==`number`&&typeof n==`number`&&Number.isInteger(t)&&Number.isInteger(n)&&t>=240&&t<=pu&&n>=240&&n<=pu)return{w:t,h:n}}return null}function _u(e){if(typeof e!=`string`)return null;let t=e.trim();return!t||t.length>2e3||!t.startsWith(`/`)||t.startsWith(`//`)?null:t}function vu(e){let t;try{t=JSON.parse(e)}catch(e){return{config:null,issues:[`preview.json is not valid JSON: ${e.message}`]}}if(typeof t!=`object`||!t||Array.isArray(t))return{config:null,issues:[`preview.json must be a JSON object`]};let n=t,r=[];n.version!==1&&r.push(`preview.json requires version: 1`);let i=mu(n.url);i||r.push(`preview.json url must be a local loopback http origin (e.g. http://localhost:5173 or http://127.0.0.1:3000)`);let a;n.title!==void 0&&(typeof n.title!=`string`||!n.title.trim()||n.title.length>200?r.push(`preview.json title must be a non-empty string (<= 200 chars)`):a=n.title.trim());let o;if(n.path!==void 0){let e=_u(n.path);e?o=e:r.push(`preview.json path must start with "/" (and not "//")`)}let s;if(n.viewport!==void 0){let e=gu(n.viewport);e?s=e:r.push(`preview.json viewport must be one of ${du.join(`, `)} or { w, h } (240..${pu})`)}return r.length>0||!i?{config:null,issues:r}:{config:{version:1,url:i.origin,...a?{title:a}:{},...o?{path:o}:{},...s?{viewport:s}:{}},issues:[]}}const yu=`preview.json`,bu=/^[a-z0-9][a-z0-9-]{0,63}$/;function xu(e){return p.default.join(p.default.dirname(e),`preview`)}function Su(e,t){return bu.test(t)?p.default.join(xu(e),t):null}function Cu(e,t){let n=Su(e,t);return n&&d.default.existsSync(p.default.join(n,`preview.json`))?n:null}function wu(e){let t=xu(e),n;try{n=d.default.readdirSync(t)}catch{return[]}let r=[];for(let e of n){if(!bu.test(e))continue;let n=p.default.join(t,e);d.default.existsSync(p.default.join(n,`preview.json`))&&r.push({id:e,payload:Tu(n,e)})}return r}function Tu(e,t,n){let r=p.default.join(e,yu),i,a=1;try{let e=d.default.statSync(r);a=Math.trunc(e.mtimeMs)||1,i=d.default.readFileSync(r,`utf8`)}catch{return{title:t,version:a,config:null,issues:[`preview.json is missing`],warnings:[`preview.json is missing`],proxyUrl:n??null}}let{config:o,issues:s}=vu(i);return{title:o?.title||t,version:a,config:o,issues:s,warnings:s,proxyUrl:n??null}}function Eu(e,t){d.default.mkdirSync(e,{recursive:!0}),U(p.default.join(e,yu),t)}function Du(e,t,n){return new Promise(r=>{let i=m.default.connect({host:e,port:t}),a=!1,o=e=>{a||(a=!0,i.destroy(),r(e))};i.setTimeout(n,()=>o(!1)),i.once(`connect`,()=>o(!0)),i.once(`error`,()=>o(!1))})}async function Ou(e,t=800){let n=mu(e);if(!n)return!1;if(n.hostname!==`localhost`)return Du(n.hostname,n.port,t);let r=await Promise.all([Du(`127.0.0.1`,n.port,t),Du(`::1`,n.port,t)]);return r[0]||r[1]}const ku=e=>p.default.join(e,`preview`,`recent.json`);function Au(e){try{let t=JSON.parse(d.default.readFileSync(ku(e),`utf8`));return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&mu(e.url)!==null&&typeof e.id==`string`):[]}catch{return[]}}function ju(e,t){let n=mu(t.url);if(!n)return;let r=_u(t.path)??`/`,i={url:n.origin,path:r,id:t.id,at:(/* @__PURE__ */ new Date()).toISOString()},a=Au(e).filter(e=>e.url!==i.url);U(ku(e),[i,...a].slice(0,8))}const Mu={resolveDir:Cu,threads:(e,t)=>{let n=e.previewComments.agentView(t);return e.previewComments.comments(t).threads.map(e=>{let t=n(e);return{...e,...t,anchor:{...e.anchor,...t.cropPath?{cropPath:t.cropPath}:{}},messages:t.messages}})}},Nu=/^marks\/[\w-]{1,100}-1\.jpg$/,Pu=e=>typeof e==`number`&&Number.isFinite(e),Fu=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t;function Iu(e){if(!Va(e))return null;let{x:t,y:n,w:r,h:i}=e;return![t,n,r,i].every(Pu)||r<=0||i<=0?null:{x:Math.round(t),y:Math.round(n),w:Math.round(r),h:Math.round(i)}}function Lu(e){if(!Va(e))return null;let{w:t,h:n}=e;return!Pu(t)||!Pu(n)||t<=0||n<=0?null:{w:Math.round(t),h:Math.round(n)}}function Ru(e){if(!Va(e))return null;let t={};if(e.component!==void 0){if(!Fu(e.component,120))return null;t.component=e.component}if(e.file!==void 0){if(!Fu(e.file,500))return null;t.file=e.file}if(e.line!==void 0){if(!Number.isInteger(e.line)||e.line<1)return null;t.line=e.line}return Object.keys(t).length>0?t:null}function zu(e){if(!Va(e)||!Fu(e.route,2e3)||!e.route.startsWith(`/`)||e.kind!==`element`&&e.kind!==`box`)return null;let t=Lu(e.viewport),n=Iu(e.rect);if(!t||!n)return null;let r={route:e.route,viewport:t,kind:e.kind,rect:n};if(e.pageRect!==void 0){let t=Iu(e.pageRect);t&&(r.pageRect=t)}if(e.selector!==void 0){if(!Fu(e.selector,1e3))return null;r.selector=e.selector}if(e.tag!==void 0){if(!Fu(e.tag,60))return null;r.tag=e.tag.toLowerCase()}if(e.text!==void 0){if(typeof e.text!=`string`)return null;let t=e.text.trim().slice(0,200);t&&(r.text=t)}if(e.source!==void 0){let t=Ru(e.source);t&&(r.source=t)}if(typeof e.crop==`string`&&Nu.test(e.crop)&&(r.crop=e.crop),e.errors!==void 0){if(!Array.isArray(e.errors))return null;let t=e.errors.filter(e=>typeof e==`string`&&e.trim().length>0).slice(0,5).map(e=>e.trim().slice(0,400));t.length>0&&(r.errors=t)}return r}const Bu={read:zu,same:(e,t)=>e.route===t.route&&e.kind===t.kind&&e.selector===t.selector&&e.rect.x===t.rect.x&&e.rect.y===t.rect.y&&e.rect.w===t.rect.w&&e.rect.h===t.rect.h,missing:`a new thread needs a preview anchor (route, viewport, kind, rect); dropped it`},Vu=()=>({version:1,threads:[]}),Hu=e=>Ga(e,Bu),Uu=(e,t,n,r,i,a)=>Za(e,t,n,r,i,a,Bu);function Wu(e,t,n,r,i){return t.op===`create`?{...e,threads:[...e.threads,eo(t.anchor,`human`,t.text,n,r,i)]}:no(e,t,n,r,i)}function Gu(e,t,n,r,i){if(t.op!==`add`)return uo(e,t,n,r,i);let a=eo(t.anchor,`agent`,t.text,n,r,{name:i});return{file:{...e,threads:[...e.threads,a]},threadId:a.id,messageId:a.messages[0].id}}const Ku={empty:Vu,saved:Hu,merge:Uu,human:(e,t,n,r,i)=>Wu(e,t,n,r,i),agent:Gu};function qu(e){if(typeof e!=`object`||!e)return null;let{host:t,id:n}=e;return t!==`claude`&&t!==`codex`&&t!==`antigravity`||typeof n!=`string`||!n.length||n.length>200?null:{host:t,id:n}}function Ju(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.op!==`create`){let t=ms(e);return t&&t.op!==`create`?t:null}let n=zu(t.anchor);if(!n||!fs(t.text)||t.text.length===0)return null;let{crop:r,...i}=n,a=qu(t.session);return{op:`create`,anchor:i,text:t.text,...typeof t.crop==`string`?{crop:t.crop}:{},...a?{session:a}:{}}}function Yu(e){if(typeof e!=`object`||!e)return null;let t=e,n=fs(t.text)&&t.text.length>0?t.text:null;if(t.op===`add`){let e=zu(t.anchor);return!e||!n?null:{op:`add`,anchor:e,text:n}}return typeof t.threadId!=`string`||t.threadId.length===0?null:t.op===`reply`?n?{op:`reply`,threadId:t.threadId,text:n}:null:t.op===`resolve`?{op:`resolve`,threadId:t.threadId}:null}function Xu(e){let t=/* @__PURE__ */ new Map,n=$o(e.stateDir,`preview`),r=t=>Es(e.stateDir,`preview/${t}`),i=t=>p.default.join(xu(e.root),t),a=n=>{let r=t.get(n);return r||(r=vs(p.default.join(i(n),`comments.json`),Ku,e.names,{artifact:`preview/${n}`,savesDir:p.default.join(e.stateDir,`preview`,n,`comment-saves`)}),t.set(n,r)),r},o=e=>({comments:a(e).current(),listening:r(e)}),s=t=>e.broadcast({type:`preview-comments`,artifact:`preview/${t}`,...o(t)}),c=(e,t,n)=>{let r=ns(i(e),t,n);return r?(a(e).update(e=>({...e,threads:e.threads.map(e=>e.id===t?{...e,anchor:{...e.anchor,crop:r}}:e)})),r):null},l=(e,t)=>{let n=new Set(t.threads.filter(e=>e.messages.some(e=>!e.deleted)).map(e=>e.anchor.crop).filter(e=>typeof e==`string`).map(e=>p.default.basename(e)));rs(i(e),n)},u=e=>{let t=i(e);return n=>{let r=n.anchor.crop,i=r&&d.default.existsSync(p.default.join(t,r))?p.default.posix.join(`.ryugi`,`preview`,e,r):void 0;return{...n,messages:n.messages.map(({avatar:e,...t})=>t),waitingOn:ro(n),...i?{cropPath:i}:{}}}};return{comments:e=>a(e).current(),state:o,agentView:u,list(e,t,r=!1){let i=a(e).current(),o=u(e);if(r)return i.threads.map(o);let{threads:s,newest:c}=co(i,n.get(e,t));return c&&n.set(e,t,c),s.map(o)},applyHuman(e,t){let n=a(e);if(t.op!==`create`)return n.apply(t),t.op===`delete`&&l(e,n.current()),s(e),o(e);let r=new Set(n.current().threads.map(e=>e.id)),{crop:i,...u}=t;n.apply(u);let d=n.current().threads.find(e=>!r.has(e.id));return d&&i&&c(e,d.id,i),s(e),o(e)},applyAgent(e,t,n){let r=a(e).applyAgent(t,n);return s(e),r},reload(e){a(e).sync(),l(e,a(e).current()),s(e)}}}const Zu=/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i;function Qu(e,t,n,r){return Zu.test(n)?ws(e)?.subscribed(t,n,r)??!1:!1}function $u(e,t,n){return n.filter(n=>Qu(e,n.host,n.id,t))}function ed(e,t,n,r,i){let a=ws(t);return!Zu.test(r)||!a?!1:(a.subscribe(n,r,i),!0)}function td(e){let{artifact:t,explicitSession:n,projectRoot:r,sessions:i,stateDir:a}=e;if(n&&(n.host===`claude`||n.host===`antigravity`||n.host===`codex`))return ed(r,a,n.host,n.id,t)?{host:n.host,id:n.id}:null;let o=$u(a,t,i);if(o.length>0)return{host:o[0].host,id:o[0].id};if(i.length===1){let e=i[0];return ed(r,a,e.host,e.id,t)?{host:e.host,id:e.id}:null}return null}const nd=/^\/api\/preview-dev\/list$/,rd=/^\/api\/preview-dev\/recent$/,id=/^\/api\/preview-dev\/open$/,ad=/^\/api\/preview-dev\/([^/]+)\/state$/,od=/^\/api\/preview-dev\/([^/]+)\/config$/,sd=/^\/api\/preview-dev\/([^/]+)\/comments$/,cd=/^\/api\/preview-dev\/([^/]+)\/selection$/,ld=/^\/api\/preview-dev\/([^/]+)\/marks\/([\w-]{1,100}-\d+\.jpg)$/,ud=/^\/api\/agent\/preview\/([^/]+)\/comments$/;function dd(e){return`http://${ne(e.options.urlHost)}:${e.port}`}function fd(e){return`${dd(e)}${e.contentPrefix}runtime/ryugi-preview-bridge.js`}function pd(e){return p.default.dirname(p.default.dirname(e.root))}const md={review:Mu,routes:[{path:nd,methods:[`GET`],auth:`viewer`,handle(e,t,n){B(t,200,{previews:wu(n.root).map(({id:e,payload:t})=>{let r=n.previewComments.comments(e).threads.filter(e=>e.status!==`resolved`).length;return{id:e,title:t.title,url:t.config?.url??null,path:t.config?.path??`/`,openThreads:r,href:`/preview/${encodeURIComponent(e)}?project=${encodeURIComponent(pd(n))}`}})})}},{path:ld,methods:[`GET`],auth:`viewer`,handle(e,t,n,{match:r}){let i=decodeURIComponent(r[1]),a=r[2],o=Cu(n.root,i);o?ie(t,p.default.join(o,`marks`,a)):z(t,404,`Not found`)}},{path:rd,methods:[`GET`],auth:`viewer`,handle(e,t,n){B(t,200,{recent:Au(n.stateDir),sessions:n.agentStatus.sessions()})}},{path:id,methods:[`POST`],auth:`same-origin`,async handle(e,t,n){let r=await yc(e);if(!r||typeof r!=`object`){B(t,400,{error:`Expected JSON body with url`});return}let i=hu(typeof r.url==`string`?r.url:``);if(!i){B(t,400,{error:`Only local loopback http URLs are allowed (e.g. http://localhost:5173)`});return}let a=typeof r.id==`string`&&r.id.trim()?r.id.trim():`dev`;if(!bu.test(a)){B(t,400,{error:`Preview id must use lowercase letters, digits, and hyphens`});return}let o=_u(r.path)??i.path,s=typeof r.title==`string`&&r.title.trim()?r.title.trim().slice(0,200):void 0,c=Su(n.root,a),l=null;try{l=vu(d.default.readFileSync(p.default.join(c,`preview.json`),`utf8`)).config}catch{}let u={version:1,url:i.url,...s?{title:s}:l?.title?{title:l.title}:{},...o&&o!==`/`?{path:o}:{},...l?.viewport?{viewport:l.viewport}:{}};Eu(c,u),ju(n.stateDir,{id:a,url:u.url,path:u.path});let f=await n.previewProxies.ensure({id:a,targetOrigin:u.url,viewerOrigin:dd(n),bridgeScriptUrl:fd(n)}),m=await Ou(u.url);B(t,200,{id:a,artifact:`preview/${a}`,config:u,proxyUrl:f.origin,upstreamAlive:m,href:`/preview/${encodeURIComponent(a)}?project=${encodeURIComponent(pd(n))}`})}},{path:ad,methods:[`GET`],auth:`viewer`,async handle(e,t,n,{match:r}){let i=decodeURIComponent(r[1]),a=Cu(n.root,i);if(!a){B(t,404,{error:`preview/${i} not found`});return}let o=Tu(a,i),s=null,c=!1;o.config&&(s=(await n.previewProxies.ensure({id:i,targetOrigin:o.config.url,viewerOrigin:dd(n),bridgeScriptUrl:fd(n)})).origin,c=await Ou(o.config.url));let l=n.agentStatus.sessions(),u=$u(n.stateDir,`preview/${i}`,l).map(e=>({host:e.host,id:e.id})),d=n.previewComments.state(i);B(t,200,{...o,contentBase:`/api/preview-dev/${encodeURIComponent(i)}/`,proxyUrl:s,upstreamAlive:c,comments:d.comments,listening:d.listening,sessions:l,subscribedSessions:u})}},{path:od,methods:[`POST`],auth:`same-origin`,async handle(e,t,n,{match:r}){let i=decodeURIComponent(r[1]),a=Cu(n.root,i);if(!a){B(t,404,{error:`preview/${i} not found`});return}let o=await yc(e);if(!o||typeof o!=`object`){B(t,400,{error:`Expected JSON body`});return}let s=Tu(a,i).config,c=typeof o.url==`string`?o.url:s?.url,l=c?mu(c)??(hu(c)?.url?mu(hu(c).url):null):null;if(!l){B(t,400,{error:`url must be a valid local loopback http origin`});return}let u={version:1,url:l.origin,...s?.title?{title:s.title}:{},...s?.path?{path:s.path}:{},...s?.viewport?{viewport:s.viewport}:{}};o.title!==void 0&&(u.title=o.title),o.path!==void 0&&(u.path=o.path),o.viewport!==void 0&&(u.viewport=o.viewport);let{config:d,issues:f}=vu(JSON.stringify(u));if(!d){B(t,400,{error:f.join(`; `)});return}Eu(a,d),ju(n.stateDir,{id:i,url:d.url,path:d.path});let p=await n.previewProxies.ensure({id:i,targetOrigin:d.url,viewerOrigin:dd(n),bridgeScriptUrl:fd(n)}),m=await Ou(d.url);B(t,200,{config:d,proxyUrl:p.origin,upstreamAlive:m})}},{path:sd,methods:[`POST`],auth:`same-origin`,async handle(e,t,n,{match:r}){let i=decodeURIComponent(r[1]);if(!Cu(n.root,i)){B(t,404,{error:`preview/${i} not found`});return}let a=Ju(await yc(e));if(!a){B(t,400,{error:`invalid preview comment operation`});return}let o=n.previewComments.applyHuman(i,a),s=null;a.op===`create`&&(s=td({artifact:`preview/${i}`,explicitSession:a.session,projectRoot:pd(n),sessions:n.agentStatus.sessions(),stateDir:n.stateDir})),B(t,200,{...o,routedSession:s})}},{path:cd,methods:[`POST`],auth:`same-origin`,async handle(e,t,n,{match:r}){let i=decodeURIComponent(r[1]);if(!Cu(n.root,i)){B(t,404,{error:`preview/${i} not found`});return}let a=await yc(e),o=p.default.join(n.stateDir,`preview`,i,`selection.json`);if(!a||a.selected===null){try{d.default.rmSync(o,{force:!0})}catch{}B(t,200,{ok:!0})}else U(o,{artifact:`preview/${i}`,updatedAt:(/* @__PURE__ */ new Date()).toISOString(),selected:a.selected}),B(t,200,{ok:!0})}},{path:ud,methods:[`POST`],auth:`agent`,async handle(e,t,n,{match:r}){let i=decodeURIComponent(r[1]);if(!Cu(n.root,i)){B(t,404,{error:`preview/${i} not found`});return}let a=await yc(e),o=typeof a==`object`&&a?a:{},s=bc(o);if(o.op===`list`){B(t,200,{type:`comments`,artifact:`preview/${i}`,threads:n.previewComments.list(i,s??`Agent`,o.all===!0)});return}let c=Yu(a);if(!c)B(t,400,{error:`not a preview agent comment op: use list, add {anchor, text}, reply {threadId, text} or resolve {threadId}`});else try{B(t,200,n.previewComments.applyAgent(i,c,s))}catch(e){B(t,400,{error:e.message})}}}]};var hd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t;(function(e){e[e.NONE=0]=`NONE`,e[e._abstract=1]=`_abstract`,e[e._accessor=2]=`_accessor`,e[e._as=3]=`_as`,e[e._assert=4]=`_assert`,e[e._asserts=5]=`_asserts`,e[e._async=6]=`_async`,e[e._await=7]=`_await`,e[e._checks=8]=`_checks`,e[e._constructor=9]=`_constructor`,e[e._declare=10]=`_declare`,e[e._enum=11]=`_enum`,e[e._exports=12]=`_exports`,e[e._from=13]=`_from`,e[e._get=14]=`_get`,e[e._global=15]=`_global`,e[e._implements=16]=`_implements`,e[e._infer=17]=`_infer`,e[e._interface=18]=`_interface`,e[e._is=19]=`_is`,e[e._keyof=20]=`_keyof`,e[e._mixins=21]=`_mixins`,e[e._module=22]=`_module`,e[e._namespace=23]=`_namespace`,e[e._of=24]=`_of`,e[e._opaque=25]=`_opaque`,e[e._out=26]=`_out`,e[e._override=27]=`_override`,e[e._private=28]=`_private`,e[e._protected=29]=`_protected`,e[e._proto=30]=`_proto`,e[e._public=31]=`_public`,e[e._readonly=32]=`_readonly`,e[e._require=33]=`_require`,e[e._satisfies=34]=`_satisfies`,e[e._set=35]=`_set`,e[e._static=36]=`_static`,e[e._symbol=37]=`_symbol`,e[e._type=38]=`_type`,e[e._unique=39]=`_unique`,e[e._using=40]=`_using`})(t||(e.ContextualKeyword=t={}))})),K=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});
115
- /* istanbul ignore file */
116
- var t;(function(e){e[e.PRECEDENCE_MASK=15]=`PRECEDENCE_MASK`,e[e.IS_KEYWORD=16]=`IS_KEYWORD`,e[e.IS_ASSIGN=32]=`IS_ASSIGN`,e[e.IS_RIGHT_ASSOCIATIVE=64]=`IS_RIGHT_ASSOCIATIVE`,e[e.IS_PREFIX=128]=`IS_PREFIX`,e[e.IS_POSTFIX=256]=`IS_POSTFIX`,e[e.IS_EXPRESSION_START=512]=`IS_EXPRESSION_START`,e[e.num=512]=`num`,e[e.bigint=1536]=`bigint`,e[e.decimal=2560]=`decimal`,e[e.regexp=3584]=`regexp`,e[e.string=4608]=`string`,e[e.name=5632]=`name`,e[e.eof=6144]=`eof`,e[e.bracketL=7680]=`bracketL`,e[e.bracketR=8192]=`bracketR`,e[e.braceL=9728]=`braceL`,e[e.braceBarL=10752]=`braceBarL`,e[e.braceR=11264]=`braceR`,e[e.braceBarR=12288]=`braceBarR`,e[e.parenL=13824]=`parenL`,e[e.parenR=14336]=`parenR`,e[e.comma=15360]=`comma`,e[e.semi=16384]=`semi`,e[e.colon=17408]=`colon`,e[e.doubleColon=18432]=`doubleColon`,e[e.dot=19456]=`dot`,e[e.question=20480]=`question`,e[e.questionDot=21504]=`questionDot`,e[e.arrow=22528]=`arrow`,e[e.template=23552]=`template`,e[e.ellipsis=24576]=`ellipsis`,e[e.backQuote=25600]=`backQuote`,e[e.dollarBraceL=27136]=`dollarBraceL`,e[e.at=27648]=`at`,e[e.hash=29184]=`hash`,e[e.eq=29728]=`eq`,e[e.assign=30752]=`assign`,e[e.preIncDec=32640]=`preIncDec`,e[e.postIncDec=33664]=`postIncDec`,e[e.bang=34432]=`bang`,e[e.tilde=35456]=`tilde`,e[e.pipeline=35841]=`pipeline`,e[e.nullishCoalescing=36866]=`nullishCoalescing`,e[e.logicalOR=37890]=`logicalOR`,e[e.logicalAND=38915]=`logicalAND`,e[e.bitwiseOR=39940]=`bitwiseOR`,e[e.bitwiseXOR=40965]=`bitwiseXOR`,e[e.bitwiseAND=41990]=`bitwiseAND`,e[e.equality=43015]=`equality`,e[e.lessThan=44040]=`lessThan`,e[e.greaterThan=45064]=`greaterThan`,e[e.relationalOrEqual=46088]=`relationalOrEqual`,e[e.bitShiftL=47113]=`bitShiftL`,e[e.bitShiftR=48137]=`bitShiftR`,e[e.plus=49802]=`plus`,e[e.minus=50826]=`minus`,e[e.modulo=51723]=`modulo`,e[e.star=52235]=`star`,e[e.slash=53259]=`slash`,e[e.exponent=54348]=`exponent`,e[e.jsxName=55296]=`jsxName`,e[e.jsxText=56320]=`jsxText`,e[e.jsxEmptyText=57344]=`jsxEmptyText`,e[e.jsxTagStart=58880]=`jsxTagStart`,e[e.jsxTagEnd=59392]=`jsxTagEnd`,e[e.typeParameterStart=60928]=`typeParameterStart`,e[e.nonNullAssertion=61440]=`nonNullAssertion`,e[e._break=62480]=`_break`,e[e._case=63504]=`_case`,e[e._catch=64528]=`_catch`,e[e._continue=65552]=`_continue`,e[e._debugger=66576]=`_debugger`,e[e._default=67600]=`_default`,e[e._do=68624]=`_do`,e[e._else=69648]=`_else`,e[e._finally=70672]=`_finally`,e[e._for=71696]=`_for`,e[e._function=73232]=`_function`,e[e._if=73744]=`_if`,e[e._return=74768]=`_return`,e[e._switch=75792]=`_switch`,e[e._throw=77456]=`_throw`,e[e._try=77840]=`_try`,e[e._var=78864]=`_var`,e[e._let=79888]=`_let`,e[e._const=80912]=`_const`,e[e._while=81936]=`_while`,e[e._with=82960]=`_with`,e[e._new=84496]=`_new`,e[e._this=85520]=`_this`,e[e._super=86544]=`_super`,e[e._class=87568]=`_class`,e[e._extends=88080]=`_extends`,e[e._export=89104]=`_export`,e[e._import=90640]=`_import`,e[e._yield=91664]=`_yield`,e[e._null=92688]=`_null`,e[e._true=93712]=`_true`,e[e._false=94736]=`_false`,e[e._in=95256]=`_in`,e[e._instanceof=96280]=`_instanceof`,e[e._typeof=97936]=`_typeof`,e[e._void=98960]=`_void`,e[e._delete=99984]=`_delete`,e[e._async=100880]=`_async`,e[e._get=101904]=`_get`,e[e._set=102928]=`_set`,e[e._declare=103952]=`_declare`,e[e._readonly=104976]=`_readonly`,e[e._abstract=106e3]=`_abstract`,e[e._static=107024]=`_static`,e[e._public=107536]=`_public`,e[e._private=108560]=`_private`,e[e._protected=109584]=`_protected`,e[e._override=110608]=`_override`,e[e._as=112144]=`_as`,e[e._enum=113168]=`_enum`,e[e._type=114192]=`_type`,e[e._implements=115216]=`_implements`})(t||(e.TokenType=t={}));function n(e){switch(e){case t.num:return`num`;case t.bigint:return`bigint`;case t.decimal:return`decimal`;case t.regexp:return`regexp`;case t.string:return`string`;case t.name:return`name`;case t.eof:return`eof`;case t.bracketL:return`[`;case t.bracketR:return`]`;case t.braceL:return`{`;case t.braceBarL:return`{|`;case t.braceR:return`}`;case t.braceBarR:return`|}`;case t.parenL:return`(`;case t.parenR:return`)`;case t.comma:return`,`;case t.semi:return`;`;case t.colon:return`:`;case t.doubleColon:return`::`;case t.dot:return`.`;case t.question:return`?`;case t.questionDot:return`?.`;case t.arrow:return`=>`;case t.template:return`template`;case t.ellipsis:return`...`;case t.backQuote:return"`";case t.dollarBraceL:return"${";case t.at:return`@`;case t.hash:return`#`;case t.eq:return`=`;case t.assign:return`_=`;case t.preIncDec:return`++/--`;case t.postIncDec:return`++/--`;case t.bang:return`!`;case t.tilde:return`~`;case t.pipeline:return`|>`;case t.nullishCoalescing:return`??`;case t.logicalOR:return`||`;case t.logicalAND:return`&&`;case t.bitwiseOR:return`|`;case t.bitwiseXOR:return`^`;case t.bitwiseAND:return`&`;case t.equality:return`==/!=`;case t.lessThan:return`<`;case t.greaterThan:return`>`;case t.relationalOrEqual:return`<=/>=`;case t.bitShiftL:return`<<`;case t.bitShiftR:return`>>/>>>`;case t.plus:return`+`;case t.minus:return`-`;case t.modulo:return`%`;case t.star:return`*`;case t.slash:return`/`;case t.exponent:return`**`;case t.jsxName:return`jsxName`;case t.jsxText:return`jsxText`;case t.jsxEmptyText:return`jsxEmptyText`;case t.jsxTagStart:return`jsxTagStart`;case t.jsxTagEnd:return`jsxTagEnd`;case t.typeParameterStart:return`typeParameterStart`;case t.nonNullAssertion:return`nonNullAssertion`;case t._break:return`break`;case t._case:return`case`;case t._catch:return`catch`;case t._continue:return`continue`;case t._debugger:return`debugger`;case t._default:return`default`;case t._do:return`do`;case t._else:return`else`;case t._finally:return`finally`;case t._for:return`for`;case t._function:return`function`;case t._if:return`if`;case t._return:return`return`;case t._switch:return`switch`;case t._throw:return`throw`;case t._try:return`try`;case t._var:return`var`;case t._let:return`let`;case t._const:return`const`;case t._while:return`while`;case t._with:return`with`;case t._new:return`new`;case t._this:return`this`;case t._super:return`super`;case t._class:return`class`;case t._extends:return`extends`;case t._export:return`export`;case t._import:return`import`;case t._yield:return`yield`;case t._null:return`null`;case t._true:return`true`;case t._false:return`false`;case t._in:return`in`;case t._instanceof:return`instanceof`;case t._typeof:return`typeof`;case t._void:return`void`;case t._delete:return`delete`;case t._async:return`async`;case t._get:return`get`;case t._set:return`set`;case t._declare:return`declare`;case t._readonly:return`readonly`;case t._abstract:return`abstract`;case t._static:return`static`;case t._public:return`public`;case t._private:return`private`;case t._protected:return`protected`;case t._override:return`override`;case t._as:return`as`;case t._enum:return`enum`;case t._type:return`type`;case t._implements:return`implements`;default:return``}}e.formatTokenType=n})),gd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=hd(),n=K();e.Scope=class{constructor(e,t,n){this.startTokenIndex=e,this.endTokenIndex=t,this.isFunctionScope=n}};var r=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f){this.potentialArrowAt=e,this.noAnonFunctionType=t,this.inDisallowConditionalTypesContext=n,this.tokensLength=r,this.scopesLength=i,this.pos=a,this.type=o,this.contextualKeyword=s,this.start=c,this.end=l,this.isType=u,this.scopeDepth=d,this.error=f}};e.StateSnapshot=r,e.default=class e{constructor(){e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),e.prototype.__init6.call(this),e.prototype.__init7.call(this),e.prototype.__init8.call(this),e.prototype.__init9.call(this),e.prototype.__init10.call(this),e.prototype.__init11.call(this),e.prototype.__init12.call(this),e.prototype.__init13.call(this)}__init(){this.potentialArrowAt=-1}__init2(){this.noAnonFunctionType=!1}__init3(){this.inDisallowConditionalTypesContext=!1}__init4(){this.tokens=[]}__init5(){this.scopes=[]}__init6(){this.pos=0}__init7(){this.type=n.TokenType.eof}__init8(){this.contextualKeyword=t.ContextualKeyword.NONE}__init9(){this.start=0}__init10(){this.end=0}__init11(){this.isType=!1}__init12(){this.scopeDepth=0}__init13(){this.error=null}snapshot(){return new r(this.potentialArrowAt,this.noAnonFunctionType,this.inDisallowConditionalTypesContext,this.tokens.length,this.scopes.length,this.pos,this.type,this.contextualKeyword,this.start,this.end,this.isType,this.scopeDepth,this.error)}restoreFromSnapshot(e){this.potentialArrowAt=e.potentialArrowAt,this.noAnonFunctionType=e.noAnonFunctionType,this.inDisallowConditionalTypesContext=e.inDisallowConditionalTypesContext,this.tokens.length=e.tokensLength,this.scopes.length=e.scopesLength,this.pos=e.pos,this.type=e.type,this.contextualKeyword=e.contextualKeyword,this.start=e.start,this.end=e.end,this.isType=e.isType,this.scopeDepth=e.scopeDepth,this.error=e.error}}})),_d=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t;(function(e){e[e.backSpace=8]=`backSpace`,e[e.lineFeed=10]=`lineFeed`,e[e.tab=9]=`tab`,e[e.carriageReturn=13]=`carriageReturn`,e[e.shiftOut=14]=`shiftOut`,e[e.space=32]=`space`,e[e.exclamationMark=33]=`exclamationMark`,e[e.quotationMark=34]=`quotationMark`,e[e.numberSign=35]=`numberSign`,e[e.dollarSign=36]=`dollarSign`,e[e.percentSign=37]=`percentSign`,e[e.ampersand=38]=`ampersand`,e[e.apostrophe=39]=`apostrophe`,e[e.leftParenthesis=40]=`leftParenthesis`,e[e.rightParenthesis=41]=`rightParenthesis`,e[e.asterisk=42]=`asterisk`,e[e.plusSign=43]=`plusSign`,e[e.comma=44]=`comma`,e[e.dash=45]=`dash`,e[e.dot=46]=`dot`,e[e.slash=47]=`slash`,e[e.digit0=48]=`digit0`,e[e.digit1=49]=`digit1`,e[e.digit2=50]=`digit2`,e[e.digit3=51]=`digit3`,e[e.digit4=52]=`digit4`,e[e.digit5=53]=`digit5`,e[e.digit6=54]=`digit6`,e[e.digit7=55]=`digit7`,e[e.digit8=56]=`digit8`,e[e.digit9=57]=`digit9`,e[e.colon=58]=`colon`,e[e.semicolon=59]=`semicolon`,e[e.lessThan=60]=`lessThan`,e[e.equalsTo=61]=`equalsTo`,e[e.greaterThan=62]=`greaterThan`,e[e.questionMark=63]=`questionMark`,e[e.atSign=64]=`atSign`,e[e.uppercaseA=65]=`uppercaseA`,e[e.uppercaseB=66]=`uppercaseB`,e[e.uppercaseC=67]=`uppercaseC`,e[e.uppercaseD=68]=`uppercaseD`,e[e.uppercaseE=69]=`uppercaseE`,e[e.uppercaseF=70]=`uppercaseF`,e[e.uppercaseG=71]=`uppercaseG`,e[e.uppercaseH=72]=`uppercaseH`,e[e.uppercaseI=73]=`uppercaseI`,e[e.uppercaseJ=74]=`uppercaseJ`,e[e.uppercaseK=75]=`uppercaseK`,e[e.uppercaseL=76]=`uppercaseL`,e[e.uppercaseM=77]=`uppercaseM`,e[e.uppercaseN=78]=`uppercaseN`,e[e.uppercaseO=79]=`uppercaseO`,e[e.uppercaseP=80]=`uppercaseP`,e[e.uppercaseQ=81]=`uppercaseQ`,e[e.uppercaseR=82]=`uppercaseR`,e[e.uppercaseS=83]=`uppercaseS`,e[e.uppercaseT=84]=`uppercaseT`,e[e.uppercaseU=85]=`uppercaseU`,e[e.uppercaseV=86]=`uppercaseV`,e[e.uppercaseW=87]=`uppercaseW`,e[e.uppercaseX=88]=`uppercaseX`,e[e.uppercaseY=89]=`uppercaseY`,e[e.uppercaseZ=90]=`uppercaseZ`,e[e.leftSquareBracket=91]=`leftSquareBracket`,e[e.backslash=92]=`backslash`,e[e.rightSquareBracket=93]=`rightSquareBracket`,e[e.caret=94]=`caret`,e[e.underscore=95]=`underscore`,e[e.graveAccent=96]=`graveAccent`,e[e.lowercaseA=97]=`lowercaseA`,e[e.lowercaseB=98]=`lowercaseB`,e[e.lowercaseC=99]=`lowercaseC`,e[e.lowercaseD=100]=`lowercaseD`,e[e.lowercaseE=101]=`lowercaseE`,e[e.lowercaseF=102]=`lowercaseF`,e[e.lowercaseG=103]=`lowercaseG`,e[e.lowercaseH=104]=`lowercaseH`,e[e.lowercaseI=105]=`lowercaseI`,e[e.lowercaseJ=106]=`lowercaseJ`,e[e.lowercaseK=107]=`lowercaseK`,e[e.lowercaseL=108]=`lowercaseL`,e[e.lowercaseM=109]=`lowercaseM`,e[e.lowercaseN=110]=`lowercaseN`,e[e.lowercaseO=111]=`lowercaseO`,e[e.lowercaseP=112]=`lowercaseP`,e[e.lowercaseQ=113]=`lowercaseQ`,e[e.lowercaseR=114]=`lowercaseR`,e[e.lowercaseS=115]=`lowercaseS`,e[e.lowercaseT=116]=`lowercaseT`,e[e.lowercaseU=117]=`lowercaseU`,e[e.lowercaseV=118]=`lowercaseV`,e[e.lowercaseW=119]=`lowercaseW`,e[e.lowercaseX=120]=`lowercaseX`,e[e.lowercaseY=121]=`lowercaseY`,e[e.lowercaseZ=122]=`lowercaseZ`,e[e.leftCurlyBrace=123]=`leftCurlyBrace`,e[e.verticalBar=124]=`verticalBar`,e[e.rightCurlyBrace=125]=`rightCurlyBrace`,e[e.tilde=126]=`tilde`,e[e.nonBreakingSpace=160]=`nonBreakingSpace`,e[e.oghamSpaceMark=5760]=`oghamSpaceMark`,e[e.lineSeparator=8232]=`lineSeparator`,e[e.paragraphSeparator=8233]=`paragraphSeparator`})(t||(e.charCodes=t={}));function n(e){return e>=t.digit0&&e<=t.digit9||e>=t.lowercaseA&&e<=t.lowercaseF||e>=t.uppercaseA&&e<=t.uppercaseF}e.isDigit=n})),vd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=t(gd()),r=_d();e.isJSXEnabled,e.isTypeScriptEnabled,e.isFlowEnabled,e.state,e.input,e.nextContextId;function i(){return e.nextContextId++}e.getNextContextId=i;function a(e){if(`pos`in e){let t=s(e.pos);e.message+=` (${t.line}:${t.column})`,e.loc=t}return e}e.augmentError=a;var o=class{constructor(e,t){this.line=e,this.column=t}};e.Loc=o;function s(t){let n=1,i=1;for(let a=0;a<t;a++)e.input.charCodeAt(a)===r.charCodes.lineFeed?(n++,i=1):i++;return new o(n,i)}e.locationForIndex=s;function c(t,r,i,a){e.input=t,e.state=new n.default,e.nextContextId=1,e.isJSXEnabled=r,e.isTypeScriptEnabled=i,e.isFlowEnabled=a}e.initParser=c})),yd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=wd(),n=K(),r=_d(),i=vd();function a(e){return i.state.contextualKeyword===e}e.isContextual=a;function o(e){let r=t.lookaheadTypeAndKeyword.call(void 0);return r.type===n.TokenType.name&&r.contextualKeyword===e}e.isLookaheadContextual=o;function s(e){return i.state.contextualKeyword===e&&t.eat.call(void 0,n.TokenType.name)}e.eatContextual=s;function c(e){s(e)||h()}e.expectContextual=c;function l(){return t.match.call(void 0,n.TokenType.eof)||t.match.call(void 0,n.TokenType.braceR)||u()}e.canInsertSemicolon=l;function u(){let e=i.state.tokens[i.state.tokens.length-1],t=e?e.end:0;for(let e=t;e<i.state.start;e++){let t=i.input.charCodeAt(e);if(t===r.charCodes.lineFeed||t===r.charCodes.carriageReturn||t===8232||t===8233)return!0}return!1}e.hasPrecedingLineBreak=u;function d(){let e=t.nextTokenStart.call(void 0);for(let t=i.state.end;t<e;t++){let e=i.input.charCodeAt(t);if(e===r.charCodes.lineFeed||e===r.charCodes.carriageReturn||e===8232||e===8233)return!0}return!1}e.hasFollowingLineBreak=d;function f(){return t.eat.call(void 0,n.TokenType.semi)||l()}e.isLineTerminator=f;function p(){f()||h(`Unexpected token, expected ";"`)}e.semicolon=p;function m(e){t.eat.call(void 0,e)||h(`Unexpected token, expected "${n.formatTokenType.call(void 0,e)}"`)}e.expect=m;function h(e=`Unexpected token`,r=i.state.start){if(i.state.error)return;let a=SyntaxError(e);a.pos=r,i.state.error=a,i.state.pos=i.input.length,t.finishToken.call(void 0,n.TokenType.eof)}e.unexpected=h})),bd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=_d();e.WHITESPACE_CHARS=[9,11,12,t.charCodes.space,t.charCodes.nonBreakingSpace,t.charCodes.oghamSpaceMark,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279],e.skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,e.IS_WHITESPACE=/* @__PURE__ */ new Uint8Array(65536);for(let t of e.WHITESPACE_CHARS)e.IS_WHITESPACE[t]=1})),xd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=_d(),n=bd();function r(e){if(e<48)return e===36;if(e<58)return!0;if(e<65)return!1;if(e<91)return!0;if(e<97)return e===95;if(e<123)return!0;if(e<128)return!1;throw Error(`Should not be called with non-ASCII char code.`)}e.IS_IDENTIFIER_CHAR=/* @__PURE__ */ new Uint8Array(65536);for(let t=0;t<128;t++)e.IS_IDENTIFIER_CHAR[t]=+!!r(t);for(let t=128;t<65536;t++)e.IS_IDENTIFIER_CHAR[t]=1;for(let t of n.WHITESPACE_CHARS)e.IS_IDENTIFIER_CHAR[t]=0;e.IS_IDENTIFIER_CHAR[8232]=0,e.IS_IDENTIFIER_CHAR[8233]=0,e.IS_IDENTIFIER_START=e.IS_IDENTIFIER_CHAR.slice();for(let n=t.charCodes.digit0;n<=t.charCodes.digit9;n++)e.IS_IDENTIFIER_START[n]=0})),Sd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=hd(),n=K();e.READ_WORD_TREE=new Int32Array([-1,27,783,918,1755,2376,2862,3483,-1,3699,-1,4617,4752,4833,5130,5508,5940,-1,6480,6939,7749,8181,8451,8613,-1,8829,-1,-1,-1,54,243,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,432,-1,-1,-1,675,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,81,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,108,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,135,-1,-1,-1,-1,-1,-1,-1,-1,-1,162,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,189,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,216,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._abstract<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,270,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,297,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,324,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,351,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,378,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,405,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._accessor<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._as<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,459,-1,-1,-1,-1,-1,594,-1,-1,-1,-1,-1,-1,486,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,513,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,540,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._assert<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,567,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._asserts<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,621,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,648,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._async<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,702,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,729,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,756,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._await<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,810,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,837,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,864,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,891,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._break<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,945,-1,-1,-1,-1,-1,-1,1107,-1,-1,-1,1242,-1,-1,1350,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,972,1026,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,999,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._case<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1053,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1080,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._catch<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1134,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1161,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1188,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1215,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._checks<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1269,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1296,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1323,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._class<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1377,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1404,1620,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1431,-1,-1,-1,-1,-1,-1,(n.TokenType._const<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1458,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1485,-1,-1,-1,-1,-1,-1,-1,-1,1512,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1539,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1566,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1593,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._constructor<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1647,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1674,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1701,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1728,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._continue<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1782,-1,-1,-1,-1,-1,-1,-1,-1,-1,2349,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1809,1971,-1,-1,2106,-1,-1,-1,-1,-1,2241,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1836,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1863,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1890,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1917,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1944,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._debugger<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1998,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2025,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2052,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2079,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._declare<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2133,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2160,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2187,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2214,-1,-1,-1,-1,-1,-1,(n.TokenType._default<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2268,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2295,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2322,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._delete<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._do<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2403,-1,2484,-1,-1,-1,-1,-1,-1,-1,-1,-1,2565,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2430,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2457,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._else<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2511,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2538,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._enum<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2592,-1,-1,-1,2727,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2619,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2646,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2673,-1,-1,-1,-1,-1,-1,(n.TokenType._export<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2700,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._exports<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2754,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2781,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2808,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2835,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._extends<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2889,-1,-1,-1,-1,-1,-1,-1,2997,-1,-1,-1,-1,-1,3159,-1,-1,3213,-1,-1,3294,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2916,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2943,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2970,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._false<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3024,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3051,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3078,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3105,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3132,-1,(n.TokenType._finally<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3186,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._for<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3240,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3267,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._from<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3321,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3348,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3375,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3402,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3429,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3456,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._function<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3510,-1,-1,-1,-1,-1,-1,3564,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3537,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._get<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3591,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3618,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3645,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3672,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._global<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3726,-1,-1,-1,-1,-1,-1,3753,4077,-1,-1,-1,-1,4590,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._if<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3780,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3807,-1,-1,3996,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3834,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3861,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3888,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3915,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3942,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3969,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._implements<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4023,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4050,-1,-1,-1,-1,-1,-1,(n.TokenType._import<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._in<<1)+1,-1,-1,-1,-1,-1,4104,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4185,4401,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4131,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4158,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._infer<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4212,-1,-1,-1,-1,-1,-1,-1,4239,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4266,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4293,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4320,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4347,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4374,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._instanceof<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4428,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4455,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4482,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4509,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4536,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4563,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._interface<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._is<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4644,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4671,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4698,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4725,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._keyof<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4779,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4806,-1,-1,-1,-1,-1,-1,(n.TokenType._let<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4860,-1,-1,-1,-1,-1,4995,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4887,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4914,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4941,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4968,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._mixins<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5022,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5049,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5076,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5103,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._module<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5157,-1,-1,-1,5373,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5427,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5184,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5211,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5238,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5265,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5292,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5319,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5346,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._namespace<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5400,-1,-1,-1,(n.TokenType._new<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5454,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5481,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._null<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5535,-1,-1,-1,-1,-1,-1,-1,-1,-1,5562,-1,-1,-1,-1,5697,5751,-1,-1,-1,-1,t.ContextualKeyword._of<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5589,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5616,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5643,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5670,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._opaque<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5724,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._out<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5778,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5805,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5832,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5859,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5886,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5913,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._override<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5967,-1,-1,6345,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5994,-1,-1,-1,-1,-1,6129,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6021,-1,-1,-1,-1,-1,6048,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6075,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6102,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._private<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6156,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6183,-1,-1,-1,-1,-1,-1,-1,-1,-1,6318,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6210,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6237,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6264,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6291,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._protected<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._proto<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6372,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6399,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6426,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6453,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._public<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6507,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6534,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6696,-1,-1,6831,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6561,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6588,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6615,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6642,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6669,-1,t.ContextualKeyword._readonly<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6723,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6750,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6777,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6804,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._require<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6858,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6885,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6912,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._return<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6966,-1,-1,-1,7182,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7236,7371,-1,7479,-1,7614,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6993,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7020,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7047,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7074,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7101,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7128,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7155,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._satisfies<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7209,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._set<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7263,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7290,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7317,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7344,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._static<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7398,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7425,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7452,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._super<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7506,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7533,-1,-1,-1,-1,-1,-1,-1,-1,-1,7560,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7587,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._switch<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7641,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7668,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7695,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7722,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._symbol<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7776,-1,-1,-1,-1,-1,-1,-1,-1,-1,7938,-1,-1,-1,-1,-1,-1,8046,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7803,-1,-1,-1,-1,-1,-1,-1,-1,7857,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7830,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._this<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7884,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7911,-1,-1,-1,(n.TokenType._throw<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7965,-1,-1,-1,8019,-1,-1,-1,-1,-1,-1,7992,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._true<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._try<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8073,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8100,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._type<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8127,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8154,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._typeof<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8208,-1,-1,-1,-1,8343,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8235,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8262,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8289,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8316,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._unique<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8370,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8397,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8424,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,t.ContextualKeyword._using<<1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8478,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8532,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8505,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._var<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8559,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8586,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._void<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8640,8748,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8667,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8694,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8721,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._while<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8775,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8802,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._with<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8856,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8883,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8910,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8937,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,(n.TokenType._yield<<1)+1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1])})),Cd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=vd(),n=_d(),r=xd(),i=wd(),a=Sd(),o=K();function s(){let e=0,s=0,c=t.state.pos;for(;c<t.input.length&&(s=t.input.charCodeAt(c),!(s<n.charCodes.lowercaseA||s>n.charCodes.lowercaseZ));){let t=a.READ_WORD_TREE[e+(s-n.charCodes.lowercaseA)+1];if(t===-1)break;e=t,c++}let l=a.READ_WORD_TREE[e];if(l>-1&&!r.IS_IDENTIFIER_CHAR[s])t.state.pos=c,l&1?i.finishToken.call(void 0,l>>>1):i.finishToken.call(void 0,o.TokenType.name,l>>>1);else{for(;c<t.input.length;){let e=t.input.charCodeAt(c);if(r.IS_IDENTIFIER_CHAR[e])c++;else if(e===n.charCodes.backslash){if(c+=2,t.input.charCodeAt(c)===n.charCodes.leftCurlyBrace){for(;c<t.input.length&&t.input.charCodeAt(c)!==n.charCodes.rightCurlyBrace;)c++;c++}}else if(e===n.charCodes.atSign&&t.input.charCodeAt(c+1)===n.charCodes.atSign)c+=2;else break}t.state.pos=c,i.finishToken.call(void 0,o.TokenType.name)}}e.default=s})),wd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=vd(),r=yd(),i=_d(),a=xd(),o=bd(),s=hd(),c=t(Cd()),l=K(),u;(function(e){e[e.Access=0]=`Access`,e[e.ExportAccess=1]=`ExportAccess`,e[e.TopLevelDeclaration=2]=`TopLevelDeclaration`,e[e.FunctionScopedDeclaration=3]=`FunctionScopedDeclaration`,e[e.BlockScopedDeclaration=4]=`BlockScopedDeclaration`,e[e.ObjectShorthandTopLevelDeclaration=5]=`ObjectShorthandTopLevelDeclaration`,e[e.ObjectShorthandFunctionScopedDeclaration=6]=`ObjectShorthandFunctionScopedDeclaration`,e[e.ObjectShorthandBlockScopedDeclaration=7]=`ObjectShorthandBlockScopedDeclaration`,e[e.ObjectShorthand=8]=`ObjectShorthand`,e[e.ImportDeclaration=9]=`ImportDeclaration`,e[e.ObjectKey=10]=`ObjectKey`,e[e.ImportAccess=11]=`ImportAccess`})(u||(e.IdentifierRole=u={}));var d;(function(e){e[e.NoChildren=0]=`NoChildren`,e[e.OneChild=1]=`OneChild`,e[e.StaticChildren=2]=`StaticChildren`,e[e.KeyAfterPropSpread=3]=`KeyAfterPropSpread`})(d||(e.JSXRole=d={}));function f(e){let t=e.identifierRole;return t===u.TopLevelDeclaration||t===u.FunctionScopedDeclaration||t===u.BlockScopedDeclaration||t===u.ObjectShorthandTopLevelDeclaration||t===u.ObjectShorthandFunctionScopedDeclaration||t===u.ObjectShorthandBlockScopedDeclaration}e.isDeclaration=f;function p(e){let t=e.identifierRole;return t===u.FunctionScopedDeclaration||t===u.BlockScopedDeclaration||t===u.ObjectShorthandFunctionScopedDeclaration||t===u.ObjectShorthandBlockScopedDeclaration}e.isNonTopLevelDeclaration=p;function m(e){let t=e.identifierRole;return t===u.TopLevelDeclaration||t===u.ObjectShorthandTopLevelDeclaration||t===u.ImportDeclaration}e.isTopLevelDeclaration=m;function h(e){let t=e.identifierRole;return t===u.TopLevelDeclaration||t===u.BlockScopedDeclaration||t===u.ObjectShorthandTopLevelDeclaration||t===u.ObjectShorthandBlockScopedDeclaration}e.isBlockScopedDeclaration=h;function g(e){let t=e.identifierRole;return t===u.FunctionScopedDeclaration||t===u.ObjectShorthandFunctionScopedDeclaration}e.isFunctionScopedDeclaration=g;function _(e){return e.identifierRole===u.ObjectShorthandTopLevelDeclaration||e.identifierRole===u.ObjectShorthandBlockScopedDeclaration||e.identifierRole===u.ObjectShorthandFunctionScopedDeclaration}e.isObjectShorthandDeclaration=_;var v=class{constructor(){this.type=n.state.type,this.contextualKeyword=n.state.contextualKeyword,this.start=n.state.start,this.end=n.state.end,this.scopeDepth=n.state.scopeDepth,this.isType=n.state.isType,this.identifierRole=null,this.jsxRole=null,this.shadowsGlobal=!1,this.isAsyncOperation=!1,this.contextId=null,this.rhsEndIndex=null,this.isExpression=!1,this.numNullishCoalesceStarts=0,this.numNullishCoalesceEnds=0,this.isOptionalChainStart=!1,this.isOptionalChainEnd=!1,this.subscriptStartIndex=null,this.nullishStartIndex=null}};e.Token=v;function y(){n.state.tokens.push(new v),M()}e.next=y;function b(){n.state.tokens.push(new v),n.state.start=n.state.pos,he()}e.nextTemplateToken=b;function x(){n.state.type===l.TokenType.assign&&--n.state.pos,ue()}e.retokenizeSlashAsRegex=x;function S(e){for(let t=n.state.tokens.length-e;t<n.state.tokens.length;t++)n.state.tokens[t].isType=!0;let t=n.state.isType;return n.state.isType=!0,t}e.pushTypeContext=S;function C(e){n.state.isType=e}e.popTypeContext=C;function w(e){return E(e)?(y(),!0):!1}e.eat=w;function T(e){let t=n.state.isType;n.state.isType=!0,w(e),n.state.isType=t}e.eatTypeToken=T;function E(e){return n.state.type===e}e.match=E;function D(){let e=n.state.snapshot();y();let t=n.state.type;return n.state.restoreFromSnapshot(e),t}e.lookaheadType=D;var O=class{constructor(e,t){this.type=e,this.contextualKeyword=t}};e.TypeAndKeyword=O;function k(){let e=n.state.snapshot();y();let t=n.state.type,r=n.state.contextualKeyword;return n.state.restoreFromSnapshot(e),new O(t,r)}e.lookaheadTypeAndKeyword=k;function A(){return j(n.state.pos)}e.nextTokenStart=A;function j(e){return o.skipWhiteSpace.lastIndex=e,e+o.skipWhiteSpace.exec(n.input)[0].length}e.nextTokenStartSince=j;function ee(){return n.input.charCodeAt(A())}e.lookaheadCharCode=ee;function M(){if(I(),n.state.start=n.state.pos,n.state.pos>=n.input.length){let e=n.state.tokens;e.length>=2&&e[e.length-1].start>=n.input.length&&e[e.length-2].start>=n.input.length&&r.unexpected.call(void 0,`Unexpectedly reached the end of input.`),L(l.TokenType.eof)}else N(n.input.charCodeAt(n.state.pos))}e.nextToken=M;function N(e){a.IS_IDENTIFIER_START[e]||e===i.charCodes.backslash||e===i.charCodes.atSign&&n.input.charCodeAt(n.state.pos+1)===i.charCodes.atSign?c.default.call(void 0):le(e)}function P(){for(;n.input.charCodeAt(n.state.pos)!==i.charCodes.asterisk||n.input.charCodeAt(n.state.pos+1)!==i.charCodes.slash;)if(n.state.pos++,n.state.pos>n.input.length){r.unexpected.call(void 0,`Unterminated comment`,n.state.pos-2);return}n.state.pos+=2}function F(e){let t=n.input.charCodeAt(n.state.pos+=e);if(n.state.pos<n.input.length)for(;t!==i.charCodes.lineFeed&&t!==i.charCodes.carriageReturn&&t!==i.charCodes.lineSeparator&&t!==i.charCodes.paragraphSeparator&&++n.state.pos<n.input.length;)t=n.input.charCodeAt(n.state.pos)}e.skipLineComment=F;function I(){for(;n.state.pos<n.input.length;){let e=n.input.charCodeAt(n.state.pos);switch(e){case i.charCodes.carriageReturn:n.input.charCodeAt(n.state.pos+1)===i.charCodes.lineFeed&&++n.state.pos;case i.charCodes.lineFeed:case i.charCodes.lineSeparator:case i.charCodes.paragraphSeparator:++n.state.pos;break;case i.charCodes.slash:switch(n.input.charCodeAt(n.state.pos+1)){case i.charCodes.asterisk:n.state.pos+=2,P();break;case i.charCodes.slash:F(2);break;default:return}break;default:if(o.IS_WHITESPACE[e])++n.state.pos;else return}}}e.skipSpace=I;function L(e,t=s.ContextualKeyword.NONE){n.state.end=n.state.pos,n.state.type=e,n.state.contextualKeyword=t}e.finishToken=L;function te(){let e=n.input.charCodeAt(n.state.pos+1);e>=i.charCodes.digit0&&e<=i.charCodes.digit9?pe(!0):e===i.charCodes.dot&&n.input.charCodeAt(n.state.pos+2)===i.charCodes.dot?(n.state.pos+=3,L(l.TokenType.ellipsis)):(++n.state.pos,L(l.TokenType.dot))}function R(){n.input.charCodeAt(n.state.pos+1)===i.charCodes.equalsTo?V(l.TokenType.assign,2):V(l.TokenType.slash,1)}function ne(e){let t=e===i.charCodes.asterisk?l.TokenType.star:l.TokenType.modulo,r=1,a=n.input.charCodeAt(n.state.pos+1);e===i.charCodes.asterisk&&a===i.charCodes.asterisk&&(r++,a=n.input.charCodeAt(n.state.pos+2),t=l.TokenType.exponent),a===i.charCodes.equalsTo&&n.input.charCodeAt(n.state.pos+2)!==i.charCodes.greaterThan&&(r++,t=l.TokenType.assign),V(t,r)}function z(e){let t=n.input.charCodeAt(n.state.pos+1);if(t===e)n.input.charCodeAt(n.state.pos+2)===i.charCodes.equalsTo?V(l.TokenType.assign,3):V(e===i.charCodes.verticalBar?l.TokenType.logicalOR:l.TokenType.logicalAND,2);else{if(e===i.charCodes.verticalBar){if(t===i.charCodes.greaterThan){V(l.TokenType.pipeline,2);return}if(t===i.charCodes.rightCurlyBrace&&n.isFlowEnabled){V(l.TokenType.braceBarR,2);return}}t===i.charCodes.equalsTo?V(l.TokenType.assign,2):V(e===i.charCodes.verticalBar?l.TokenType.bitwiseOR:l.TokenType.bitwiseAND,1)}}function B(){n.input.charCodeAt(n.state.pos+1)===i.charCodes.equalsTo?V(l.TokenType.assign,2):V(l.TokenType.bitwiseXOR,1)}function re(e){let t=n.input.charCodeAt(n.state.pos+1);t===e?V(l.TokenType.preIncDec,2):t===i.charCodes.equalsTo?V(l.TokenType.assign,2):e===i.charCodes.plusSign?V(l.TokenType.plus,1):V(l.TokenType.minus,1)}function ie(){let e=n.input.charCodeAt(n.state.pos+1);if(e===i.charCodes.lessThan){if(n.input.charCodeAt(n.state.pos+2)===i.charCodes.equalsTo){V(l.TokenType.assign,3);return}n.state.isType?V(l.TokenType.lessThan,1):V(l.TokenType.bitShiftL,2)}else e===i.charCodes.equalsTo?V(l.TokenType.relationalOrEqual,2):V(l.TokenType.lessThan,1)}function ae(){if(n.state.isType){V(l.TokenType.greaterThan,1);return}let e=n.input.charCodeAt(n.state.pos+1);if(e===i.charCodes.greaterThan){let e=n.input.charCodeAt(n.state.pos+2)===i.charCodes.greaterThan?3:2;if(n.input.charCodeAt(n.state.pos+e)===i.charCodes.equalsTo){V(l.TokenType.assign,e+1);return}V(l.TokenType.bitShiftR,e)}else e===i.charCodes.equalsTo?V(l.TokenType.relationalOrEqual,2):V(l.TokenType.greaterThan,1)}function oe(){n.state.type===l.TokenType.greaterThan&&(--n.state.pos,ae())}e.rescan_gt=oe;function se(e){let t=n.input.charCodeAt(n.state.pos+1);t===i.charCodes.equalsTo?V(l.TokenType.equality,n.input.charCodeAt(n.state.pos+2)===i.charCodes.equalsTo?3:2):e===i.charCodes.equalsTo&&t===i.charCodes.greaterThan?(n.state.pos+=2,L(l.TokenType.arrow)):V(e===i.charCodes.equalsTo?l.TokenType.eq:l.TokenType.bang,1)}function ce(){let e=n.input.charCodeAt(n.state.pos+1),t=n.input.charCodeAt(n.state.pos+2);e===i.charCodes.questionMark&&!(n.isFlowEnabled&&n.state.isType)?t===i.charCodes.equalsTo?V(l.TokenType.assign,3):V(l.TokenType.nullishCoalescing,2):e===i.charCodes.dot&&!(t>=i.charCodes.digit0&&t<=i.charCodes.digit9)?(n.state.pos+=2,L(l.TokenType.questionDot)):(++n.state.pos,L(l.TokenType.question))}function le(e){switch(e){case i.charCodes.numberSign:++n.state.pos,L(l.TokenType.hash);return;case i.charCodes.dot:te();return;case i.charCodes.leftParenthesis:++n.state.pos,L(l.TokenType.parenL);return;case i.charCodes.rightParenthesis:++n.state.pos,L(l.TokenType.parenR);return;case i.charCodes.semicolon:++n.state.pos,L(l.TokenType.semi);return;case i.charCodes.comma:++n.state.pos,L(l.TokenType.comma);return;case i.charCodes.leftSquareBracket:++n.state.pos,L(l.TokenType.bracketL);return;case i.charCodes.rightSquareBracket:++n.state.pos,L(l.TokenType.bracketR);return;case i.charCodes.leftCurlyBrace:n.isFlowEnabled&&n.input.charCodeAt(n.state.pos+1)===i.charCodes.verticalBar?V(l.TokenType.braceBarL,2):(++n.state.pos,L(l.TokenType.braceL));return;case i.charCodes.rightCurlyBrace:++n.state.pos,L(l.TokenType.braceR);return;case i.charCodes.colon:n.input.charCodeAt(n.state.pos+1)===i.charCodes.colon?V(l.TokenType.doubleColon,2):(++n.state.pos,L(l.TokenType.colon));return;case i.charCodes.questionMark:ce();return;case i.charCodes.atSign:++n.state.pos,L(l.TokenType.at);return;case i.charCodes.graveAccent:++n.state.pos,L(l.TokenType.backQuote);return;case i.charCodes.digit0:{let e=n.input.charCodeAt(n.state.pos+1);if(e===i.charCodes.lowercaseX||e===i.charCodes.uppercaseX||e===i.charCodes.lowercaseO||e===i.charCodes.uppercaseO||e===i.charCodes.lowercaseB||e===i.charCodes.uppercaseB){fe();return}}case i.charCodes.digit1:case i.charCodes.digit2:case i.charCodes.digit3:case i.charCodes.digit4:case i.charCodes.digit5:case i.charCodes.digit6:case i.charCodes.digit7:case i.charCodes.digit8:case i.charCodes.digit9:pe(!1);return;case i.charCodes.quotationMark:case i.charCodes.apostrophe:me(e);return;case i.charCodes.slash:R();return;case i.charCodes.percentSign:case i.charCodes.asterisk:ne(e);return;case i.charCodes.verticalBar:case i.charCodes.ampersand:z(e);return;case i.charCodes.caret:B();return;case i.charCodes.plusSign:case i.charCodes.dash:re(e);return;case i.charCodes.lessThan:ie();return;case i.charCodes.greaterThan:ae();return;case i.charCodes.equalsTo:case i.charCodes.exclamationMark:se(e);return;case i.charCodes.tilde:V(l.TokenType.tilde,1);return}r.unexpected.call(void 0,`Unexpected character '${String.fromCharCode(e)}'`,n.state.pos)}e.getTokenFromCode=le;function V(e,t){n.state.pos+=t,L(e)}function ue(){let e=n.state.pos,t=!1,a=!1;for(;;){if(n.state.pos>=n.input.length){r.unexpected.call(void 0,`Unterminated regular expression`,e);return}let o=n.input.charCodeAt(n.state.pos);if(t)t=!1;else{if(o===i.charCodes.leftSquareBracket)a=!0;else if(o===i.charCodes.rightSquareBracket&&a)a=!1;else if(o===i.charCodes.slash&&!a)break;t=o===i.charCodes.backslash}++n.state.pos}++n.state.pos,ge(),L(l.TokenType.regexp)}function de(){for(;;){let e=n.input.charCodeAt(n.state.pos);if(e>=i.charCodes.digit0&&e<=i.charCodes.digit9||e===i.charCodes.underscore)n.state.pos++;else break}}function fe(){for(n.state.pos+=2;;){let e=n.input.charCodeAt(n.state.pos);if(e>=i.charCodes.digit0&&e<=i.charCodes.digit9||e>=i.charCodes.lowercaseA&&e<=i.charCodes.lowercaseF||e>=i.charCodes.uppercaseA&&e<=i.charCodes.uppercaseF||e===i.charCodes.underscore)n.state.pos++;else break}n.input.charCodeAt(n.state.pos)===i.charCodes.lowercaseN?(++n.state.pos,L(l.TokenType.bigint)):L(l.TokenType.num)}function pe(e){let t=!1,r=!1;e||de();let a=n.input.charCodeAt(n.state.pos);a===i.charCodes.dot&&(++n.state.pos,de(),a=n.input.charCodeAt(n.state.pos)),(a===i.charCodes.uppercaseE||a===i.charCodes.lowercaseE)&&(a=n.input.charCodeAt(++n.state.pos),(a===i.charCodes.plusSign||a===i.charCodes.dash)&&++n.state.pos,de(),a=n.input.charCodeAt(n.state.pos)),a===i.charCodes.lowercaseN?(++n.state.pos,t=!0):a===i.charCodes.lowercaseM&&(++n.state.pos,r=!0),L(t?l.TokenType.bigint:r?l.TokenType.decimal:l.TokenType.num)}function me(e){for(n.state.pos++;;){if(n.state.pos>=n.input.length){r.unexpected.call(void 0,`Unterminated string constant`);return}let t=n.input.charCodeAt(n.state.pos);if(t===i.charCodes.backslash)n.state.pos++;else if(t===e)break;n.state.pos++}n.state.pos++,L(l.TokenType.string)}function he(){for(;;){if(n.state.pos>=n.input.length){r.unexpected.call(void 0,`Unterminated template`);return}let e=n.input.charCodeAt(n.state.pos);if(e===i.charCodes.graveAccent||e===i.charCodes.dollarSign&&n.input.charCodeAt(n.state.pos+1)===i.charCodes.leftCurlyBrace){if(n.state.pos===n.state.start&&E(l.TokenType.template)){if(e===i.charCodes.dollarSign){n.state.pos+=2,L(l.TokenType.dollarBraceL);return}++n.state.pos,L(l.TokenType.backQuote);return}L(l.TokenType.template);return}e===i.charCodes.backslash&&n.state.pos++,n.state.pos++}}function ge(){for(;n.state.pos<n.input.length;){let e=n.input.charCodeAt(n.state.pos);if(a.IS_IDENTIFIER_CHAR[e])n.state.pos++;else if(e===i.charCodes.backslash){if(n.state.pos+=2,n.input.charCodeAt(n.state.pos)===i.charCodes.leftCurlyBrace){for(;n.state.pos<n.input.length&&n.input.charCodeAt(n.state.pos)!==i.charCodes.rightCurlyBrace;)n.state.pos++;n.state.pos++}}else break}}e.skipWord=ge})),Td=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=K();function n(e,t=e.currentIndex()){let n=t+1;if(r(e,n)){let r=e.identifierNameAtIndex(t);return{isType:!1,leftName:r,rightName:r,endIndex:n}}if(n++,r(e,n))return{isType:!0,leftName:null,rightName:null,endIndex:n};if(n++,r(e,n))return{isType:!1,leftName:e.identifierNameAtIndex(t),rightName:e.identifierNameAtIndex(t+2),endIndex:n};if(n++,r(e,n))return{isType:!0,leftName:null,rightName:null,endIndex:n};throw Error(`Unexpected import/export specifier at ${t}`)}e.default=n;function r(e,n){let r=e.tokens[n];return r.type===t.TokenType.braceR||r.type===t.TokenType.comma}})),Ed=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=/* @__PURE__ */ new Map([[`quot`,`"`],[`amp`,`&`],[`apos`,`'`],[`lt`,`<`],[`gt`,`>`],[`nbsp`,`\xA0`],[`iexcl`,`¡`],[`cent`,`¢`],[`pound`,`£`],[`curren`,`¤`],[`yen`,`¥`],[`brvbar`,`¦`],[`sect`,`§`],[`uml`,`¨`],[`copy`,`©`],[`ordf`,`ª`],[`laquo`,`«`],[`not`,`¬`],[`shy`,`­`],[`reg`,`®`],[`macr`,`¯`],[`deg`,`°`],[`plusmn`,`±`],[`sup2`,`²`],[`sup3`,`³`],[`acute`,`´`],[`micro`,`µ`],[`para`,`¶`],[`middot`,`·`],[`cedil`,`¸`],[`sup1`,`¹`],[`ordm`,`º`],[`raquo`,`»`],[`frac14`,`¼`],[`frac12`,`½`],[`frac34`,`¾`],[`iquest`,`¿`],[`Agrave`,`À`],[`Aacute`,`Á`],[`Acirc`,`Â`],[`Atilde`,`Ã`],[`Auml`,`Ä`],[`Aring`,`Å`],[`AElig`,`Æ`],[`Ccedil`,`Ç`],[`Egrave`,`È`],[`Eacute`,`É`],[`Ecirc`,`Ê`],[`Euml`,`Ë`],[`Igrave`,`Ì`],[`Iacute`,`Í`],[`Icirc`,`Î`],[`Iuml`,`Ï`],[`ETH`,`Ð`],[`Ntilde`,`Ñ`],[`Ograve`,`Ò`],[`Oacute`,`Ó`],[`Ocirc`,`Ô`],[`Otilde`,`Õ`],[`Ouml`,`Ö`],[`times`,`×`],[`Oslash`,`Ø`],[`Ugrave`,`Ù`],[`Uacute`,`Ú`],[`Ucirc`,`Û`],[`Uuml`,`Ü`],[`Yacute`,`Ý`],[`THORN`,`Þ`],[`szlig`,`ß`],[`agrave`,`à`],[`aacute`,`á`],[`acirc`,`â`],[`atilde`,`ã`],[`auml`,`ä`],[`aring`,`å`],[`aelig`,`æ`],[`ccedil`,`ç`],[`egrave`,`è`],[`eacute`,`é`],[`ecirc`,`ê`],[`euml`,`ë`],[`igrave`,`ì`],[`iacute`,`í`],[`icirc`,`î`],[`iuml`,`ï`],[`eth`,`ð`],[`ntilde`,`ñ`],[`ograve`,`ò`],[`oacute`,`ó`],[`ocirc`,`ô`],[`otilde`,`õ`],[`ouml`,`ö`],[`divide`,`÷`],[`oslash`,`ø`],[`ugrave`,`ù`],[`uacute`,`ú`],[`ucirc`,`û`],[`uuml`,`ü`],[`yacute`,`ý`],[`thorn`,`þ`],[`yuml`,`ÿ`],[`OElig`,`Œ`],[`oelig`,`œ`],[`Scaron`,`Š`],[`scaron`,`š`],[`Yuml`,`Ÿ`],[`fnof`,`ƒ`],[`circ`,`ˆ`],[`tilde`,`˜`],[`Alpha`,`Α`],[`Beta`,`Β`],[`Gamma`,`Γ`],[`Delta`,`Δ`],[`Epsilon`,`Ε`],[`Zeta`,`Ζ`],[`Eta`,`Η`],[`Theta`,`Θ`],[`Iota`,`Ι`],[`Kappa`,`Κ`],[`Lambda`,`Λ`],[`Mu`,`Μ`],[`Nu`,`Ν`],[`Xi`,`Ξ`],[`Omicron`,`Ο`],[`Pi`,`Π`],[`Rho`,`Ρ`],[`Sigma`,`Σ`],[`Tau`,`Τ`],[`Upsilon`,`Υ`],[`Phi`,`Φ`],[`Chi`,`Χ`],[`Psi`,`Ψ`],[`Omega`,`Ω`],[`alpha`,`α`],[`beta`,`β`],[`gamma`,`γ`],[`delta`,`δ`],[`epsilon`,`ε`],[`zeta`,`ζ`],[`eta`,`η`],[`theta`,`θ`],[`iota`,`ι`],[`kappa`,`κ`],[`lambda`,`λ`],[`mu`,`μ`],[`nu`,`ν`],[`xi`,`ξ`],[`omicron`,`ο`],[`pi`,`π`],[`rho`,`ρ`],[`sigmaf`,`ς`],[`sigma`,`σ`],[`tau`,`τ`],[`upsilon`,`υ`],[`phi`,`φ`],[`chi`,`χ`],[`psi`,`ψ`],[`omega`,`ω`],[`thetasym`,`ϑ`],[`upsih`,`ϒ`],[`piv`,`ϖ`],[`ensp`,` `],[`emsp`,` `],[`thinsp`,` `],[`zwnj`,`‌`],[`zwj`,`‍`],[`lrm`,`‎`],[`rlm`,`‏`],[`ndash`,`–`],[`mdash`,`—`],[`lsquo`,`‘`],[`rsquo`,`’`],[`sbquo`,`‚`],[`ldquo`,`“`],[`rdquo`,`”`],[`bdquo`,`„`],[`dagger`,`†`],[`Dagger`,`‡`],[`bull`,`•`],[`hellip`,`…`],[`permil`,`‰`],[`prime`,`′`],[`Prime`,`″`],[`lsaquo`,`‹`],[`rsaquo`,`›`],[`oline`,`‾`],[`frasl`,`⁄`],[`euro`,`€`],[`image`,`ℑ`],[`weierp`,`℘`],[`real`,`ℜ`],[`trade`,`™`],[`alefsym`,`ℵ`],[`larr`,`←`],[`uarr`,`↑`],[`rarr`,`→`],[`darr`,`↓`],[`harr`,`↔`],[`crarr`,`↵`],[`lArr`,`⇐`],[`uArr`,`⇑`],[`rArr`,`⇒`],[`dArr`,`⇓`],[`hArr`,`⇔`],[`forall`,`∀`],[`part`,`∂`],[`exist`,`∃`],[`empty`,`∅`],[`nabla`,`∇`],[`isin`,`∈`],[`notin`,`∉`],[`ni`,`∋`],[`prod`,`∏`],[`sum`,`∑`],[`minus`,`−`],[`lowast`,`∗`],[`radic`,`√`],[`prop`,`∝`],[`infin`,`∞`],[`ang`,`∠`],[`and`,`∧`],[`or`,`∨`],[`cap`,`∩`],[`cup`,`∪`],[`int`,`∫`],[`there4`,`∴`],[`sim`,`∼`],[`cong`,`≅`],[`asymp`,`≈`],[`ne`,`≠`],[`equiv`,`≡`],[`le`,`≤`],[`ge`,`≥`],[`sub`,`⊂`],[`sup`,`⊃`],[`nsub`,`⊄`],[`sube`,`⊆`],[`supe`,`⊇`],[`oplus`,`⊕`],[`otimes`,`⊗`],[`perp`,`⊥`],[`sdot`,`⋅`],[`lceil`,`⌈`],[`rceil`,`⌉`],[`lfloor`,`⌊`],[`rfloor`,`⌋`],[`lang`,`〈`],[`rang`,`〉`],[`loz`,`◊`],[`spades`,`♠`],[`clubs`,`♣`],[`hearts`,`♥`],[`diams`,`♦`]])})),Dd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let[t,r]=n(e.jsxPragma||`React.createElement`),[i,a]=n(e.jsxFragmentPragma||`React.Fragment`);return{base:t,suffix:r,fragmentBase:i,fragmentSuffix:a}}e.default=t;function n(e){let t=e.indexOf(`.`);return t===-1&&(t=e.length),[e.slice(0,t),e.slice(t)]}})),Od=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class{getPrefixCode(){return``}getHoistedCode(){return``}getSuffixCode(){return``}}})),kd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=t(Ed()),r=wd(),i=K(),a=_d(),o=t(Dd()),s=t(Od());e.default=class e extends s.default{__init(){this.lastLineNumber=1}__init2(){this.lastIndex=0}__init3(){this.filenameVarName=null}__init4(){this.esmAutomaticImportNameResolutions={}}__init5(){this.cjsAutomaticModuleNameResolutions={}}constructor(t,n,r,i,a){super(),this.rootTransformer=t,this.tokens=n,this.importProcessor=r,this.nameManager=i,this.options=a,e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this),this.jsxPragmaInfo=o.default.call(void 0,a),this.isAutomaticRuntime=a.jsxRuntime===`automatic`,this.jsxImportSource=a.jsxImportSource||`react`}process(){return this.tokens.matches1(i.TokenType.jsxTagStart)?(this.processJSXTag(),!0):!1}getPrefixCode(){let e=``;if(this.filenameVarName&&(e+=`const ${this.filenameVarName} = ${JSON.stringify(this.options.filePath||``)};`),this.isAutomaticRuntime){if(this.importProcessor)for(let[t,n]of Object.entries(this.cjsAutomaticModuleNameResolutions))e+=`var ${n} = require("${t}");`;else{let{createElement:t,...n}=this.esmAutomaticImportNameResolutions;t&&(e+=`import {createElement as ${t}} from "${this.jsxImportSource}";`);let r=Object.entries(n).map(([e,t])=>`${e} as ${t}`).join(`, `);if(r){let t=this.jsxImportSource+(this.options.production?`/jsx-runtime`:`/jsx-dev-runtime`);e+=`import {${r}} from "${t}";`}}}return e}processJSXTag(){let{jsxRole:e,start:t}=this.tokens.currentToken(),n=this.options.production?null:this.getElementLocationCode(t);this.isAutomaticRuntime&&e!==r.JSXRole.KeyAfterPropSpread?this.transformTagToJSXFunc(n,e):this.transformTagToCreateElement(n)}getElementLocationCode(e){return`lineNumber: ${this.getLineNumberForIndex(e)}`}getLineNumberForIndex(e){let t=this.tokens.code;for(;this.lastIndex<e&&this.lastIndex<t.length;)t[this.lastIndex]===`
117
- `&&this.lastLineNumber++,this.lastIndex++;return this.lastLineNumber}transformTagToJSXFunc(e,t){let n=t===r.JSXRole.StaticChildren;this.tokens.replaceToken(this.getJSXFuncInvocationCode(n));let a=null;if(this.tokens.matches1(i.TokenType.jsxTagEnd))this.tokens.replaceToken(`${this.getFragmentCode()}, {`),this.processAutomaticChildrenAndEndProps(t);else{if(this.processTagIntro(),this.tokens.appendCode(`, {`),a=this.processProps(!0),this.tokens.matches2(i.TokenType.slash,i.TokenType.jsxTagEnd))this.tokens.appendCode(`}`);else if(this.tokens.matches1(i.TokenType.jsxTagEnd))this.tokens.removeToken(),this.processAutomaticChildrenAndEndProps(t);else throw Error(`Expected either /> or > at the end of the tag.`);a&&this.tokens.appendCode(`, ${a}`)}for(this.options.production||(a===null&&this.tokens.appendCode(`, void 0`),this.tokens.appendCode(`, ${n}, ${this.getDevSource(e)}, this`)),this.tokens.removeInitialToken();!this.tokens.matches1(i.TokenType.jsxTagEnd);)this.tokens.removeToken();this.tokens.replaceToken(`)`)}transformTagToCreateElement(e){if(this.tokens.replaceToken(this.getCreateElementInvocationCode()),this.tokens.matches1(i.TokenType.jsxTagEnd))this.tokens.replaceToken(`${this.getFragmentCode()}, null`),this.processChildren(!0);else if(this.processTagIntro(),this.processPropsObjectWithDevInfo(e),!this.tokens.matches2(i.TokenType.slash,i.TokenType.jsxTagEnd)){if(this.tokens.matches1(i.TokenType.jsxTagEnd))this.tokens.removeToken(),this.processChildren(!0);else throw Error(`Expected either /> or > at the end of the tag.`)}for(this.tokens.removeInitialToken();!this.tokens.matches1(i.TokenType.jsxTagEnd);)this.tokens.removeToken();this.tokens.replaceToken(`)`)}getJSXFuncInvocationCode(e){return this.options.production?e?this.claimAutoImportedFuncInvocation(`jsxs`,`/jsx-runtime`):this.claimAutoImportedFuncInvocation(`jsx`,`/jsx-runtime`):this.claimAutoImportedFuncInvocation(`jsxDEV`,`/jsx-dev-runtime`)}getCreateElementInvocationCode(){if(this.isAutomaticRuntime)return this.claimAutoImportedFuncInvocation(`createElement`,``);{let{jsxPragmaInfo:e}=this;return`${this.importProcessor&&this.importProcessor.getIdentifierReplacement(e.base)||e.base}${e.suffix}(`}}getFragmentCode(){if(this.isAutomaticRuntime)return this.claimAutoImportedName(`Fragment`,this.options.production?`/jsx-runtime`:`/jsx-dev-runtime`);{let{jsxPragmaInfo:e}=this;return(this.importProcessor&&this.importProcessor.getIdentifierReplacement(e.fragmentBase)||e.fragmentBase)+e.fragmentSuffix}}claimAutoImportedFuncInvocation(e,t){let n=this.claimAutoImportedName(e,t);return this.importProcessor?`${n}.call(void 0, `:`${n}(`}claimAutoImportedName(e,t){if(this.importProcessor){let n=this.jsxImportSource+t;return this.cjsAutomaticModuleNameResolutions[n]||(this.cjsAutomaticModuleNameResolutions[n]=this.importProcessor.getFreeIdentifierForPath(n)),`${this.cjsAutomaticModuleNameResolutions[n]}.${e}`}return this.esmAutomaticImportNameResolutions[e]||(this.esmAutomaticImportNameResolutions[e]=this.nameManager.claimFreeName(`_${e}`)),this.esmAutomaticImportNameResolutions[e]}processTagIntro(){let e=this.tokens.currentIndex()+1;for(;this.tokens.tokens[e].isType||!this.tokens.matches2AtIndex(e-1,i.TokenType.jsxName,i.TokenType.jsxName)&&!this.tokens.matches2AtIndex(e-1,i.TokenType.greaterThan,i.TokenType.jsxName)&&!this.tokens.matches1AtIndex(e,i.TokenType.braceL)&&!this.tokens.matches1AtIndex(e,i.TokenType.jsxTagEnd)&&!this.tokens.matches2AtIndex(e,i.TokenType.slash,i.TokenType.jsxTagEnd);)e++;if(e===this.tokens.currentIndex()+1){let e=this.tokens.identifierName();c(e)&&this.tokens.replaceToken(`'${e}'`)}for(;this.tokens.currentIndex()<e;)this.rootTransformer.processToken()}processPropsObjectWithDevInfo(e){let t=this.options.production?``:`__self: this, __source: ${this.getDevSource(e)}`;!this.tokens.matches1(i.TokenType.jsxName)&&!this.tokens.matches1(i.TokenType.braceL)?t?this.tokens.appendCode(`, {${t}}`):this.tokens.appendCode(`, null`):(this.tokens.appendCode(`, {`),this.processProps(!1),t?this.tokens.appendCode(` ${t}}`):this.tokens.appendCode(`}`))}processProps(e){let t=null;for(;;){if(this.tokens.matches2(i.TokenType.jsxName,i.TokenType.eq)){let n=this.tokens.identifierName();if(e&&n===`key`){t!==null&&this.tokens.appendCode(t.replace(/[^\n]/g,``)),this.tokens.removeToken(),this.tokens.removeToken();let e=this.tokens.snapshot();this.processPropValue(),t=this.tokens.dangerouslyGetAndRemoveCodeSinceSnapshot(e);continue}this.processPropName(n),this.tokens.replaceToken(`: `),this.processPropValue()}else if(this.tokens.matches1(i.TokenType.jsxName)){let e=this.tokens.identifierName();this.processPropName(e),this.tokens.appendCode(`: true`)}else if(this.tokens.matches1(i.TokenType.braceL))this.tokens.replaceToken(``),this.rootTransformer.processBalancedCode(),this.tokens.replaceToken(``);else break;this.tokens.appendCode(`,`)}return t}processPropName(e){e.includes(`-`)?this.tokens.replaceToken(`'${e}'`):this.tokens.copyToken()}processPropValue(){this.tokens.matches1(i.TokenType.braceL)?(this.tokens.replaceToken(``),this.rootTransformer.processBalancedCode(),this.tokens.replaceToken(``)):this.tokens.matches1(i.TokenType.jsxTagStart)?this.processJSXTag():this.processStringPropValue()}processStringPropValue(){let e=this.tokens.currentToken(),t=this.tokens.code.slice(e.start+1,e.end-1),n=u(t),r=d(t);this.tokens.replaceToken(r+n)}processAutomaticChildrenAndEndProps(e){e===r.JSXRole.StaticChildren?(this.tokens.appendCode(` children: [`),this.processChildren(!1),this.tokens.appendCode(`]}`)):(e===r.JSXRole.OneChild&&this.tokens.appendCode(` children: `),this.processChildren(!1),this.tokens.appendCode(`}`))}processChildren(e){let t=e;for(;;){if(this.tokens.matches2(i.TokenType.jsxTagStart,i.TokenType.slash))return;let e=!1;if(this.tokens.matches1(i.TokenType.braceL))this.tokens.matches2(i.TokenType.braceL,i.TokenType.braceR)?(this.tokens.replaceToken(``),this.tokens.replaceToken(``)):(this.tokens.replaceToken(t?`, `:``),this.rootTransformer.processBalancedCode(),this.tokens.replaceToken(``),e=!0);else if(this.tokens.matches1(i.TokenType.jsxTagStart))this.tokens.appendCode(t?`, `:``),this.processJSXTag(),e=!0;else if(this.tokens.matches1(i.TokenType.jsxText)||this.tokens.matches1(i.TokenType.jsxEmptyText))e=this.processChildTextElement(t);else throw Error(`Unexpected token when processing JSX children.`);e&&(t=!0)}}processChildTextElement(e){let t=this.tokens.currentToken(),n=this.tokens.code.slice(t.start,t.end),r=u(n),i=l(n);return i===`""`?(this.tokens.replaceToken(r),!1):(this.tokens.replaceToken(`${e?`, `:``}${i}${r}`),!0)}getDevSource(e){return`{fileName: ${this.getFilenameVarName()}, ${e}}`}getFilenameVarName(){return this.filenameVarName||=this.nameManager.claimFreeName(`_jsxFileName`),this.filenameVarName}};function c(e){let t=e.charCodeAt(0);return t>=a.charCodes.lowercaseA&&t<=a.charCodes.lowercaseZ}e.startsWithLowerCase=c;function l(e){let t=``,n=``,r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o===` `||o===` `||o===`\r`)r||(n+=o);else if(o===`
118
- `)n=``,r=!0;else{if(i&&r&&(t+=` `),t+=n,n=``,o===`&`){let{entity:n,newI:r}=f(e,a+1);a=r-1,t+=n}else t+=o;i=!0,r=!1}}return r||(t+=n),JSON.stringify(t)}function u(e){let t=0,n=0;for(let r of e)r===`
119
- `?(t++,n=0):r===` `&&n++;return`
120
- `.repeat(t)+` `.repeat(n)}function d(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`
121
- `){if(/\s/.test(e[n+1]))for(t+=` `;n<e.length&&/\s/.test(e[n+1]);)n++;else t+=`
122
- `}else if(r===`&`){let{entity:r,newI:i}=f(e,n+1);t+=r,n=i-1}else t+=r}return JSON.stringify(t)}function f(e,t){let r=``,i=0,a,o=t;if(e[o]===`#`){let t=10;o++;let n;if(e[o]===`x`)for(t=16,o++,n=o;o<e.length&&m(e.charCodeAt(o));)o++;else for(n=o;o<e.length&&p(e.charCodeAt(o));)o++;if(e[o]===`;`){let r=e.slice(n,o);r&&(o++,a=String.fromCodePoint(parseInt(r,t)))}}else for(;o<e.length&&i++<10;){let t=e[o];if(o++,t===`;`){a=n.default.get(r);break}r+=t}return a?{entity:a,newI:o}:{entity:`&`,newI:t}}function p(e){return e>=a.charCodes.digit0&&e<=a.charCodes.digit9}function m(e){return e>=a.charCodes.digit0&&e<=a.charCodes.digit9||e>=a.charCodes.lowercaseA&&e<=a.charCodes.lowercaseF||e>=a.charCodes.uppercaseA&&e<=a.charCodes.uppercaseF}})),Ad=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=wd(),r=K(),i=kd(),a=t(Dd());function o(e,t){let o=a.default.call(void 0,t),s=/* @__PURE__ */ new Set;for(let t=0;t<e.tokens.length;t++){let a=e.tokens[t];if(a.type!==r.TokenType.name||a.isType||a.identifierRole!==n.IdentifierRole.Access&&a.identifierRole!==n.IdentifierRole.ObjectShorthand&&a.identifierRole!==n.IdentifierRole.ExportAccess||a.shadowsGlobal||s.add(e.identifierNameForToken(a)),a.type===r.TokenType.jsxTagStart&&s.add(o.base),a.type===r.TokenType.jsxTagStart&&t+1<e.tokens.length&&e.tokens[t+1].type===r.TokenType.jsxTagEnd&&(s.add(o.base),s.add(o.fragmentBase)),a.type===r.TokenType.jsxName&&a.identifierRole===n.IdentifierRole.Access){let n=e.identifierNameForToken(a);i.startsWithLowerCase.call(void 0,n)&&e.tokens[t+1].type!==r.TokenType.dot||s.add(e.identifierNameForToken(a))}}return s}e.getNonTypeIdentifiers=o})),jd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=wd(),r=hd(),i=K(),a=t(Td()),o=Ad();e.default=class e{__init(){this.nonTypeIdentifiers=/* @__PURE__ */ new Set}__init2(){this.importInfoByPath=/* @__PURE__ */ new Map}__init3(){this.importsToReplace=/* @__PURE__ */ new Map}__init4(){this.identifierReplacements=/* @__PURE__ */ new Map}__init5(){this.exportBindingsByLocalName=/* @__PURE__ */ new Map}constructor(t,n,r,i,a,o,s){this.nameManager=t,this.tokens=n,this.enableLegacyTypeScriptModuleInterop=r,this.options=i,this.isTypeScriptTransformEnabled=a,this.keepUnusedImports=o,this.helperManager=s,e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),e.prototype.__init4.call(this),e.prototype.__init5.call(this)}preprocessTokens(){for(let e=0;e<this.tokens.tokens.length;e++)this.tokens.matches1AtIndex(e,i.TokenType._import)&&!this.tokens.matches3AtIndex(e,i.TokenType._import,i.TokenType.name,i.TokenType.eq)&&this.preprocessImportAtIndex(e),this.tokens.matches1AtIndex(e,i.TokenType._export)&&!this.tokens.matches2AtIndex(e,i.TokenType._export,i.TokenType.eq)&&this.preprocessExportAtIndex(e);this.generateImportReplacements()}pruneTypeOnlyImports(){this.nonTypeIdentifiers=o.getNonTypeIdentifiers.call(void 0,this.tokens,this.options);for(let[e,t]of this.importInfoByPath.entries())t.hasBareImport||t.hasStarExport||t.exportStarNames.length>0||t.namedExports.length>0||[...t.defaultNames,...t.wildcardNames,...t.namedImports.map(({localName:e})=>e)].every(e=>this.shouldAutomaticallyElideImportedName(e))&&this.importsToReplace.set(e,``)}shouldAutomaticallyElideImportedName(e){return this.isTypeScriptTransformEnabled&&!this.keepUnusedImports&&!this.nonTypeIdentifiers.has(e)}generateImportReplacements(){for(let[e,t]of this.importInfoByPath.entries()){let{defaultNames:n,wildcardNames:r,namedImports:i,namedExports:a,exportStarNames:o,hasStarExport:s}=t;if(n.length===0&&r.length===0&&i.length===0&&a.length===0&&o.length===0&&!s){this.importsToReplace.set(e,`require('${e}');`);continue}let c=this.getFreeIdentifierForPath(e),l;l=this.enableLegacyTypeScriptModuleInterop?c:r.length>0?r[0]:this.getFreeIdentifierForPath(e);let u=`var ${c} = require('${e}');`;if(r.length>0)for(let e of r){let t=this.enableLegacyTypeScriptModuleInterop?c:`${this.helperManager.getHelperName(`interopRequireWildcard`)}(${c})`;u+=` var ${e} = ${t};`}else o.length>0&&l!==c?u+=` var ${l} = ${this.helperManager.getHelperName(`interopRequireWildcard`)}(${c});`:n.length>0&&l!==c&&(u+=` var ${l} = ${this.helperManager.getHelperName(`interopRequireDefault`)}(${c});`);for(let{importedName:e,localName:t}of a)u+=` ${this.helperManager.getHelperName(`createNamedExportFrom`)}(${c}, '${t}', '${e}');`;for(let e of o)u+=` exports.${e} = ${l};`;s&&(u+=` ${this.helperManager.getHelperName(`createStarExport`)}(${c});`),this.importsToReplace.set(e,u);for(let e of n)this.identifierReplacements.set(e,`${l}.default`);for(let{importedName:e,localName:t}of i)this.identifierReplacements.set(t,`${c}.${e}`)}}getFreeIdentifierForPath(e){let t=e.split(`/`),n=t[t.length-1].replace(/\W/g,``);return this.nameManager.claimFreeName(`_${n}`)}preprocessImportAtIndex(e){let t=[],n=[],a=[];if(e++,(this.tokens.matchesContextualAtIndex(e,r.ContextualKeyword._type)||this.tokens.matches1AtIndex(e,i.TokenType._typeof))&&!this.tokens.matches1AtIndex(e+1,i.TokenType.comma)&&!this.tokens.matchesContextualAtIndex(e+1,r.ContextualKeyword._from)||this.tokens.matches1AtIndex(e,i.TokenType.parenL))return;if(this.tokens.matches1AtIndex(e,i.TokenType.name)&&(t.push(this.tokens.identifierNameAtIndex(e)),e++,this.tokens.matches1AtIndex(e,i.TokenType.comma)&&e++),this.tokens.matches1AtIndex(e,i.TokenType.star)&&(e+=2,n.push(this.tokens.identifierNameAtIndex(e)),e++),this.tokens.matches1AtIndex(e,i.TokenType.braceL)){let n=this.getNamedImports(e+1);e=n.newIndex;for(let e of n.namedImports)e.importedName==="default"?t.push(e.localName):a.push(e)}if(this.tokens.matchesContextualAtIndex(e,r.ContextualKeyword._from)&&e++,!this.tokens.matches1AtIndex(e,i.TokenType.string))throw Error(`Expected string token at the end of import statement.`);let o=this.tokens.stringValueAtIndex(e),s=this.getImportInfo(o);s.defaultNames.push(...t),s.wildcardNames.push(...n),s.namedImports.push(...a),t.length===0&&n.length===0&&a.length===0&&(s.hasBareImport=!0)}preprocessExportAtIndex(e){if(this.tokens.matches2AtIndex(e,i.TokenType._export,i.TokenType._var)||this.tokens.matches2AtIndex(e,i.TokenType._export,i.TokenType._let)||this.tokens.matches2AtIndex(e,i.TokenType._export,i.TokenType._const))this.preprocessVarExportAtIndex(e);else if(this.tokens.matches2AtIndex(e,i.TokenType._export,i.TokenType._function)||this.tokens.matches2AtIndex(e,i.TokenType._export,i.TokenType._class)){let t=this.tokens.identifierNameAtIndex(e+2);this.addExportBinding(t,t)}else if(this.tokens.matches3AtIndex(e,i.TokenType._export,i.TokenType.name,i.TokenType._function)){let t=this.tokens.identifierNameAtIndex(e+3);this.addExportBinding(t,t)}else this.tokens.matches2AtIndex(e,i.TokenType._export,i.TokenType.braceL)?this.preprocessNamedExportAtIndex(e):this.tokens.matches2AtIndex(e,i.TokenType._export,i.TokenType.star)&&this.preprocessExportStarAtIndex(e)}preprocessVarExportAtIndex(e){let t=0;for(let r=e+2;;r++)if(this.tokens.matches1AtIndex(r,i.TokenType.braceL)||this.tokens.matches1AtIndex(r,i.TokenType.dollarBraceL)||this.tokens.matches1AtIndex(r,i.TokenType.bracketL))t++;else if(this.tokens.matches1AtIndex(r,i.TokenType.braceR)||this.tokens.matches1AtIndex(r,i.TokenType.bracketR))t--;else if(t===0&&!this.tokens.matches1AtIndex(r,i.TokenType.name))break;else if(this.tokens.matches1AtIndex(1,i.TokenType.eq)){let e=this.tokens.currentToken().rhsEndIndex;if(e==null)throw Error(`Expected = token with an end index.`);r=e-1}else{let e=this.tokens.tokens[r];if(n.isDeclaration.call(void 0,e)){let e=this.tokens.identifierNameAtIndex(r);this.identifierReplacements.set(e,`exports.${e}`)}}}preprocessNamedExportAtIndex(e){e+=2;let{newIndex:t,namedImports:n}=this.getNamedImports(e);if(e=t,this.tokens.matchesContextualAtIndex(e,r.ContextualKeyword._from))e++;else{for(let{importedName:e,localName:t}of n)this.addExportBinding(e,t);return}if(!this.tokens.matches1AtIndex(e,i.TokenType.string))throw Error(`Expected string token at the end of import statement.`);let a=this.tokens.stringValueAtIndex(e);this.getImportInfo(a).namedExports.push(...n)}preprocessExportStarAtIndex(e){let t=null;if(this.tokens.matches3AtIndex(e,i.TokenType._export,i.TokenType.star,i.TokenType._as)?(e+=3,t=this.tokens.identifierNameAtIndex(e),e+=2):e+=3,!this.tokens.matches1AtIndex(e,i.TokenType.string))throw Error(`Expected string token at the end of star export statement.`);let n=this.tokens.stringValueAtIndex(e),r=this.getImportInfo(n);t===null?r.hasStarExport=!0:r.exportStarNames.push(t)}getNamedImports(e){let t=[];for(;;){if(this.tokens.matches1AtIndex(e,i.TokenType.braceR)){e++;break}let n=a.default.call(void 0,this.tokens,e);if(e=n.endIndex,n.isType||t.push({importedName:n.leftName,localName:n.rightName}),this.tokens.matches2AtIndex(e,i.TokenType.comma,i.TokenType.braceR)){e+=2;break}if(this.tokens.matches1AtIndex(e,i.TokenType.braceR)){e++;break}if(this.tokens.matches1AtIndex(e,i.TokenType.comma))e++;else throw Error(`Unexpected token: ${JSON.stringify(this.tokens.tokens[e])}`)}return{newIndex:e,namedImports:t}}getImportInfo(e){let t=this.importInfoByPath.get(e);if(t)return t;let n={defaultNames:[],wildcardNames:[],namedImports:[],namedExports:[],hasBareImport:!1,exportStarNames:[],hasStarExport:!1};return this.importInfoByPath.set(e,n),n}addExportBinding(e,t){this.exportBindingsByLocalName.has(e)||this.exportBindingsByLocalName.set(e,[]),this.exportBindingsByLocalName.get(e).push(t)}claimImportCode(e){let t=this.importsToReplace.get(e);return this.importsToReplace.set(e,``),t||``}getIdentifierReplacement(e){return this.identifierReplacements.get(e)||null}resolveExportBinding(e){let t=this.exportBindingsByLocalName.get(e);return!t||t.length===0?null:t.map(e=>`exports.${e}`).join(` = `)}getGlobalNames(){return/* @__PURE__ */ new Set([...this.identifierReplacements.keys(),...this.exportBindingsByLocalName.keys()])}}})),Md=/* @__PURE__ */ o(((e,t,n)=>{(function(n,r){if(typeof e==`object`&&t!==void 0)r(t),t.exports=i(t);else if(typeof define==`function`&&define.amd)define([`module`],function(e){r.apply(this,arguments),e.exports=i(e)});else{let e={exports:{}};r(e),n=typeof globalThis<`u`?globalThis:n||self,n.sourcemapCodec=i(e)}function i(e){return`default`in e.exports?e.exports.default:e.exports}})(n,(function(e){"use strict";var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},o=(e,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of r(a))!i.call(e,c)&&c!==o&&t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e},s=e=>o(t({},`__esModule`,{value:!0}),e),c={};a(c,{decode:()=>M,decodeGeneratedRanges:()=>D,decodeOriginalScopes:()=>w,decodeRangeMappings:()=>j,encode:()=>F,encodeGeneratedRanges:()=>O,encodeOriginalScopes:()=>T,encodeRangeMappings:()=>ee}),e.exports=s(c);var l=44,u=59,d=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,f=/* @__PURE__ */ new Uint8Array(64),p=/* @__PURE__ */ new Uint8Array(128);for(let e=0;e<d.length;e++){let t=d.charCodeAt(e);f[e]=t,p[t]=e}function m(e){let t=0,n=0,r=0;do r=p[e.next()],t|=(r&31)<<n,n+=5;while(r&32);return t}function h(e){return e&1?-2147483648|-(e>>>1):e>>>1}function g(e,t){do{let n=t&31;t>>>=5,t>0&&(n|=32),e.write(f[n])}while(t>0)}function _(e){return e<0?-e<<1|1:e<<1}function v(e,t){return e.pos>=t?!1:e.peek()!==l}var y=16384,b=typeof TextDecoder<`u`?/* @__PURE__ */ new TextDecoder:typeof Buffer<`u`?{decode(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString()}}:{decode(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}},x=class{constructor(){this.pos=0,this.out=``,this.buffer=new Uint8Array(y)}write(e){let{buffer:t}=this;t[this.pos++]=e,this.pos===y&&(this.out+=b.decode(t),this.pos=0)}flush(){let{buffer:e,out:t,pos:n}=this;return n>0?t+b.decode(e.subarray(0,n)):t}},S=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){let{buffer:t,pos:n}=this,r=t.indexOf(e,n);return r===-1?t.length:r}},C=[];function w(e){let{length:t}=e,n=new S(e),r=[],i=[],a=0;for(;n.pos<t;n.pos++){a+=h(m(n));let e=h(m(n));if(!v(n,t)){let t=i.pop();t[2]=a,t[3]=e;continue}let o=h(m(n)),s=h(m(n))&1?[a,e,0,0,o,h(m(n))]:[a,e,0,0,o],c=C;if(v(n,t)){c=[];do{let e=h(m(n));c.push(e)}while(v(n,t))}s.vars=c,r.push(s),i.push(s)}return r}function T(e){let t=new x;for(let n=0;n<e.length;)n=E(e,n,t,[0]);return t.flush()}function E(e,t,n,r){let i=e[t],{0:a,1:o,2:s,3:c,4:u,vars:d}=i;t>0&&n.write(l),g(n,_(a-r[0])),r[0]=a,g(n,_(o)),g(n,_(u)),g(n,_(+(i.length===6))),i.length===6&&g(n,_(i[5]));for(let e of d)g(n,_(e));for(t++;t<e.length;){let{0:i,1:a}=e[t];if(i>s||i===s&&a>=c)break;t=E(e,t,n,r)}return n.write(l),g(n,_(s-r[0])),r[0]=s,g(n,_(c)),t}function D(e){let{length:t}=e,n=new S(e),r=[],i=[],a=0,o=0,s=0,c=0,l=0,u=0,d=0,f=0;do{let e=n.indexOf(`;`),t=0;for(;n.pos<e;n.pos++){if(t+=h(m(n)),!v(n,e)){let e=i.pop();e[2]=a,e[3]=t;continue}let p=h(m(n)),g=p&1,_=p&2,y=p&4,b=null,x=C,S;if(g){let e=o+h(m(n));s=h(m(n))+(o===e?s:0),o=e,S=[a,t,0,0,e,s]}else S=[a,t,0,0];if(S.isScope=!!y,_){let e=c,t=l;c+=h(m(n));let r=e===c;l=(r?l:0)+h(m(n)),u=(r&&t===l?u:0)+h(m(n)),b=[c,l,u]}if(S.callsite=b,v(n,e)){x=[];do{d=a,f=t;let e=h(m(n)),r;if(e<-1){r=[[h(m(n))]];for(let t=-1;t>e;t--){let e=d;d+=h(m(n)),f=(d===e?f:0)+h(m(n));let t=h(m(n));r.push([t,d,f])}}else r=[[e]];x.push(r)}while(v(n,e))}S.bindings=x,r.push(S),i.push(S)}a++,n.pos=e+1}while(n.pos<t);return r}function O(e){if(e.length===0)return``;let t=new x;for(let n=0;n<e.length;)n=k(e,n,t,[0,0,0,0,0,0,0]);return t.flush()}function k(e,t,n,r){let i=e[t],{0:a,1:o,2:s,3:c,isScope:u,callsite:d,bindings:f}=i;if(r[0]<a?(A(n,r[0],a),r[0]=a,r[1]=0):t>0&&n.write(l),g(n,_(i[1]-r[1])),r[1]=i[1],g(n,_(i.length===6|(d?2:0)|(u?4:0))),i.length===6){let{4:e,5:t}=i;e!==r[2]&&(r[3]=0),g(n,_(e-r[2])),r[2]=e,g(n,_(t-r[3])),r[3]=t}if(d){let{0:e,1:t,2:a}=i.callsite;e===r[4]?t!==r[5]&&(r[6]=0):(r[5]=0,r[6]=0),g(n,_(e-r[4])),r[4]=e,g(n,_(t-r[5])),r[5]=t,g(n,_(a-r[6])),r[6]=a}if(f)for(let e of f){e.length>1&&g(n,_(-e.length));let t=e[0][0];g(n,_(t));let r=a,i=o;for(let t=1;t<e.length;t++){let a=e[t];g(n,_(a[1]-r)),r=a[1],g(n,_(a[2]-i)),i=a[2],g(n,_(a[0]))}}for(t++;t<e.length;){let{0:i,1:a}=e[t];if(i>s||i===s&&a>=c)break;t=k(e,t,n,r)}return r[0]<s?(A(n,r[0],s),r[0]=s,r[1]=0):n.write(l),g(n,_(c-r[1])),r[1]=c,t}function A(e,t,n){do e.write(u);while(++t<n)}function j(e){let{length:t}=e,n=new S(e),r=[];do{let e=n.indexOf(`;`),t=[],i=0;for(;n.pos<e;)i+=m(n),t.push(i);r.push(t),n.pos=e+1}while(n.pos<=t);return r}function ee(e){if(e.length===0)return``;let t=new x;for(let n=0;n<e.length;n++){let r=e[n];n>0&&t.write(u);let i=0;for(let e=0;e<r.length;e++){let n=r[e];g(t,n-i),i=n}}return t.flush()}function M(e){let{length:t}=e,n=new S(e),r=[],i=0,a=0,o=0,s=0,c=0;do{let e=n.indexOf(`;`),t=[],l=!0,u=0;for(i=0;n.pos<e;){let r;i+=h(m(n)),i<u&&(l=!1),u=i,v(n,e)?(a+=h(m(n)),o+=h(m(n)),s+=h(m(n)),v(n,e)?(c+=h(m(n)),r=[i,a,o,s,c]):r=[i,a,o,s]):r=[i],t.push(r),n.pos++}l||N(t),r.push(t),n.pos=e+1}while(n.pos<=t);return r}function N(e){e.sort(P)}function P(e,t){return e[0]-t[0]}function F(e){let t=new x,n=0,r=0,i=0,a=0;for(let o=0;o<e.length;o++){let s=e[o];if(o>0&&t.write(u),s.length===0)continue;let c=0;for(let e=0;e<s.length;e++){let o=s[e];e>0&&t.write(l),g(t,_(o[0]-c)),c=o[0],o.length!==1&&(g(t,_(o[1]-n)),g(t,_(o[2]-r)),g(t,_(o[3]-i)),n=o[1],r=o[2],i=o[3],o.length!==4&&(g(t,_(o[4]-a)),a=o[4]))}}return t.flush()}}))})),Nd=/* @__PURE__ */ o(((e,t,n)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self,n.resolveURI=r())})(n,(function(){"use strict";let e=/^[\w+.-]+:\/\//,t=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,n=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function r(t){return e.test(t)}function i(e){return e.startsWith(`//`)}function a(e){return e.startsWith(`/`)}function o(e){return e.startsWith(`file:`)}function s(e){return/^[.?#]/.test(e)}function c(e){let n=t.exec(e);return u(n[1],n[2]||``,n[3],n[4]||``,n[5]||`/`,n[6]||``,n[7]||``)}function l(e){let t=n.exec(e),r=t[2];return u(`file:`,``,t[1]||``,``,a(r)?r:`/`+r,t[3]||``,t[4]||``)}function u(e,t,n,r,i,a,o){return{scheme:e,user:t,host:n,port:r,path:i,query:a,hash:o,type:7}}function d(e){if(i(e)){let t=c(`http:`+e);return t.scheme=``,t.type=6,t}if(a(e)){let t=c(`http://foo.com`+e);return t.scheme=``,t.host=``,t.type=5,t}if(o(e))return l(e);if(r(e))return c(e);let t=c(`http://foo.com/`+e);return t.scheme=``,t.host=``,t.type=e?e.startsWith(`?`)?3:e.startsWith(`#`)?2:4:1,t}function f(e){if(e.endsWith(`/..`))return e;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function p(e,t){m(t,t.type),e.path=e.path===`/`?t.path:f(t.path)+e.path}function m(e,t){let n=t<=4,r=e.path.split(`/`),i=1,a=0,o=!1;for(let e=1;e<r.length;e++){let t=r[e];t?(o=!1,t!==`.`&&(t===`..`?a?(o=!0,a--,i--):n&&(r[i++]=t):(r[i++]=t,a++))):o=!0}let s=``;for(let e=1;e<i;e++)s+=`/`+r[e];(!s||o&&!s.endsWith(`/..`))&&(s+=`/`),e.path=s}function h(e,t){if(!e&&!t)return``;let n=d(e),r=n.type;if(t&&r!==7){let e=d(t),i=e.type;switch(r){case 1:n.hash=e.hash;case 2:n.query=e.query;case 3:case 4:p(n,e);case 5:n.user=e.user,n.host=e.host,n.port=e.port;case 6:n.scheme=e.scheme}i>r&&(r=i)}m(n,r);let i=n.query+n.hash;switch(r){case 2:case 3:return i;case 4:{let r=n.path.slice(1);return r?s(t||e)&&!s(r)?`./`+r+i:r+i:i||`.`}case 5:return n.path+i;default:return n.scheme+`//`+n.user+n.host+n.port+n.path+i}}return h}))})),Pd=/* @__PURE__ */ o(((e,t,n)=>{(function(n,r){if(typeof e==`object`&&t!==void 0)r(t,Nd(),Md()),t.exports=i(t);else if(typeof define==`function`&&define.amd)define([`module`,`@jridgewell/resolve-uri`,`@jridgewell/sourcemap-codec`],function(e){r.apply(this,arguments),e.exports=i(e)});else{let e={exports:{}};r(e,n.resolveURI,n.sourcemapCodec),n=typeof globalThis<`u`?globalThis:n||self,n.traceMapping=i(e)}function i(e){return`default`in e.exports?e.exports.default:e.exports}})(n,(function(e,t,n){"use strict";var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},u=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},f=(e,t,n)=>(n=e==null?{}:r(s(e)),d(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),p=e=>d(i({},`__esModule`,{value:!0}),e),m=l({"umd:@jridgewell/sourcemap-codec"(e,t){t.exports=n}}),h=l({"umd:@jridgewell/resolve-uri"(e,n){n.exports=t}}),g={};u(g,{AnyMap:()=>ne,FlattenMap:()=>ne,GREATEST_LOWER_BOUND:()=>ce,LEAST_UPPER_BOUND:()=>se,TraceMap:()=>le,allGeneratedPositionsFor:()=>he,decodedMap:()=>xe,decodedMappings:()=>de,eachMapping:()=>ge,encodedMap:()=>Se,encodedMappings:()=>ue,generatedPositionFor:()=>me,isIgnored:()=>ye,originalPositionFor:()=>pe,presortedDecodedMap:()=>be,sourceContentFor:()=>ve,traceSegment:()=>fe}),e.exports=p(g);var _=f(m()),v=f(h());function y(e){if(!e)return``;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function b(e,t){let n=y(e),r=t?t+`/`:``;return e=>(0,v.default)(r+(e||``),n)}var x=0,S=1,C=2,w=3,T=4,E=1,D=2;function O(e,t){let n=k(e,0);if(n===e.length)return e;t||(e=e.slice());for(let r=n;r<e.length;r=k(e,r+1))e[r]=j(e[r],t);return e}function k(e,t){for(let n=t;n<e.length;n++)if(!A(e[n]))return n;return e.length}function A(e){for(let t=1;t<e.length;t++)if(e[t][x]<e[t-1][x])return!1;return!0}function j(e,t){return t||(e=e.slice()),e.sort(ee)}function ee(e,t){return e[x]-t[x]}function M(e,t){let n=t.map(()=>[]);for(let t=0;t<e.length;t++){let r=e[t];for(let e=0;e<r.length;e++){let i=r[e];if(i.length===1)continue;let a=i[S],o=i[C],s=i[w],c=n[a];(c[o]||(c[o]=[])).push([s,t,i[x]])}}for(let e=0;e<n.length;e++){let t=n[e];for(let e=0;e<t.length;e++){let n=t[e];n&&n.sort(ee)}}return n}var N=!1;function P(e,t,n,r){for(;n<=r;){let i=n+(r-n>>1),a=e[i][x]-t;if(a===0)return N=!0,i;a<0?n=i+1:r=i-1}return N=!1,n-1}function F(e,t,n){for(let r=n+1;r<e.length&&e[r][x]===t;n=r++);return n}function I(e,t,n){for(let r=n-1;r>=0&&e[r][x]===t;n=r--);return n}function L(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function te(e,t,n,r){let{lastKey:i,lastNeedle:a,lastIndex:o}=n,s=0,c=e.length-1;if(r===i){if(t===a)return N=o!==-1&&e[o][x]===t,o;t>=a?s=o===-1?0:o:c=o}return n.lastKey=r,n.lastNeedle=t,n.lastIndex=P(e,t,s,c)}function R(e){return typeof e==`string`?JSON.parse(e):e}var ne=function(e,t){let n=R(e);if(!(`sections`in n))return new le(n,t);let r=[],i=[],a=[],o=[],s=[];return z(n,t,r,i,a,o,s,0,0,1/0,1/0),be({version:3,file:n.file,names:o,sources:i,sourcesContent:a,mappings:r,ignoreList:s})};function z(e,t,n,r,i,a,o,s,c,l,u){let{sections:d}=e;for(let e=0;e<d.length;e++){let{map:f,offset:p}=d[e],m=l,h=u;if(e+1<d.length){let t=d[e+1].offset;m=Math.min(l,s+t.line),m===l?h=Math.min(u,c+t.column):m<l&&(h=c+t.column)}B(f,t,n,r,i,a,o,s+p.line,c+p.column,m,h)}}function B(e,t,n,r,i,a,o,s,c,l,u){let d=R(e);if(`sections`in d)return z(...arguments);let f=new le(d,t),p=r.length,m=a.length,h=de(f),{resolvedSources:g,sourcesContent:_,ignoreList:v}=f;if(re(r,g),re(a,f.names),_)re(i,_);else for(let e=0;e<g.length;e++)i.push(null);if(v)for(let e=0;e<v.length;e++)o.push(v[e]+p);for(let e=0;e<h.length;e++){let t=s+e;if(t>l)return;let r=ie(n,t),i=e===0?c:0,a=h[e];for(let e=0;e<a.length;e++){let n=a[e],o=i+n[x];if(t===l&&o>=u)return;if(n.length===1){r.push([o]);continue}let s=p+n[S],c=n[C],d=n[w];r.push(n.length===4?[o,s,c,d]:[o,s,c,d,m+n[T]])}}}function re(e,t){for(let n=0;n<t.length;n++)e.push(t[n])}function ie(e,t){for(let n=e.length;n<=t;n++)e[n]=[];return e[t]}var ae="`line` must be greater than 0 (lines start at line 1)",oe="`column` must be greater than or equal to 0 (columns start at column 0)",se=-1,ce=1,le=class{constructor(e,t){let n=typeof e==`string`;if(!n&&e._decodedMemo)return e;let r=R(e),{version:i,file:a,names:o,sourceRoot:s,sources:c,sourcesContent:l}=r;this.version=i,this.file=a,this.names=o||[],this.sourceRoot=s,this.sources=c,this.sourcesContent=l,this.ignoreList=r.ignoreList||r.x_google_ignoreList||void 0;let u=b(t,s);this.resolvedSources=c.map(u);let{mappings:d}=r;if(typeof d==`string`)this._encoded=d,this._decoded=void 0;else if(Array.isArray(d))this._encoded=void 0,this._decoded=O(d,n);else if(r.sections)throw Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);else throw Error(`invalid source map: ${JSON.stringify(r)}`);this._decodedMemo=L(),this._bySources=void 0,this._bySourceMemos=void 0}};function V(e){return e}function ue(e){var t;return(t=V(e))._encoded??(t._encoded=(0,_.encode)(V(e)._decoded))}function de(e){var t;return(t=V(e))._decoded||(t._decoded=(0,_.decode)(V(e)._encoded))}function fe(e,t,n){let r=de(e);if(t>=r.length)return null;let i=r[t],a=Te(i,V(e)._decodedMemo,t,n,ce);return a===-1?null:i[a]}function pe(e,t){let{line:n,column:r,bias:i}=t;if(n--,n<0)throw Error(ae);if(r<0)throw Error(oe);let a=de(e);if(n>=a.length)return we(null,null,null,null);let o=a[n],s=Te(o,V(e)._decodedMemo,n,r,i||ce);if(s===-1)return we(null,null,null,null);let c=o[s];if(c.length===1)return we(null,null,null,null);let{names:l,resolvedSources:u}=e;return we(u[c[S]],c[C]+1,c[w],c.length===5?l[c[T]]:null)}function me(e,t){let{source:n,line:r,column:i,bias:a}=t;return De(e,n,r,i,a||ce,!1)}function he(e,t){let{source:n,line:r,column:i,bias:a}=t;return De(e,n,r,i,a||se,!0)}function ge(e,t){let n=de(e),{names:r,resolvedSources:i}=e;for(let e=0;e<n.length;e++){let a=n[e];for(let n=0;n<a.length;n++){let o=a[n],s=e+1,c=o[0],l=null,u=null,d=null,f=null;o.length!==1&&(l=i[o[1]],u=o[2]+1,d=o[3]),o.length===5&&(f=r[o[4]]),t({generatedLine:s,generatedColumn:c,source:l,originalLine:u,originalColumn:d,name:f})}}}function _e(e,t){let{sources:n,resolvedSources:r}=e,i=n.indexOf(t);return i===-1&&(i=r.indexOf(t)),i}function ve(e,t){let{sourcesContent:n}=e;if(n==null)return null;let r=_e(e,t);return r===-1?null:n[r]}function ye(e,t){let{ignoreList:n}=e;if(n==null)return!1;let r=_e(e,t);return r!==-1&&n.includes(r)}function be(e,t){let n=new le(Ce(e,[]),t);return V(n)._decoded=e.mappings,n}function xe(e){return Ce(e,de(e))}function Se(e){return Ce(e,ue(e))}function Ce(e,t){return{version:e.version,file:e.file,names:e.names,sourceRoot:e.sourceRoot,sources:e.sources,sourcesContent:e.sourcesContent,mappings:t,ignoreList:e.ignoreList||e.x_google_ignoreList}}function we(e,t,n,r){return{source:e,line:t,column:n,name:r}}function H(e,t){return{line:e,column:t}}function Te(e,t,n,r,i){let a=te(e,r,t,n);return N?a=(i===se?F:I)(e,r,a):i===se&&a++,a===-1||a===e.length?-1:a}function Ee(e,t,n,r,i){let a=Te(e,t,n,r,ce);if(!N&&i===se&&a++,a===-1||a===e.length)return[];let o=N?r:e[a][x];N||(a=I(e,o,a));let s=F(e,o,a),c=[];for(;a<=s;a++){let t=e[a];c.push(H(t[E]+1,t[D]))}return c}function De(e,t,n,r,i,a){var o,s;if(n--,n<0)throw Error(ae);if(r<0)throw Error(oe);let{sources:c,resolvedSources:l}=e,u=c.indexOf(t);if(u===-1&&(u=l.indexOf(t)),u===-1)return a?[]:H(null,null);let d=(o=V(e))._bySourceMemos||(o._bySourceMemos=c.map(L)),f=((s=V(e))._bySources||(s._bySources=M(de(e),d)))[u][n];if(f==null)return a?[]:H(null,null);let p=d[u];if(a)return Ee(f,p,n,r,i);let m=Te(f,p,n,r,i);if(m===-1)return H(null,null);let h=f[m];return H(h[E]+1,h[D])}}))})),Fd=/* @__PURE__ */ o(((e,t,n)=>{(function(n,r){if(typeof e==`object`&&t!==void 0)r(t,Md(),Pd()),t.exports=i(t);else if(typeof define==`function`&&define.amd)define([`module`,`@jridgewell/sourcemap-codec`,`@jridgewell/trace-mapping`],function(e){r.apply(this,arguments),e.exports=i(e)});else{let e={exports:{}};r(e,n.sourcemapCodec,n.traceMapping),n=typeof globalThis<`u`?globalThis:n||self,n.genMapping=i(e)}function i(e){return`default`in e.exports?e.exports.default:e.exports}})(n,(function(e,t,n){"use strict";var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},u=(e,t)=>{for(var n in t)i(e,n,{get:t[n],enumerable:!0})},d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&i(e,s,{get:()=>t[s],enumerable:!(r=a(t,s))||r.enumerable});return e},f=(e,t,n)=>(n=e==null?{}:r(s(e)),d(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),p=e=>d(i({},`__esModule`,{value:!0}),e),m=l({"umd:@jridgewell/sourcemap-codec"(e,n){n.exports=t}}),h=l({"umd:@jridgewell/trace-mapping"(e,t){t.exports=n}}),g={};u(g,{GenMapping:()=>A,addMapping:()=>M,addSegment:()=>ee,allMappings:()=>ne,fromMap:()=>R,maybeAddMapping:()=>P,maybeAddSegment:()=>N,setIgnore:()=>I,setSourceContent:()=>F,toDecodedMap:()=>L,toEncodedMap:()=>te}),e.exports=p(g);var _=class{constructor(){this._indexes={__proto__:null},this.array=[]}};function v(e){return e}function y(e,t){return v(e)._indexes[t]}function b(e,t){let n=y(e,t);if(n!==void 0)return n;let{array:r,_indexes:i}=v(e);return i[t]=r.push(t)-1}function x(e,t){let n=y(e,t);if(n===void 0)return;let{array:r,_indexes:i}=v(e);for(let e=n+1;e<r.length;e++){let t=r[e];r[e-1]=t,i[t]--}i[t]=void 0,r.pop()}var S=f(m()),C=f(h()),w=0,T=1,E=2,D=3,O=4,k=-1,A=class{constructor({file:e,sourceRoot:t}={}){this._names=new _,this._sources=new _,this._sourcesContent=[],this._mappings=[],this.file=e,this.sourceRoot=t,this._ignoreList=new _}};function j(e){return e}function ee(e,t,n,r,i,a,o,s){return z(!1,e,t,n,r,i,a,o,s)}function M(e,t){return le(!1,e,t)}var N=(e,t,n,r,i,a,o,s)=>z(!0,e,t,n,r,i,a,o,s),P=(e,t)=>le(!0,e,t);function F(e,t,n){let{_sources:r,_sourcesContent:i}=j(e),a=b(r,t);i[a]=n}function I(e,t,n=!0){let{_sources:r,_sourcesContent:i,_ignoreList:a}=j(e),o=b(r,t);o===i.length&&(i[o]=null),n?b(a,o):x(a,o)}function L(e){let{_mappings:t,_sources:n,_sourcesContent:r,_names:i,_ignoreList:a}=j(e);return ae(t),{version:3,file:e.file||void 0,names:i.array,sourceRoot:e.sourceRoot||void 0,sources:n.array,sourcesContent:r,mappings:t,ignoreList:a.array}}function te(e){let t=L(e);return Object.assign({},t,{mappings:(0,S.encode)(t.mappings)})}function R(e){let t=new C.TraceMap(e),n=new A({file:t.file,sourceRoot:t.sourceRoot});return oe(j(n)._names,t.names),oe(j(n)._sources,t.sources),j(n)._sourcesContent=t.sourcesContent||t.sources.map(()=>null),j(n)._mappings=(0,C.decodedMappings)(t),t.ignoreList&&oe(j(n)._ignoreList,t.ignoreList),n}function ne(e){let t=[],{_mappings:n,_sources:r,_names:i}=j(e);for(let e=0;e<n.length;e++){let a=n[e];for(let n=0;n<a.length;n++){let o=a[n],s={line:e+1,column:o[w]},c,l,u;o.length!==1&&(c=r.array[o[T]],l={line:o[E]+1,column:o[D]},o.length===5&&(u=i.array[o[O]])),t.push({generated:s,source:c,original:l,name:u})}}return t}function z(e,t,n,r,i,a,o,s,c){let{_mappings:l,_sources:u,_sourcesContent:d,_names:f}=j(t),p=B(l,n),m=re(p,r);if(!i)return e&&se(p,m)?void 0:ie(p,m,[r]);let h=b(u,i),g=s?b(f,s):k;if(h===d.length&&(d[h]=c??null),!(e&&ce(p,m,h,a,o,g)))return ie(p,m,s?[r,h,a,o,g]:[r,h,a,o])}function B(e,t){for(let n=e.length;n<=t;n++)e[n]=[];return e[t]}function re(e,t){let n=e.length;for(let r=n-1;r>=0&&!(t>=e[r][w]);n=r--);return n}function ie(e,t,n){for(let n=e.length;n>t;n--)e[n]=e[n-1];e[t]=n}function ae(e){let{length:t}=e,n=t;for(let t=n-1;t>=0&&!(e[t].length>0);n=t,t--);n<t&&(e.length=n)}function oe(e,t){for(let n=0;n<t.length;n++)b(e,t[n])}function se(e,t){return t===0||e[t-1].length===1}function ce(e,t,n,r,i,a){if(t===0)return!1;let o=e[t-1];return o.length!==1&&n===o[T]&&r===o[E]&&i===o[D]&&a===(o.length===5?o[O]:k)}function le(e,t,n){let{generated:r,source:i,original:a,name:o,content:s}=n;return i?z(e,t,r.line-1,r.column,i,a.line-1,a.column,o,s):z(e,t,r.line-1,r.column,null,null,null,null,null)}}))})),Id=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Fd(),n=_d();function r({code:e,mappings:r},a,o,s,c){let l=i(s,c),u=new t.GenMapping({file:o.compiledFilename}),d=0,f=r[0];for(;f===void 0&&d<r.length-1;)d++,f=r[d];let p=0,m=0;f!==m&&t.maybeAddSegment.call(void 0,u,p,0,a,p,0);for(let i=0;i<e.length;i++){if(i===f){let e=f-m,n=l[d];for(t.maybeAddSegment.call(void 0,u,p,e,a,p,n);(f===i||f===void 0)&&d<r.length-1;)d++,f=r[d]}e.charCodeAt(i)===n.charCodes.lineFeed&&(p++,m=i+1,f!==m&&t.maybeAddSegment.call(void 0,u,p,0,a,p,0))}let{sourceRoot:h,sourcesContent:g,..._}=t.toEncodedMap.call(void 0,u);return _}e.default=r;function i(e,t){let r=Array(t.length),i=0,a=t[i].start,o=0;for(let s=0;s<e.length;s++)s===a&&(r[i]=a-o,i++,a=t[i].start),e.charCodeAt(s)===n.charCodes.lineFeed&&(o=s+1);return r}})),Ld=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t={require:`
123
- import {createRequire as CREATE_REQUIRE_NAME} from "module";
124
- const require = CREATE_REQUIRE_NAME(import.meta.url);
125
- `,interopRequireWildcard:`
126
- function interopRequireWildcard(obj) {
127
- if (obj && obj.__esModule) {
128
- return obj;
129
- } else {
130
- var newObj = {};
131
- if (obj != null) {
132
- for (var key in obj) {
133
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
134
- newObj[key] = obj[key];
135
- }
136
- }
137
- }
138
- newObj.default = obj;
139
- return newObj;
140
- }
141
- }
142
- `,interopRequireDefault:`
143
- function interopRequireDefault(obj) {
144
- return obj && obj.__esModule ? obj : { default: obj };
145
- }
146
- `,createNamedExportFrom:`
147
- function createNamedExportFrom(obj, localName, importedName) {
148
- Object.defineProperty(exports, localName, {enumerable: true, configurable: true, get: () => obj[importedName]});
149
- }
150
- `,createStarExport:`
151
- function createStarExport(obj) {
152
- Object.keys(obj)
153
- .filter((key) => key !== "default" && key !== "__esModule")
154
- .forEach((key) => {
155
- if (exports.hasOwnProperty(key)) {
156
- return;
157
- }
158
- Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]});
159
- });
160
- }
161
- `,nullishCoalesce:`
162
- function nullishCoalesce(lhs, rhsFn) {
163
- if (lhs != null) {
164
- return lhs;
165
- } else {
166
- return rhsFn();
167
- }
168
- }
169
- `,asyncNullishCoalesce:`
170
- async function asyncNullishCoalesce(lhs, rhsFn) {
171
- if (lhs != null) {
172
- return lhs;
173
- } else {
174
- return await rhsFn();
175
- }
176
- }
177
- `,optionalChain:`
178
- function optionalChain(ops) {
179
- let lastAccessLHS = undefined;
180
- let value = ops[0];
181
- let i = 1;
182
- while (i < ops.length) {
183
- const op = ops[i];
184
- const fn = ops[i + 1];
185
- i += 2;
186
- if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
187
- return undefined;
188
- }
189
- if (op === 'access' || op === 'optionalAccess') {
190
- lastAccessLHS = value;
191
- value = fn(value);
192
- } else if (op === 'call' || op === 'optionalCall') {
193
- value = fn((...args) => value.call(lastAccessLHS, ...args));
194
- lastAccessLHS = undefined;
195
- }
196
- }
197
- return value;
198
- }
199
- `,asyncOptionalChain:`
200
- async function asyncOptionalChain(ops) {
201
- let lastAccessLHS = undefined;
202
- let value = ops[0];
203
- let i = 1;
204
- while (i < ops.length) {
205
- const op = ops[i];
206
- const fn = ops[i + 1];
207
- i += 2;
208
- if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {
209
- return undefined;
210
- }
211
- if (op === 'access' || op === 'optionalAccess') {
212
- lastAccessLHS = value;
213
- value = await fn(value);
214
- } else if (op === 'call' || op === 'optionalCall') {
215
- value = await fn((...args) => value.call(lastAccessLHS, ...args));
216
- lastAccessLHS = undefined;
217
- }
218
- }
219
- return value;
220
- }
221
- `,optionalChainDelete:`
222
- function optionalChainDelete(ops) {
223
- const result = OPTIONAL_CHAIN_NAME(ops);
224
- return result == null ? true : result;
225
- }
226
- `,asyncOptionalChainDelete:`
227
- async function asyncOptionalChainDelete(ops) {
228
- const result = await ASYNC_OPTIONAL_CHAIN_NAME(ops);
229
- return result == null ? true : result;
230
- }
231
- `};e.HelperManager=class e{__init(){this.helperNames={}}__init2(){this.createRequireName=null}constructor(t){this.nameManager=t,e.prototype.__init.call(this),e.prototype.__init2.call(this)}getHelperName(e){let t=this.helperNames[e];return t||(t=this.nameManager.claimFreeName(`_${e}`),this.helperNames[e]=t,t)}emitHelpers(){let e=``;this.helperNames.optionalChainDelete&&this.getHelperName(`optionalChain`),this.helperNames.asyncOptionalChainDelete&&this.getHelperName(`asyncOptionalChain`);for(let[n,r]of Object.entries(t)){let t=this.helperNames[n],i=r;n===`optionalChainDelete`?i=i.replace(`OPTIONAL_CHAIN_NAME`,this.helperNames.optionalChain):n===`asyncOptionalChainDelete`?i=i.replace(`ASYNC_OPTIONAL_CHAIN_NAME`,this.helperNames.asyncOptionalChain):n===`require`&&(this.createRequireName===null&&(this.createRequireName=this.nameManager.claimFreeName(`_createRequire`)),i=i.replace(/CREATE_REQUIRE_NAME/g,this.createRequireName)),t&&(e+=` `,e+=i.replace(n,t).replace(/\s+/g,` `).trim())}return e}}})),Rd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=wd(),n=K();function r(e,t,n){i(e,n)&&a(e,t,n)}e.default=r;function i(e,r){for(let i of e.tokens)if(i.type===n.TokenType.name&&!i.isType&&t.isNonTopLevelDeclaration.call(void 0,i)&&r.has(e.identifierNameForToken(i)))return!0;return!1}e.hasShadowedGlobals=i;function a(e,r,i){let a=[],s=r.length-1;for(let c=e.tokens.length-1;;c--){for(;a.length>0&&a[a.length-1].startTokenIndex===c+1;)a.pop();for(;s>=0&&r[s].endTokenIndex===c+1;)a.push(r[s]),s--;if(c<0)break;let l=e.tokens[c],u=e.identifierNameForToken(l);if(a.length>1&&!l.isType&&l.type===n.TokenType.name&&i.has(u)){if(t.isBlockScopedDeclaration.call(void 0,l))o(a[a.length-1],e,u);else if(t.isFunctionScopedDeclaration.call(void 0,l)){let t=a.length-1;for(;t>0&&!a[t].isFunctionScope;)t--;if(t<0)throw Error(`Did not find parent function scope.`);o(a[t],e,u)}}}if(a.length>0)throw Error(`Expected empty scope stack after processing file.`)}function o(e,t,r){for(let i=e.startTokenIndex;i<e.endTokenIndex;i++){let e=t.tokens[i];(e.type===n.TokenType.name||e.type===n.TokenType.jsxName)&&t.identifierNameForToken(e)===r&&(e.shadowsGlobal=!0)}}})),zd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=K();function n(e,n){let r=[];for(let i of n)i.type===t.TokenType.name&&r.push(e.slice(i.start,i.end));return r}e.default=n})),Bd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=t(zd());e.default=class e{__init(){this.usedNames=/* @__PURE__ */ new Set}constructor(t,r){e.prototype.__init.call(this),this.usedNames=new Set(n.default.call(void 0,t,r))}claimFreeName(e){let t=this.findFreeName(e);return this.usedNames.add(t),t}findFreeName(e){if(!this.usedNames.has(e))return e;let t=2;for(;this.usedNames.has(e+String(t));)t++;return e+String(t)}}})),Vd=/* @__PURE__ */ o(((e,t,n)=>{var r=n&&n.__extends||(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.DetailContext=e.NoopContext=e.VError=void 0;var i=function(e){r(t,e);function t(n,r){var i=e.call(this,r)||this;return i.path=n,Object.setPrototypeOf(i,t.prototype),i}return t}(Error);e.VError=i,e.NoopContext=function(){function e(){}return e.prototype.fail=function(e,t,n){return!1},e.prototype.unionResolver=function(){return this},e.prototype.createContext=function(){return this},e.prototype.resolveUnion=function(e){},e}();var a=function(){function e(){this._propNames=[``],this._messages=[null],this._score=0}return e.prototype.fail=function(e,t,n){return this._propNames.push(e),this._messages.push(t),this._score+=n,!1},e.prototype.unionResolver=function(){return new o},e.prototype.resolveUnion=function(e){for(var t,n,r=e,i=null,a=0,o=r.contexts;a<o.length;a++){var s=o[a];(!i||s._score>=i._score)&&(i=s)}i&&i._score>0&&((t=this._propNames).push.apply(t,i._propNames),(n=this._messages).push.apply(n,i._messages))},e.prototype.getError=function(e){for(var t=[],n=this._propNames.length-1;n>=0;n--){var r=this._propNames[n];e+=typeof r==`number`?`[`+r+`]`:r?`.`+r:``;var a=this._messages[n];a&&t.push(e+` `+a)}return new i(e,t.join(`; `))},e.prototype.getErrorDetail=function(e){for(var t=[],n=this._propNames.length-1;n>=0;n--){var r=this._propNames[n];e+=typeof r==`number`?`[`+r+`]`:r?`.`+r:``;var i=this._messages[n];i&&t.push({path:e,message:i})}for(var a=null,n=t.length-1;n>=0;n--)a&&(t[n].nested=[a]),a=t[n];return a},e}();e.DetailContext=a;var o=function(){function e(){this.contexts=[]}return e.prototype.createContext=function(){var e=new a;return this.contexts.push(e),e},e}()})),Hd=/* @__PURE__ */ o(((e,t,n)=>{var r=n&&n.__extends||(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.basicTypes=e.BasicType=e.TParamList=e.TParam=e.param=e.TFunc=e.func=e.TProp=e.TOptional=e.opt=e.TIface=e.iface=e.TEnumLiteral=e.enumlit=e.TEnumType=e.enumtype=e.TIntersection=e.intersection=e.TUnion=e.union=e.TTuple=e.tuple=e.TArray=e.array=e.TLiteral=e.lit=e.TName=e.name=e.TType=void 0;var i=Vd(),a=function(){function e(){}return e}();e.TType=a;function o(e){return typeof e==`string`?c(e):e}function s(e,t){var n=e[t];if(!n)throw Error(`Unknown type `+t);return n}function c(e){return new l(e)}e.name=c;var l=function(e){r(t,e);function t(t){var n=e.call(this)||this;return n.name=t,n._failMsg=`is not a `+t,n}return t.prototype.getChecker=function(e,n,r){var i=this,a=s(e,this.name),o=a.getChecker(e,n,r);return a instanceof F||a instanceof t?o:function(e,t){return o(e,t)?!0:t.fail(null,i._failMsg,0)}},t}(a);e.TName=l;function u(e){return new d(e)}e.lit=u;var d=function(e){r(t,e);function t(t){var n=e.call(this)||this;return n.value=t,n.name=JSON.stringify(t),n._failMsg=`is not `+n.name,n}return t.prototype.getChecker=function(e,t){var n=this;return function(e,t){return e===n.value||t.fail(null,n._failMsg,-1)}},t}(a);e.TLiteral=d;function f(e){return new p(o(e))}e.array=f;var p=function(e){r(t,e);function t(t){var n=e.call(this)||this;return n.ttype=t,n}return t.prototype.getChecker=function(e,t){var n=this.ttype.getChecker(e,t);return function(e,t){if(!Array.isArray(e))return t.fail(null,`is not an array`,0);for(var r=0;r<e.length;r++)if(!n(e[r],t))return t.fail(r,null,1);return!0}},t}(a);e.TArray=p;function m(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return new h(e.map(function(e){return o(e)}))}e.tuple=m;var h=function(e){r(t,e);function t(t){var n=e.call(this)||this;return n.ttypes=t,n}return t.prototype.getChecker=function(e,t){var n=this.ttypes.map(function(n){return n.getChecker(e,t)}),r=function(e,t){if(!Array.isArray(e))return t.fail(null,`is not an array`,0);for(var r=0;r<n.length;r++)if(!n[r](e[r],t))return t.fail(r,null,1);return!0};return t?function(e,t){return r(e,t)?e.length<=n.length||t.fail(n.length,`is extraneous`,2):!1}:r},t}(a);e.TTuple=h;function g(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return new _(e.map(function(e){return o(e)}))}e.union=g;var _=function(e){r(t,e);function t(t){var n=e.call(this)||this;n.ttypes=t;var r=t.map(function(e){return e instanceof l||e instanceof d?e.name:null}).filter(function(e){return e}),i=t.length-r.length;return r.length?(i>0&&r.push(i+` more`),n._failMsg=`is none of `+r.join(`, `)):n._failMsg=`is none of `+i+` types`,n}return t.prototype.getChecker=function(e,t){var n=this,r=this.ttypes.map(function(n){return n.getChecker(e,t)});return function(e,t){for(var i=t.unionResolver(),a=0;a<r.length;a++)if(r[a](e,i.createContext()))return!0;return t.resolveUnion(i),t.fail(null,n._failMsg,0)}},t}(a);e.TUnion=_;function v(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return new y(e.map(function(e){return o(e)}))}e.intersection=v;var y=function(e){r(t,e);function t(t){var n=e.call(this)||this;return n.ttypes=t,n}return t.prototype.getChecker=function(e,t){var n=/* @__PURE__ */ new Set,r=this.ttypes.map(function(r){return r.getChecker(e,t,n)});return function(e,t){return r.every(function(n){return n(e,t)})?!0:t.fail(null,null,0)}},t}(a);e.TIntersection=y;function b(e){return new x(e)}e.enumtype=b;var x=function(e){r(t,e);function t(t){var n=e.call(this)||this;return n.members=t,n.validValues=/* @__PURE__ */ new Set,n._failMsg=`is not a valid enum value`,n.validValues=new Set(Object.keys(t).map(function(e){return t[e]})),n}return t.prototype.getChecker=function(e,t){var n=this;return function(e,t){return n.validValues.has(e)?!0:t.fail(null,n._failMsg,0)}},t}(a);e.TEnumType=x;function S(e,t){return new C(e,t)}e.enumlit=S;var C=function(e){r(t,e);function t(t,n){var r=e.call(this)||this;return r.enumName=t,r.prop=n,r._failMsg=`is not `+t+`.`+n,r}return t.prototype.getChecker=function(e,t){var n=this,r=s(e,this.enumName);if(!(r instanceof x))throw Error(`Type `+this.enumName+` used in enumlit is not an enum type`);var i=r.members[this.prop];if(!r.members.hasOwnProperty(this.prop))throw Error(`Unknown value `+this.enumName+`.`+this.prop+` used in enumlit`);return function(e,t){return e===i||t.fail(null,n._failMsg,-1)}},t}(a);e.TEnumLiteral=C;function w(e){return Object.keys(e).map(function(t){return T(t,e[t])})}function T(e,t){return t instanceof k?new A(e,t.ttype,!0):new A(e,o(t),!1)}function E(e,t){return new D(e,w(t))}e.iface=E;var D=function(e){r(t,e);function t(t,n){var r=e.call(this)||this;return r.bases=t,r.props=n,r.propSet=new Set(n.map(function(e){return e.name})),r}return t.prototype.getChecker=function(e,t,n){var r=this,a=this.bases.map(function(n){return s(e,n).getChecker(e,t)}),o=this.props.map(function(n){return n.ttype.getChecker(e,t)}),c=new i.NoopContext,l=this.props.map(function(e,t){return!e.isOpt&&!o[t](void 0,c)}),u=function(e,t){if(typeof e!=`object`||!e)return t.fail(null,`is not an object`,0);for(var n=0;n<a.length;n++)if(!a[n](e,t))return!1;for(var n=0;n<o.length;n++){var i=r.props[n].name,s=e[i];if(s===void 0){if(l[n])return t.fail(i,`is missing`,1)}else if(!o[n](s,t))return t.fail(i,null,1)}return!0};if(!t)return u;var d=this.propSet;return n&&(this.propSet.forEach(function(e){return n.add(e)}),d=n),function(e,t){if(!u(e,t))return!1;for(var n in e)if(!d.has(n))return t.fail(n,`is extraneous`,2);return!0}},t}(a);e.TIface=D;function O(e){return new k(o(e))}e.opt=O;var k=function(e){r(t,e);function t(t){var n=e.call(this)||this;return n.ttype=t,n}return t.prototype.getChecker=function(e,t){var n=this.ttype.getChecker(e,t);return function(e,t){return e===void 0||n(e,t)}},t}(a);e.TOptional=k;var A=function(){function e(e,t,n){this.name=e,this.ttype=t,this.isOpt=n}return e}();e.TProp=A;function j(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return new ee(new P(t),o(e))}e.func=j;var ee=function(e){r(t,e);function t(t,n){var r=e.call(this)||this;return r.paramList=t,r.result=n,r}return t.prototype.getChecker=function(e,t){return function(e,t){return typeof e==`function`||t.fail(null,`is not a function`,0)}},t}(a);e.TFunc=ee;function M(e,t,n){return new N(e,o(t),!!n)}e.param=M;var N=function(){function e(e,t,n){this.name=e,this.ttype=t,this.isOpt=n}return e}();e.TParam=N;var P=function(e){r(t,e);function t(t){var n=e.call(this)||this;return n.params=t,n}return t.prototype.getChecker=function(e,t){var n=this,r=this.params.map(function(n){return n.ttype.getChecker(e,t)}),a=new i.NoopContext,o=this.params.map(function(e,t){return!e.isOpt&&!r[t](void 0,a)}),s=function(e,t){if(!Array.isArray(e))return t.fail(null,`is not an array`,0);for(var i=0;i<r.length;i++){var a=n.params[i];if(e[i]===void 0){if(o[i])return t.fail(a.name,`is missing`,1)}else if(!r[i](e[i],t))return t.fail(a.name,null,1)}return!0};return t?function(e,t){return s(e,t)?e.length<=r.length||t.fail(r.length,`is extraneous`,2):!1}:s},t}(a);e.TParamList=P;var F=function(e){r(t,e);function t(t,n){var r=e.call(this)||this;return r.validator=t,r.message=n,r}return t.prototype.getChecker=function(e,t){var n=this;return function(e,t){return n.validator(e)?!0:t.fail(null,n.message,0)}},t}(a);e.BasicType=F,e.basicTypes={any:new F(function(e){return!0},`is invalid`),number:new F(function(e){return typeof e==`number`},`is not a number`),object:new F(function(e){return typeof e==`object`&&e},`is not an object`),boolean:new F(function(e){return typeof e==`boolean`},`is not a boolean`),string:new F(function(e){return typeof e==`string`},`is not a string`),symbol:new F(function(e){return typeof e==`symbol`},`is not a symbol`),void:new F(function(e){return e==null},`is not void`),undefined:new F(function(e){return e===void 0},`is not undefined`),null:new F(function(e){return e===null},`is not null`),never:new F(function(e){return!1},`is unexpected`),Date:new F(L(`[object Date]`),`is not a Date`),RegExp:new F(L(`[object RegExp]`),`is not a RegExp`)};var I=Object.prototype.toString;function L(e){return function(t){return typeof t==`object`&&t&&I.call(t)===e}}typeof Buffer<`u`&&(e.basicTypes.Buffer=new F(function(e){return Buffer.isBuffer(e)},`is not a Buffer`));for(var te=function(t){e.basicTypes[t.name]=new F(function(e){return e instanceof t},`is not a `+t.name)},R=0,ne=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,ArrayBuffer];R<ne.length;R++){var z=ne[R];te(z)}})),Ud=/* @__PURE__ */ o(((e,t,n)=>{var r=n&&n.__spreadArrays||function(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var a=arguments[t],o=0,s=a.length;o<s;o++,i++)r[i]=a[o];return r};Object.defineProperty(e,"__esModule",{value:!0}),e.Checker=e.createCheckers=void 0;var i=Hd(),a=Vd(),o=Hd();Object.defineProperty(e,"TArray",{enumerable:!0,get:function(){return o.TArray}}),Object.defineProperty(e,"TEnumType",{enumerable:!0,get:function(){return o.TEnumType}}),Object.defineProperty(e,"TEnumLiteral",{enumerable:!0,get:function(){return o.TEnumLiteral}}),Object.defineProperty(e,"TFunc",{enumerable:!0,get:function(){return o.TFunc}}),Object.defineProperty(e,"TIface",{enumerable:!0,get:function(){return o.TIface}}),Object.defineProperty(e,"TLiteral",{enumerable:!0,get:function(){return o.TLiteral}}),Object.defineProperty(e,"TName",{enumerable:!0,get:function(){return o.TName}}),Object.defineProperty(e,"TOptional",{enumerable:!0,get:function(){return o.TOptional}}),Object.defineProperty(e,"TParam",{enumerable:!0,get:function(){return o.TParam}}),Object.defineProperty(e,"TParamList",{enumerable:!0,get:function(){return o.TParamList}}),Object.defineProperty(e,"TProp",{enumerable:!0,get:function(){return o.TProp}}),Object.defineProperty(e,"TTuple",{enumerable:!0,get:function(){return o.TTuple}}),Object.defineProperty(e,"TType",{enumerable:!0,get:function(){return o.TType}}),Object.defineProperty(e,"TUnion",{enumerable:!0,get:function(){return o.TUnion}}),Object.defineProperty(e,"TIntersection",{enumerable:!0,get:function(){return o.TIntersection}}),Object.defineProperty(e,"array",{enumerable:!0,get:function(){return o.array}}),Object.defineProperty(e,"enumlit",{enumerable:!0,get:function(){return o.enumlit}}),Object.defineProperty(e,"enumtype",{enumerable:!0,get:function(){return o.enumtype}}),Object.defineProperty(e,"func",{enumerable:!0,get:function(){return o.func}}),Object.defineProperty(e,"iface",{enumerable:!0,get:function(){return o.iface}}),Object.defineProperty(e,"lit",{enumerable:!0,get:function(){return o.lit}}),Object.defineProperty(e,"name",{enumerable:!0,get:function(){return o.name}}),Object.defineProperty(e,"opt",{enumerable:!0,get:function(){return o.opt}}),Object.defineProperty(e,"param",{enumerable:!0,get:function(){return o.param}}),Object.defineProperty(e,"tuple",{enumerable:!0,get:function(){return o.tuple}}),Object.defineProperty(e,"union",{enumerable:!0,get:function(){return o.union}}),Object.defineProperty(e,"intersection",{enumerable:!0,get:function(){return o.intersection}}),Object.defineProperty(e,"BasicType",{enumerable:!0,get:function(){return o.BasicType}});var s=Vd();Object.defineProperty(e,"VError",{enumerable:!0,get:function(){return s.VError}});function c(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=Object.assign.apply(Object,r([{},i.basicTypes],e)),a={},o=0,s=e;o<s.length;o++)for(var c=s[o],u=0,d=Object.keys(c);u<d.length;u++){var f=d[u];a[f]=new l(n,c[f])}return a}e.createCheckers=c;var l=function(){function e(e,t,n){if(n===void 0&&(n=`value`),this.suite=e,this.ttype=t,this._path=n,this.props=/* @__PURE__ */ new Map,t instanceof i.TIface)for(var r=0,a=t.props;r<a.length;r++){var o=a[r];this.props.set(o.name,o.ttype)}this.checkerPlain=this.ttype.getChecker(e,!1),this.checkerStrict=this.ttype.getChecker(e,!0)}return e.prototype.setReportedPath=function(e){this._path=e},e.prototype.check=function(e){return this._doCheck(this.checkerPlain,e)},e.prototype.test=function(e){return this.checkerPlain(e,new a.NoopContext)},e.prototype.validate=function(e){return this._doValidate(this.checkerPlain,e)},e.prototype.strictCheck=function(e){return this._doCheck(this.checkerStrict,e)},e.prototype.strictTest=function(e){return this.checkerStrict(e,new a.NoopContext)},e.prototype.strictValidate=function(e){return this._doValidate(this.checkerStrict,e)},e.prototype.getProp=function(t){var n=this.props.get(t);if(!n)throw Error(`Type has no property `+t);return new e(this.suite,n,this._path+`.`+t)},e.prototype.methodArgs=function(t){var n=this._getMethod(t);return new e(this.suite,n.paramList)},e.prototype.methodResult=function(t){var n=this._getMethod(t);return new e(this.suite,n.result)},e.prototype.getArgs=function(){if(!(this.ttype instanceof i.TFunc))throw Error(`getArgs() applied to non-function`);return new e(this.suite,this.ttype.paramList)},e.prototype.getResult=function(){if(!(this.ttype instanceof i.TFunc))throw Error(`getResult() applied to non-function`);return new e(this.suite,this.ttype.result)},e.prototype.getType=function(){return this.ttype},e.prototype._doCheck=function(e,t){if(!e(t,new a.NoopContext)){var n=new a.DetailContext;throw e(t,n),n.getError(this._path)}},e.prototype._doValidate=function(e,t){if(e(t,new a.NoopContext))return null;var n=new a.DetailContext;return e(t,n),n.getErrorDetail(this._path)},e.prototype._getMethod=function(e){var t=this.props.get(e);if(!t)throw Error(`Type has no property `+e);if(!(t instanceof i.TFunc))throw Error(`Property `+e+` is not a method`);return t},e}();e.Checker=l})),Wd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}var n=t(Ud());e.Transform=n.union(n.lit(`jsx`),n.lit(`typescript`),n.lit(`flow`),n.lit(`imports`),n.lit(`react-hot-loader`),n.lit(`jest`)),e.SourceMapOptions=n.iface([],{compiledFilename:`string`}),e.Options=n.iface([],{transforms:n.array(`Transform`),disableESTransforms:n.opt(`boolean`),jsxRuntime:n.opt(n.union(n.lit(`classic`),n.lit(`automatic`),n.lit(`preserve`))),production:n.opt(`boolean`),jsxImportSource:n.opt(`string`),jsxPragma:n.opt(`string`),jsxFragmentPragma:n.opt(`string`),keepUnusedImports:n.opt(`boolean`),preserveDynamicImport:n.opt(`boolean`),injectCreateRequireForImportRequire:n.opt(`boolean`),enableLegacyTypeScriptModuleInterop:n.opt(`boolean`),enableLegacyBabel5ModuleInterop:n.opt(`boolean`),sourceMapOptions:n.opt(`SourceMapOptions`),filePath:n.opt(`string`)}),e.default={Transform:e.Transform,SourceMapOptions:e.SourceMapOptions,Options:e.Options}})),Gd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=Ud(),r=t(Wd());let{Options:i}=n.createCheckers.call(void 0,r.default);function a(e){i.strictCheck(e)}e.validateOptions=a})),Kd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Zd(),n=qd(),r=wd(),i=hd(),a=K(),o=vd(),s=Xd(),c=yd();function l(){r.next.call(void 0),s.parseMaybeAssign.call(void 0,!1)}e.parseSpread=l;function u(e){r.next.call(void 0),m(e)}e.parseRest=u;function d(e){s.parseIdentifier.call(void 0),p(e)}e.parseBindingIdentifier=d;function f(){s.parseIdentifier.call(void 0),o.state.tokens[o.state.tokens.length-1].identifierRole=r.IdentifierRole.ImportDeclaration}e.parseImportedIdentifier=f;function p(e){let t;t=o.state.scopeDepth===0?r.IdentifierRole.TopLevelDeclaration:e?r.IdentifierRole.BlockScopedDeclaration:r.IdentifierRole.FunctionScopedDeclaration,o.state.tokens[o.state.tokens.length-1].identifierRole=t}e.markPriorBindingIdentifier=p;function m(e){switch(o.state.type){case a.TokenType._this:{let e=r.pushTypeContext.call(void 0,0);r.next.call(void 0),r.popTypeContext.call(void 0,e);return}case a.TokenType._yield:case a.TokenType.name:o.state.type=a.TokenType.name,d(e);return;case a.TokenType.bracketL:r.next.call(void 0),h(a.TokenType.bracketR,e,!0);return;case a.TokenType.braceL:s.parseObj.call(void 0,!0,e);return;default:c.unexpected.call(void 0)}}e.parseBindingAtom=m;function h(e,t,n=!1,i=!1,s=0){let l=!0,d=!1,f=o.state.tokens.length;for(;!r.eat.call(void 0,e)&&!o.state.error;)if(l?l=!1:(c.expect.call(void 0,a.TokenType.comma),o.state.tokens[o.state.tokens.length-1].contextId=s,!d&&o.state.tokens[f].isType&&(o.state.tokens[o.state.tokens.length-1].isType=!0,d=!0)),!(n&&r.match.call(void 0,a.TokenType.comma))){if(r.eat.call(void 0,e))break;if(r.match.call(void 0,a.TokenType.ellipsis)){u(t),_(),r.eat.call(void 0,a.TokenType.comma),c.expect.call(void 0,e);break}g(i,t)}}e.parseBindingList=h;function g(e,t){e&&n.tsParseModifiers.call(void 0,[i.ContextualKeyword._public,i.ContextualKeyword._protected,i.ContextualKeyword._private,i.ContextualKeyword._readonly,i.ContextualKeyword._override]),v(t),_(),v(t,!0)}function _(){o.isFlowEnabled?t.flowParseAssignableListItemTypes.call(void 0):o.isTypeScriptEnabled&&n.tsParseAssignableListItemTypes.call(void 0)}function v(e,t=!1){if(t||m(e),!r.eat.call(void 0,a.TokenType.eq))return;let n=o.state.tokens.length-1;s.parseMaybeAssign.call(void 0),o.state.tokens[n].rhsEndIndex=o.state.tokens.length}e.parseMaybeDefault=v})),qd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=wd(),n=hd(),r=K(),i=vd(),a=Xd(),o=Kd(),s=Qd(),c=yd(),l=Jd();function u(){return t.match.call(void 0,r.TokenType.name)}function d(){return t.match.call(void 0,r.TokenType.name)||!!(i.state.type&r.TokenType.IS_KEYWORD)||t.match.call(void 0,r.TokenType.string)||t.match.call(void 0,r.TokenType.num)||t.match.call(void 0,r.TokenType.bigint)||t.match.call(void 0,r.TokenType.decimal)}function f(){let e=i.state.snapshot();return t.next.call(void 0),(t.match.call(void 0,r.TokenType.bracketL)||t.match.call(void 0,r.TokenType.braceL)||t.match.call(void 0,r.TokenType.star)||t.match.call(void 0,r.TokenType.ellipsis)||t.match.call(void 0,r.TokenType.hash)||d())&&!c.hasPrecedingLineBreak.call(void 0)?!0:(i.state.restoreFromSnapshot(e),!1)}function p(e){for(;m(e)!==null;);}e.tsParseModifiers=p;function m(e){if(!t.match.call(void 0,r.TokenType.name))return null;let a=i.state.contextualKeyword;if(e.indexOf(a)!==-1&&f()){switch(a){case n.ContextualKeyword._readonly:i.state.tokens[i.state.tokens.length-1].type=r.TokenType._readonly;break;case n.ContextualKeyword._abstract:i.state.tokens[i.state.tokens.length-1].type=r.TokenType._abstract;break;case n.ContextualKeyword._static:i.state.tokens[i.state.tokens.length-1].type=r.TokenType._static;break;case n.ContextualKeyword._public:i.state.tokens[i.state.tokens.length-1].type=r.TokenType._public;break;case n.ContextualKeyword._private:i.state.tokens[i.state.tokens.length-1].type=r.TokenType._private;break;case n.ContextualKeyword._protected:i.state.tokens[i.state.tokens.length-1].type=r.TokenType._protected;break;case n.ContextualKeyword._override:i.state.tokens[i.state.tokens.length-1].type=r.TokenType._override;break;case n.ContextualKeyword._declare:i.state.tokens[i.state.tokens.length-1].type=r.TokenType._declare}return a}return null}e.tsParseModifier=m;function h(){for(a.parseIdentifier.call(void 0);t.eat.call(void 0,r.TokenType.dot);)a.parseIdentifier.call(void 0)}function g(){h(),!c.hasPrecedingLineBreak.call(void 0)&&t.match.call(void 0,r.TokenType.lessThan)&&He()}function _(){t.next.call(void 0),_e()}function v(){t.next.call(void 0)}function y(){c.expect.call(void 0,r.TokenType._typeof),t.match.call(void 0,r.TokenType._import)?b():h(),!c.hasPrecedingLineBreak.call(void 0)&&t.match.call(void 0,r.TokenType.lessThan)&&He()}function b(){c.expect.call(void 0,r.TokenType._import),c.expect.call(void 0,r.TokenType.parenL),c.expect.call(void 0,r.TokenType.string),c.expect.call(void 0,r.TokenType.parenR),t.eat.call(void 0,r.TokenType.dot)&&h(),t.match.call(void 0,r.TokenType.lessThan)&&He()}function x(){t.eat.call(void 0,r.TokenType._const);let e=t.eat.call(void 0,r.TokenType._in),o=c.eatContextual.call(void 0,n.ContextualKeyword._out);t.eat.call(void 0,r.TokenType._const),(e||o)&&!t.match.call(void 0,r.TokenType.name)?i.state.tokens[i.state.tokens.length-1].type=r.TokenType.name:a.parseIdentifier.call(void 0),t.eat.call(void 0,r.TokenType._extends)&&ve(),t.eat.call(void 0,r.TokenType.eq)&&ve()}function S(){t.match.call(void 0,r.TokenType.lessThan)&&C()}e.tsTryParseTypeParameters=S;function C(){let e=t.pushTypeContext.call(void 0,0);for(t.match.call(void 0,r.TokenType.lessThan)||t.match.call(void 0,r.TokenType.typeParameterStart)?t.next.call(void 0):c.unexpected.call(void 0);!t.eat.call(void 0,r.TokenType.greaterThan)&&!i.state.error;)x(),t.eat.call(void 0,r.TokenType.comma);t.popTypeContext.call(void 0,e)}function w(e){let n=e===r.TokenType.arrow;S(),c.expect.call(void 0,r.TokenType.parenL),i.state.scopeDepth++,T(!1),i.state.scopeDepth--,(n||t.match.call(void 0,e))&&fe(e)}function T(e){o.parseBindingList.call(void 0,r.TokenType.parenR,e)}function E(){t.eat.call(void 0,r.TokenType.comma)||c.semicolon.call(void 0)}function D(){w(r.TokenType.colon),E()}function O(){let e=i.state.snapshot();t.next.call(void 0);let n=t.eat.call(void 0,r.TokenType.name)&&t.match.call(void 0,r.TokenType.colon);return i.state.restoreFromSnapshot(e),n}function k(){if(!(t.match.call(void 0,r.TokenType.bracketL)&&O()))return!1;let e=t.pushTypeContext.call(void 0,0);return c.expect.call(void 0,r.TokenType.bracketL),a.parseIdentifier.call(void 0),_e(),c.expect.call(void 0,r.TokenType.bracketR),me(),E(),t.popTypeContext.call(void 0,e),!0}function A(e){t.eat.call(void 0,r.TokenType.question),!e&&(t.match.call(void 0,r.TokenType.parenL)||t.match.call(void 0,r.TokenType.lessThan))?(w(r.TokenType.colon),E()):(me(),E())}function j(){if(t.match.call(void 0,r.TokenType.parenL)||t.match.call(void 0,r.TokenType.lessThan)){D();return}if(t.match.call(void 0,r.TokenType._new)){t.next.call(void 0),t.match.call(void 0,r.TokenType.parenL)||t.match.call(void 0,r.TokenType.lessThan)?D():A(!1);return}let e=!!m([n.ContextualKeyword._readonly]);k()||((c.isContextual.call(void 0,n.ContextualKeyword._get)||c.isContextual.call(void 0,n.ContextualKeyword._set))&&f(),a.parsePropertyName.call(void 0,-1),A(e))}function ee(){M()}function M(){for(c.expect.call(void 0,r.TokenType.braceL);!t.eat.call(void 0,r.TokenType.braceR)&&!i.state.error;)j()}function N(){let e=i.state.snapshot(),t=P();return i.state.restoreFromSnapshot(e),t}function P(){return t.next.call(void 0),t.eat.call(void 0,r.TokenType.plus)||t.eat.call(void 0,r.TokenType.minus)?c.isContextual.call(void 0,n.ContextualKeyword._readonly):(c.isContextual.call(void 0,n.ContextualKeyword._readonly)&&t.next.call(void 0),!t.match.call(void 0,r.TokenType.bracketL)||(t.next.call(void 0),!u())?!1:(t.next.call(void 0),t.match.call(void 0,r.TokenType._in)))}function F(){a.parseIdentifier.call(void 0),c.expect.call(void 0,r.TokenType._in),ve()}function I(){c.expect.call(void 0,r.TokenType.braceL),t.match.call(void 0,r.TokenType.plus)||t.match.call(void 0,r.TokenType.minus)?(t.next.call(void 0),c.expectContextual.call(void 0,n.ContextualKeyword._readonly)):c.eatContextual.call(void 0,n.ContextualKeyword._readonly),c.expect.call(void 0,r.TokenType.bracketL),F(),c.eatContextual.call(void 0,n.ContextualKeyword._as)&&ve(),c.expect.call(void 0,r.TokenType.bracketR),t.match.call(void 0,r.TokenType.plus)||t.match.call(void 0,r.TokenType.minus)?(t.next.call(void 0),c.expect.call(void 0,r.TokenType.question)):t.eat.call(void 0,r.TokenType.question),he(),c.semicolon.call(void 0),c.expect.call(void 0,r.TokenType.braceR)}function L(){for(c.expect.call(void 0,r.TokenType.bracketL);!t.eat.call(void 0,r.TokenType.bracketR)&&!i.state.error;)te(),t.eat.call(void 0,r.TokenType.comma)}function te(){t.eat.call(void 0,r.TokenType.ellipsis)?ve():(ve(),t.eat.call(void 0,r.TokenType.question)),t.eat.call(void 0,r.TokenType.colon)&&ve()}function R(){c.expect.call(void 0,r.TokenType.parenL),ve(),c.expect.call(void 0,r.TokenType.parenR)}function ne(){for(t.nextTemplateToken.call(void 0),t.nextTemplateToken.call(void 0);!t.match.call(void 0,r.TokenType.backQuote)&&!i.state.error;)c.expect.call(void 0,r.TokenType.dollarBraceL),ve(),t.nextTemplateToken.call(void 0),t.nextTemplateToken.call(void 0);t.next.call(void 0)}var z;(function(e){e[e.TSFunctionType=0]=`TSFunctionType`,e[e.TSConstructorType=1]=`TSConstructorType`,e[e.TSAbstractConstructorType=2]=`TSAbstractConstructorType`})(z||={});function B(e){e===z.TSAbstractConstructorType&&c.expectContextual.call(void 0,n.ContextualKeyword._abstract),(e===z.TSConstructorType||e===z.TSAbstractConstructorType)&&c.expect.call(void 0,r.TokenType._new);let t=i.state.inDisallowConditionalTypesContext;i.state.inDisallowConditionalTypesContext=!1,w(r.TokenType.arrow),i.state.inDisallowConditionalTypesContext=t}function re(){switch(i.state.type){case r.TokenType.name:g();return;case r.TokenType._void:case r.TokenType._null:t.next.call(void 0);return;case r.TokenType.string:case r.TokenType.num:case r.TokenType.bigint:case r.TokenType.decimal:case r.TokenType._true:case r.TokenType._false:a.parseLiteral.call(void 0);return;case r.TokenType.minus:t.next.call(void 0),a.parseLiteral.call(void 0);return;case r.TokenType._this:v(),c.isContextual.call(void 0,n.ContextualKeyword._is)&&!c.hasPrecedingLineBreak.call(void 0)&&_();return;case r.TokenType._typeof:y();return;case r.TokenType._import:b();return;case r.TokenType.braceL:N()?I():ee();return;case r.TokenType.bracketL:L();return;case r.TokenType.parenL:R();return;case r.TokenType.backQuote:ne();return;default:if(i.state.type&r.TokenType.IS_KEYWORD){t.next.call(void 0),i.state.tokens[i.state.tokens.length-1].type=r.TokenType.name;return}}c.unexpected.call(void 0)}function ie(){for(re();!c.hasPrecedingLineBreak.call(void 0)&&t.eat.call(void 0,r.TokenType.bracketL);)t.eat.call(void 0,r.TokenType.bracketR)||(ve(),c.expect.call(void 0,r.TokenType.bracketR))}function ae(){if(c.expectContextual.call(void 0,n.ContextualKeyword._infer),a.parseIdentifier.call(void 0),t.match.call(void 0,r.TokenType._extends)){let e=i.state.snapshot();c.expect.call(void 0,r.TokenType._extends);let n=i.state.inDisallowConditionalTypesContext;i.state.inDisallowConditionalTypesContext=!0,ve(),i.state.inDisallowConditionalTypesContext=n,(i.state.error||!i.state.inDisallowConditionalTypesContext&&t.match.call(void 0,r.TokenType.question))&&i.state.restoreFromSnapshot(e)}}function oe(){if(c.isContextual.call(void 0,n.ContextualKeyword._keyof)||c.isContextual.call(void 0,n.ContextualKeyword._unique)||c.isContextual.call(void 0,n.ContextualKeyword._readonly))t.next.call(void 0),oe();else if(c.isContextual.call(void 0,n.ContextualKeyword._infer))ae();else{let e=i.state.inDisallowConditionalTypesContext;i.state.inDisallowConditionalTypesContext=!1,ie(),i.state.inDisallowConditionalTypesContext=e}}function se(){if(t.eat.call(void 0,r.TokenType.bitwiseAND),oe(),t.match.call(void 0,r.TokenType.bitwiseAND))for(;t.eat.call(void 0,r.TokenType.bitwiseAND);)oe()}function ce(){if(t.eat.call(void 0,r.TokenType.bitwiseOR),se(),t.match.call(void 0,r.TokenType.bitwiseOR))for(;t.eat.call(void 0,r.TokenType.bitwiseOR);)se()}function le(){return t.match.call(void 0,r.TokenType.lessThan)?!0:t.match.call(void 0,r.TokenType.parenL)&&ue()}function V(){if(t.match.call(void 0,r.TokenType.name)||t.match.call(void 0,r.TokenType._this))return t.next.call(void 0),!0;if(t.match.call(void 0,r.TokenType.braceL)||t.match.call(void 0,r.TokenType.bracketL)){let e=1;for(t.next.call(void 0);e>0&&!i.state.error;)t.match.call(void 0,r.TokenType.braceL)||t.match.call(void 0,r.TokenType.bracketL)?e++:(t.match.call(void 0,r.TokenType.braceR)||t.match.call(void 0,r.TokenType.bracketR))&&e--,t.next.call(void 0);return!0}return!1}function ue(){let e=i.state.snapshot(),t=de();return i.state.restoreFromSnapshot(e),t}function de(){return t.next.call(void 0),!!(t.match.call(void 0,r.TokenType.parenR)||t.match.call(void 0,r.TokenType.ellipsis)||V()&&(t.match.call(void 0,r.TokenType.colon)||t.match.call(void 0,r.TokenType.comma)||t.match.call(void 0,r.TokenType.question)||t.match.call(void 0,r.TokenType.eq)||t.match.call(void 0,r.TokenType.parenR)&&(t.next.call(void 0),t.match.call(void 0,r.TokenType.arrow))))}function fe(e){let n=t.pushTypeContext.call(void 0,0);c.expect.call(void 0,e),ge()||ve(),t.popTypeContext.call(void 0,n)}function pe(){t.match.call(void 0,r.TokenType.colon)&&fe(r.TokenType.colon)}function me(){t.match.call(void 0,r.TokenType.colon)&&_e()}e.tsTryParseTypeAnnotation=me;function he(){t.eat.call(void 0,r.TokenType.colon)&&ve()}function ge(){let e=i.state.snapshot();return c.isContextual.call(void 0,n.ContextualKeyword._asserts)?(t.next.call(void 0),c.eatContextual.call(void 0,n.ContextualKeyword._is)?(ve(),!0):u()||t.match.call(void 0,r.TokenType._this)?(t.next.call(void 0),c.eatContextual.call(void 0,n.ContextualKeyword._is)&&ve(),!0):(i.state.restoreFromSnapshot(e),!1)):u()||t.match.call(void 0,r.TokenType._this)?(t.next.call(void 0),c.isContextual.call(void 0,n.ContextualKeyword._is)&&!c.hasPrecedingLineBreak.call(void 0)?(t.next.call(void 0),ve(),!0):(i.state.restoreFromSnapshot(e),!1)):!1}function _e(){let e=t.pushTypeContext.call(void 0,0);c.expect.call(void 0,r.TokenType.colon),ve(),t.popTypeContext.call(void 0,e)}e.tsParseTypeAnnotation=_e;function ve(){if(be(),i.state.inDisallowConditionalTypesContext||c.hasPrecedingLineBreak.call(void 0)||!t.eat.call(void 0,r.TokenType._extends))return;let e=i.state.inDisallowConditionalTypesContext;i.state.inDisallowConditionalTypesContext=!0,be(),i.state.inDisallowConditionalTypesContext=e,c.expect.call(void 0,r.TokenType.question),ve(),c.expect.call(void 0,r.TokenType.colon),ve()}e.tsParseType=ve;function ye(){return c.isContextual.call(void 0,n.ContextualKeyword._abstract)&&t.lookaheadType.call(void 0)===r.TokenType._new}function be(){le()?B(z.TSFunctionType):t.match.call(void 0,r.TokenType._new)?B(z.TSConstructorType):ye()?B(z.TSAbstractConstructorType):ce()}e.tsParseNonConditionalType=be;function xe(){let e=t.pushTypeContext.call(void 0,1);ve(),c.expect.call(void 0,r.TokenType.greaterThan),t.popTypeContext.call(void 0,e),a.parseMaybeUnary.call(void 0)}e.tsParseTypeAssertion=xe;function Se(){if(t.eat.call(void 0,r.TokenType.jsxTagStart)){i.state.tokens[i.state.tokens.length-1].type=r.TokenType.typeParameterStart;let e=t.pushTypeContext.call(void 0,1);for(;!t.match.call(void 0,r.TokenType.greaterThan)&&!i.state.error;)ve(),t.eat.call(void 0,r.TokenType.comma);l.nextJSXTagToken.call(void 0),t.popTypeContext.call(void 0,e)}}e.tsTryParseJSXTypeArgument=Se;function Ce(){for(;!t.match.call(void 0,r.TokenType.braceL)&&!i.state.error;)we(),t.eat.call(void 0,r.TokenType.comma)}function we(){h(),t.match.call(void 0,r.TokenType.lessThan)&&He()}function H(){o.parseBindingIdentifier.call(void 0,!1),S(),t.eat.call(void 0,r.TokenType._extends)&&Ce(),M()}function Te(){o.parseBindingIdentifier.call(void 0,!1),S(),c.expect.call(void 0,r.TokenType.eq),ve(),c.semicolon.call(void 0)}function Ee(){if(t.match.call(void 0,r.TokenType.string)?a.parseLiteral.call(void 0):a.parseIdentifier.call(void 0),t.eat.call(void 0,r.TokenType.eq)){let e=i.state.tokens.length-1;a.parseMaybeAssign.call(void 0),i.state.tokens[e].rhsEndIndex=i.state.tokens.length}}function De(){for(o.parseBindingIdentifier.call(void 0,!1),c.expect.call(void 0,r.TokenType.braceL);!t.eat.call(void 0,r.TokenType.braceR)&&!i.state.error;)Ee(),t.eat.call(void 0,r.TokenType.comma)}function Oe(){c.expect.call(void 0,r.TokenType.braceL),s.parseBlockBody.call(void 0,r.TokenType.braceR)}function ke(){o.parseBindingIdentifier.call(void 0,!1),t.eat.call(void 0,r.TokenType.dot)?ke():Oe()}function Ae(){c.isContextual.call(void 0,n.ContextualKeyword._global)?a.parseIdentifier.call(void 0):t.match.call(void 0,r.TokenType.string)?a.parseExprAtom.call(void 0):c.unexpected.call(void 0),t.match.call(void 0,r.TokenType.braceL)?Oe():c.semicolon.call(void 0)}function je(){o.parseImportedIdentifier.call(void 0),c.expect.call(void 0,r.TokenType.eq),Ne(),c.semicolon.call(void 0)}e.tsParseImportEqualsDeclaration=je;function Me(){return c.isContextual.call(void 0,n.ContextualKeyword._require)&&t.lookaheadType.call(void 0)===r.TokenType.parenL}function Ne(){Me()?Pe():h()}function Pe(){c.expectContextual.call(void 0,n.ContextualKeyword._require),c.expect.call(void 0,r.TokenType.parenL),t.match.call(void 0,r.TokenType.string)||c.unexpected.call(void 0),a.parseLiteral.call(void 0),c.expect.call(void 0,r.TokenType.parenR)}function Fe(){if(c.isLineTerminator.call(void 0))return!1;switch(i.state.type){case r.TokenType._function:{let e=t.pushTypeContext.call(void 0,1);t.next.call(void 0);let n=i.state.start;return s.parseFunction.call(void 0,n,!0),t.popTypeContext.call(void 0,e),!0}case r.TokenType._class:{let e=t.pushTypeContext.call(void 0,1);return s.parseClass.call(void 0,!0,!1),t.popTypeContext.call(void 0,e),!0}case r.TokenType._const:if(t.match.call(void 0,r.TokenType._const)&&c.isLookaheadContextual.call(void 0,n.ContextualKeyword._enum)){let e=t.pushTypeContext.call(void 0,1);return c.expect.call(void 0,r.TokenType._const),c.expectContextual.call(void 0,n.ContextualKeyword._enum),i.state.tokens[i.state.tokens.length-1].type=r.TokenType._enum,De(),t.popTypeContext.call(void 0,e),!0}case r.TokenType._var:case r.TokenType._let:{let e=t.pushTypeContext.call(void 0,1);return s.parseVarStatement.call(void 0,i.state.type!==r.TokenType._var),t.popTypeContext.call(void 0,e),!0}case r.TokenType.name:{let e=t.pushTypeContext.call(void 0,1),r=i.state.contextualKeyword,a=!1;return r===n.ContextualKeyword._global?(Ae(),a=!0):a=Re(r,!0),t.popTypeContext.call(void 0,e),a}default:return!1}}function Ie(){return Re(i.state.contextualKeyword,!0)}function Le(e){switch(e){case n.ContextualKeyword._declare:{let e=i.state.tokens.length-1;if(Fe())return i.state.tokens[e].type=r.TokenType._declare,!0;break}case n.ContextualKeyword._global:if(t.match.call(void 0,r.TokenType.braceL))return Oe(),!0;break;default:return Re(e,!1)}return!1}function Re(e,a){switch(e){case n.ContextualKeyword._abstract:if(ze(a)&&t.match.call(void 0,r.TokenType._class))return i.state.tokens[i.state.tokens.length-1].type=r.TokenType._abstract,s.parseClass.call(void 0,!0,!1),!0;break;case n.ContextualKeyword._enum:if(ze(a)&&t.match.call(void 0,r.TokenType.name))return i.state.tokens[i.state.tokens.length-1].type=r.TokenType._enum,De(),!0;break;case n.ContextualKeyword._interface:if(ze(a)&&t.match.call(void 0,r.TokenType.name)){let e=t.pushTypeContext.call(void 0,a?2:1);return H(),t.popTypeContext.call(void 0,e),!0}break;case n.ContextualKeyword._module:if(ze(a)){if(t.match.call(void 0,r.TokenType.string)){let e=t.pushTypeContext.call(void 0,a?2:1);return Ae(),t.popTypeContext.call(void 0,e),!0}if(t.match.call(void 0,r.TokenType.name)){let e=t.pushTypeContext.call(void 0,a?2:1);return ke(),t.popTypeContext.call(void 0,e),!0}}break;case n.ContextualKeyword._namespace:if(ze(a)&&t.match.call(void 0,r.TokenType.name)){let e=t.pushTypeContext.call(void 0,a?2:1);return ke(),t.popTypeContext.call(void 0,e),!0}break;case n.ContextualKeyword._type:if(ze(a)&&t.match.call(void 0,r.TokenType.name)){let e=t.pushTypeContext.call(void 0,a?2:1);return Te(),t.popTypeContext.call(void 0,e),!0}}return!1}function ze(e){return e?(t.next.call(void 0),!0):!c.isLineTerminator.call(void 0)}function Be(){let e=i.state.snapshot();return C(),s.parseFunctionParams.call(void 0),pe(),c.expect.call(void 0,r.TokenType.arrow),i.state.error?(i.state.restoreFromSnapshot(e),!1):(a.parseFunctionBody.call(void 0,!0),!0)}function Ve(){i.state.type===r.TokenType.bitShiftL&&(--i.state.pos,t.finishToken.call(void 0,r.TokenType.lessThan)),He()}function He(){let e=t.pushTypeContext.call(void 0,0);for(c.expect.call(void 0,r.TokenType.lessThan);!t.match.call(void 0,r.TokenType.greaterThan)&&!i.state.error;)ve(),t.eat.call(void 0,r.TokenType.comma);e?(c.expect.call(void 0,r.TokenType.greaterThan),t.popTypeContext.call(void 0,e)):(t.popTypeContext.call(void 0,e),t.rescan_gt.call(void 0),c.expect.call(void 0,r.TokenType.greaterThan),i.state.tokens[i.state.tokens.length-1].isType=!0)}function Ue(){if(t.match.call(void 0,r.TokenType.name))switch(i.state.contextualKeyword){case n.ContextualKeyword._abstract:case n.ContextualKeyword._declare:case n.ContextualKeyword._enum:case n.ContextualKeyword._interface:case n.ContextualKeyword._module:case n.ContextualKeyword._namespace:case n.ContextualKeyword._type:return!0}return!1}e.tsIsDeclarationStart=Ue;function We(e,n){if(t.match.call(void 0,r.TokenType.colon)&&fe(r.TokenType.colon),!t.match.call(void 0,r.TokenType.braceL)&&c.isLineTerminator.call(void 0)){let t=i.state.tokens.length-1;for(;t>=0&&(i.state.tokens[t].start>=e||i.state.tokens[t].type===r.TokenType._default||i.state.tokens[t].type===r.TokenType._export);)i.state.tokens[t].isType=!0,t--}else a.parseFunctionBody.call(void 0,!1,n)}e.tsParseFunctionBodyAndFinish=We;function Ge(e,n,o){if(!c.hasPrecedingLineBreak.call(void 0)&&t.eat.call(void 0,r.TokenType.bang))i.state.tokens[i.state.tokens.length-1].type=r.TokenType.nonNullAssertion;else{if(t.match.call(void 0,r.TokenType.lessThan)||t.match.call(void 0,r.TokenType.bitShiftL)){let o=i.state.snapshot();if(!n&&a.atPossibleAsync.call(void 0)&&Be())return;if(Ve(),!n&&t.eat.call(void 0,r.TokenType.parenL)?(i.state.tokens[i.state.tokens.length-1].subscriptStartIndex=e,a.parseCallExpressionArguments.call(void 0)):t.match.call(void 0,r.TokenType.backQuote)?a.parseTemplate.call(void 0):(i.state.type===r.TokenType.greaterThan||i.state.type!==r.TokenType.parenL&&i.state.type&r.TokenType.IS_EXPRESSION_START&&!c.hasPrecedingLineBreak.call(void 0))&&c.unexpected.call(void 0),i.state.error)i.state.restoreFromSnapshot(o);else return}else!n&&t.match.call(void 0,r.TokenType.questionDot)&&t.lookaheadType.call(void 0)===r.TokenType.lessThan&&(t.next.call(void 0),i.state.tokens[e].isOptionalChainStart=!0,i.state.tokens[i.state.tokens.length-1].subscriptStartIndex=e,He(),c.expect.call(void 0,r.TokenType.parenL),a.parseCallExpressionArguments.call(void 0));a.baseParseSubscript.call(void 0,e,n,o)}}e.tsParseSubscript=Ge;function Ke(){if(t.eat.call(void 0,r.TokenType._import))return c.isContextual.call(void 0,n.ContextualKeyword._type)&&t.lookaheadType.call(void 0)!==r.TokenType.eq&&c.expectContextual.call(void 0,n.ContextualKeyword._type),je(),!0;if(t.eat.call(void 0,r.TokenType.eq))return a.parseExpression.call(void 0),c.semicolon.call(void 0),!0;if(c.eatContextual.call(void 0,n.ContextualKeyword._as))return c.expectContextual.call(void 0,n.ContextualKeyword._namespace),a.parseIdentifier.call(void 0),c.semicolon.call(void 0),!0;if(c.isContextual.call(void 0,n.ContextualKeyword._type)){let e=t.lookaheadType.call(void 0);(e===r.TokenType.braceL||e===r.TokenType.star)&&t.next.call(void 0)}return!1}e.tsTryParseExport=Ke;function qe(){a.parseIdentifier.call(void 0),t.match.call(void 0,r.TokenType.comma)||t.match.call(void 0,r.TokenType.braceR)?i.state.tokens[i.state.tokens.length-1].identifierRole=t.IdentifierRole.ImportDeclaration:(a.parseIdentifier.call(void 0),t.match.call(void 0,r.TokenType.comma)||t.match.call(void 0,r.TokenType.braceR)?(i.state.tokens[i.state.tokens.length-1].identifierRole=t.IdentifierRole.ImportDeclaration,i.state.tokens[i.state.tokens.length-2].isType=!0,i.state.tokens[i.state.tokens.length-1].isType=!0):(a.parseIdentifier.call(void 0),t.match.call(void 0,r.TokenType.comma)||t.match.call(void 0,r.TokenType.braceR)?(i.state.tokens[i.state.tokens.length-3].identifierRole=t.IdentifierRole.ImportAccess,i.state.tokens[i.state.tokens.length-1].identifierRole=t.IdentifierRole.ImportDeclaration):(a.parseIdentifier.call(void 0),i.state.tokens[i.state.tokens.length-3].identifierRole=t.IdentifierRole.ImportAccess,i.state.tokens[i.state.tokens.length-1].identifierRole=t.IdentifierRole.ImportDeclaration,i.state.tokens[i.state.tokens.length-4].isType=!0,i.state.tokens[i.state.tokens.length-3].isType=!0,i.state.tokens[i.state.tokens.length-2].isType=!0,i.state.tokens[i.state.tokens.length-1].isType=!0)))}e.tsParseImportSpecifier=qe;function Je(){a.parseIdentifier.call(void 0),t.match.call(void 0,r.TokenType.comma)||t.match.call(void 0,r.TokenType.braceR)?i.state.tokens[i.state.tokens.length-1].identifierRole=t.IdentifierRole.ExportAccess:(a.parseIdentifier.call(void 0),t.match.call(void 0,r.TokenType.comma)||t.match.call(void 0,r.TokenType.braceR)?(i.state.tokens[i.state.tokens.length-1].identifierRole=t.IdentifierRole.ExportAccess,i.state.tokens[i.state.tokens.length-2].isType=!0,i.state.tokens[i.state.tokens.length-1].isType=!0):(a.parseIdentifier.call(void 0),t.match.call(void 0,r.TokenType.comma)||t.match.call(void 0,r.TokenType.braceR)?i.state.tokens[i.state.tokens.length-3].identifierRole=t.IdentifierRole.ExportAccess:(a.parseIdentifier.call(void 0),i.state.tokens[i.state.tokens.length-3].identifierRole=t.IdentifierRole.ExportAccess,i.state.tokens[i.state.tokens.length-4].isType=!0,i.state.tokens[i.state.tokens.length-3].isType=!0,i.state.tokens[i.state.tokens.length-2].isType=!0,i.state.tokens[i.state.tokens.length-1].isType=!0)))}e.tsParseExportSpecifier=Je;function Ye(){if(c.isContextual.call(void 0,n.ContextualKeyword._abstract)&&t.lookaheadType.call(void 0)===r.TokenType._class)return i.state.type=r.TokenType._abstract,t.next.call(void 0),s.parseClass.call(void 0,!0,!0),!0;if(c.isContextual.call(void 0,n.ContextualKeyword._interface)){let e=t.pushTypeContext.call(void 0,2);return Re(n.ContextualKeyword._interface,!0),t.popTypeContext.call(void 0,e),!0}return!1}e.tsTryParseExportDefaultExpression=Ye;function Xe(){if(i.state.type===r.TokenType._const){let e=t.lookaheadTypeAndKeyword.call(void 0);if(e.type===r.TokenType.name&&e.contextualKeyword===n.ContextualKeyword._enum)return c.expect.call(void 0,r.TokenType._const),c.expectContextual.call(void 0,n.ContextualKeyword._enum),i.state.tokens[i.state.tokens.length-1].type=r.TokenType._enum,De(),!0}return!1}e.tsTryParseStatementContent=Xe;function Ze(e){let t=i.state.tokens.length;p([n.ContextualKeyword._abstract,n.ContextualKeyword._readonly,n.ContextualKeyword._declare,n.ContextualKeyword._static,n.ContextualKeyword._override]);let r=i.state.tokens.length;if(k()){let n=e?t-1:t;for(let e=n;e<r;e++)i.state.tokens[e].isType=!0;return!0}return!1}e.tsTryParseClassMemberWithIsStatic=Ze;function Qe(e){Le(e)||c.semicolon.call(void 0)}e.tsParseIdentifierStatement=Qe;function $e(){let e=c.eatContextual.call(void 0,n.ContextualKeyword._declare);e&&(i.state.tokens[i.state.tokens.length-1].type=r.TokenType._declare);let a=!1;if(t.match.call(void 0,r.TokenType.name)){if(e){let e=t.pushTypeContext.call(void 0,2);a=Ie(),t.popTypeContext.call(void 0,e)}else a=Ie()}if(!a){if(e){let e=t.pushTypeContext.call(void 0,2);s.parseStatement.call(void 0,!0),t.popTypeContext.call(void 0,e)}else s.parseStatement.call(void 0,!0)}}e.tsParseExportDeclaration=$e;function et(e){if(e&&(t.match.call(void 0,r.TokenType.lessThan)||t.match.call(void 0,r.TokenType.bitShiftL))&&Ve(),c.eatContextual.call(void 0,n.ContextualKeyword._implements)){i.state.tokens[i.state.tokens.length-1].type=r.TokenType._implements;let e=t.pushTypeContext.call(void 0,1);Ce(),t.popTypeContext.call(void 0,e)}}e.tsAfterParseClassSuper=et;function tt(){S()}e.tsStartParseObjPropValue=tt;function nt(){S()}e.tsStartParseFunctionParams=nt;function rt(){let e=t.pushTypeContext.call(void 0,0);c.hasPrecedingLineBreak.call(void 0)||t.eat.call(void 0,r.TokenType.bang),me(),t.popTypeContext.call(void 0,e)}e.tsAfterParseVarHead=rt;function it(){t.match.call(void 0,r.TokenType.colon)&&_e()}e.tsStartParseAsyncArrowFromCallExpression=it;function at(e,t){return i.isJSXEnabled?ot(e,t):st(e,t)}e.tsParseMaybeAssign=at;function ot(e,n){if(!t.match.call(void 0,r.TokenType.lessThan))return a.baseParseMaybeAssign.call(void 0,e,n);let o=i.state.snapshot(),s=a.baseParseMaybeAssign.call(void 0,e,n);if(i.state.error)i.state.restoreFromSnapshot(o);else return s;return i.state.type=r.TokenType.typeParameterStart,C(),s=a.baseParseMaybeAssign.call(void 0,e,n),s||c.unexpected.call(void 0),s}e.tsParseMaybeAssignWithJSX=ot;function st(e,n){if(!t.match.call(void 0,r.TokenType.lessThan))return a.baseParseMaybeAssign.call(void 0,e,n);let o=i.state.snapshot();C();let s=a.baseParseMaybeAssign.call(void 0,e,n);if(s||c.unexpected.call(void 0),i.state.error)i.state.restoreFromSnapshot(o);else return s;return a.baseParseMaybeAssign.call(void 0,e,n)}e.tsParseMaybeAssignWithoutJSX=st;function ct(){if(t.match.call(void 0,r.TokenType.colon)){let e=i.state.snapshot();fe(r.TokenType.colon),c.canInsertSemicolon.call(void 0)&&c.unexpected.call(void 0),t.match.call(void 0,r.TokenType.arrow)||c.unexpected.call(void 0),i.state.error&&i.state.restoreFromSnapshot(e)}return t.eat.call(void 0,r.TokenType.arrow)}e.tsParseArrow=ct;function lt(){let e=t.pushTypeContext.call(void 0,0);t.eat.call(void 0,r.TokenType.question),me(),t.popTypeContext.call(void 0,e)}e.tsParseAssignableListItemTypes=lt;function ut(){(t.match.call(void 0,r.TokenType.lessThan)||t.match.call(void 0,r.TokenType.bitShiftL))&&Ve(),s.baseParseMaybeDecoratorArguments.call(void 0)}e.tsParseMaybeDecoratorArguments=ut})),Jd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=wd(),n=K(),r=vd(),i=Xd(),a=yd(),o=_d(),s=xd(),c=qd();function l(){let e=!1,i=!1;for(;;){if(r.state.pos>=r.input.length){a.unexpected.call(void 0,`Unterminated JSX contents`);return}let s=r.input.charCodeAt(r.state.pos);if(s===o.charCodes.lessThan||s===o.charCodes.leftCurlyBrace){if(r.state.pos===r.state.start){if(s===o.charCodes.lessThan){r.state.pos++,t.finishToken.call(void 0,n.TokenType.jsxTagStart);return}t.getTokenFromCode.call(void 0,s);return}e&&!i?t.finishToken.call(void 0,n.TokenType.jsxEmptyText):t.finishToken.call(void 0,n.TokenType.jsxText);return}s===o.charCodes.lineFeed?e=!0:s!==o.charCodes.space&&s!==o.charCodes.carriageReturn&&s!==o.charCodes.tab&&(i=!0),r.state.pos++}}function u(e){for(r.state.pos++;;){if(r.state.pos>=r.input.length){a.unexpected.call(void 0,`Unterminated string constant`);return}if(r.input.charCodeAt(r.state.pos)===e){r.state.pos++;break}r.state.pos++}t.finishToken.call(void 0,n.TokenType.string)}function d(){let e;do{if(r.state.pos>r.input.length){a.unexpected.call(void 0,`Unexpectedly reached the end of input.`);return}e=r.input.charCodeAt(++r.state.pos)}while(s.IS_IDENTIFIER_CHAR[e]||e===o.charCodes.dash);t.finishToken.call(void 0,n.TokenType.jsxName)}function f(){x()}function p(e){f(),t.eat.call(void 0,n.TokenType.colon)?f():r.state.tokens[r.state.tokens.length-1].identifierRole=e}function m(){let e=r.state.tokens.length;p(t.IdentifierRole.Access);let i=!1;for(;t.match.call(void 0,n.TokenType.dot);)i=!0,x(),f();if(!i){let t=r.state.tokens[e],n=r.input.charCodeAt(t.start);n>=o.charCodes.lowercaseA&&n<=o.charCodes.lowercaseZ&&(t.identifierRole=null)}}function h(){switch(r.state.type){case n.TokenType.braceL:t.next.call(void 0),i.parseExpression.call(void 0),x();return;case n.TokenType.jsxTagStart:b(),x();return;case n.TokenType.string:x();return;default:a.unexpected.call(void 0,`JSX value should be either an expression or a quoted JSX text`)}}function g(){a.expect.call(void 0,n.TokenType.ellipsis),i.parseExpression.call(void 0)}function _(e){if(t.match.call(void 0,n.TokenType.jsxTagEnd))return!1;m(),r.isTypeScriptEnabled&&c.tsTryParseJSXTypeArgument.call(void 0);let s=!1;for(;!t.match.call(void 0,n.TokenType.slash)&&!t.match.call(void 0,n.TokenType.jsxTagEnd)&&!r.state.error;)t.eat.call(void 0,n.TokenType.braceL)?(s=!0,a.expect.call(void 0,n.TokenType.ellipsis),i.parseMaybeAssign.call(void 0),x()):(s&&r.state.end-r.state.start===3&&r.input.charCodeAt(r.state.start)===o.charCodes.lowercaseK&&r.input.charCodeAt(r.state.start+1)===o.charCodes.lowercaseE&&r.input.charCodeAt(r.state.start+2)===o.charCodes.lowercaseY&&(r.state.tokens[e].jsxRole=t.JSXRole.KeyAfterPropSpread),p(t.IdentifierRole.ObjectKey),t.match.call(void 0,n.TokenType.eq)&&(x(),h()));let l=t.match.call(void 0,n.TokenType.slash);return l&&x(),l}function v(){t.match.call(void 0,n.TokenType.jsxTagEnd)||m()}function y(){let e=r.state.tokens.length-1;r.state.tokens[e].jsxRole=t.JSXRole.NoChildren;let o=0;if(!_(e))for(S();;)switch(r.state.type){case n.TokenType.jsxTagStart:if(x(),t.match.call(void 0,n.TokenType.slash)){x(),v(),r.state.tokens[e].jsxRole!==t.JSXRole.KeyAfterPropSpread&&(o===1?r.state.tokens[e].jsxRole=t.JSXRole.OneChild:o>1&&(r.state.tokens[e].jsxRole=t.JSXRole.StaticChildren));return}o++,y(),S();break;case n.TokenType.jsxText:o++,S();break;case n.TokenType.jsxEmptyText:S();break;case n.TokenType.braceL:t.next.call(void 0),t.match.call(void 0,n.TokenType.ellipsis)?(g(),S(),o+=2):(t.match.call(void 0,n.TokenType.braceR)||(o++,i.parseExpression.call(void 0)),S());break;
232
- // istanbul ignore next - should never happen
233
- default:a.unexpected.call(void 0);return}}function b(){x(),y()}e.jsxParseElement=b;function x(){r.state.tokens.push(new t.Token),t.skipSpace.call(void 0),r.state.start=r.state.pos;let e=r.input.charCodeAt(r.state.pos);if(s.IS_IDENTIFIER_START[e])d();else if(e===o.charCodes.quotationMark||e===o.charCodes.apostrophe)u(e);else switch(++r.state.pos,e){case o.charCodes.greaterThan:t.finishToken.call(void 0,n.TokenType.jsxTagEnd);break;case o.charCodes.lessThan:t.finishToken.call(void 0,n.TokenType.jsxTagStart);break;case o.charCodes.slash:t.finishToken.call(void 0,n.TokenType.slash);break;case o.charCodes.equalsTo:t.finishToken.call(void 0,n.TokenType.eq);break;case o.charCodes.leftCurlyBrace:t.finishToken.call(void 0,n.TokenType.braceL);break;case o.charCodes.dot:t.finishToken.call(void 0,n.TokenType.dot);break;case o.charCodes.colon:t.finishToken.call(void 0,n.TokenType.colon);break;default:a.unexpected.call(void 0)}}e.nextJSXTagToken=x;function S(){r.state.tokens.push(new t.Token),r.state.start=r.state.pos,l()}})),Yd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=wd(),n=K(),r=vd(),i=Xd(),a=Zd(),o=qd();function s(e){if(t.match.call(void 0,n.TokenType.question)){let e=t.lookaheadType.call(void 0);if(e===n.TokenType.colon||e===n.TokenType.comma||e===n.TokenType.parenR)return}i.baseParseConditional.call(void 0,e)}e.typedParseConditional=s;function c(){t.eatTypeToken.call(void 0,n.TokenType.question),t.match.call(void 0,n.TokenType.colon)&&(r.isTypeScriptEnabled?o.tsParseTypeAnnotation.call(void 0):r.isFlowEnabled&&a.flowParseTypeAnnotation.call(void 0))}e.typedParseParenItem=c})),Xd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Zd(),n=Jd(),r=Yd(),i=qd(),a=wd(),o=hd(),s=gd(),c=K(),l=_d(),u=xd(),d=vd(),f=Kd(),p=Qd(),m=yd(),h=class{constructor(e){this.stop=e}};e.StopState=h;function g(e=!1){if(_(e),a.match.call(void 0,c.TokenType.comma))for(;a.eat.call(void 0,c.TokenType.comma);)_(e)}e.parseExpression=g;function _(e=!1,n=!1){return d.isTypeScriptEnabled?i.tsParseMaybeAssign.call(void 0,e,n):d.isFlowEnabled?t.flowParseMaybeAssign.call(void 0,e,n):v(e,n)}e.parseMaybeAssign=_;function v(e,t){if(a.match.call(void 0,c.TokenType._yield))return ye(),!1;(a.match.call(void 0,c.TokenType.parenL)||a.match.call(void 0,c.TokenType.name)||a.match.call(void 0,c.TokenType._yield))&&(d.state.potentialArrowAt=d.state.start);let n=y(e);return t&&B(),d.state.type&c.TokenType.IS_ASSIGN?(a.next.call(void 0),_(e),!1):n}e.baseParseMaybeAssign=v;function y(e){return S(e)?!0:(b(e),!1)}function b(e){d.isTypeScriptEnabled||d.isFlowEnabled?r.typedParseConditional.call(void 0,e):x(e)}function x(e){a.eat.call(void 0,c.TokenType.question)&&(_(),m.expect.call(void 0,c.TokenType.colon),_(e))}e.baseParseConditional=x;function S(e){let t=d.state.tokens.length;return w()?!0:(C(t,-1,e),!1)}function C(e,t,n){if(d.isTypeScriptEnabled&&(c.TokenType._in&c.TokenType.PRECEDENCE_MASK)>t&&!m.hasPrecedingLineBreak.call(void 0)&&(m.eatContextual.call(void 0,o.ContextualKeyword._as)||m.eatContextual.call(void 0,o.ContextualKeyword._satisfies))){let r=a.pushTypeContext.call(void 0,1);i.tsParseType.call(void 0),a.popTypeContext.call(void 0,r),a.rescan_gt.call(void 0),C(e,t,n);return}let r=d.state.type&c.TokenType.PRECEDENCE_MASK;if(r>0&&(!n||!a.match.call(void 0,c.TokenType._in))&&r>t){let i=d.state.type;a.next.call(void 0),i===c.TokenType.nullishCoalescing&&(d.state.tokens[d.state.tokens.length-1].nullishStartIndex=e);let o=d.state.tokens.length;w(),C(o,i&c.TokenType.IS_RIGHT_ASSOCIATIVE?r-1:r,n),i===c.TokenType.nullishCoalescing&&(d.state.tokens[e].numNullishCoalesceStarts++,d.state.tokens[d.state.tokens.length-1].numNullishCoalesceEnds++),C(e,t,n)}}function w(){if(d.isTypeScriptEnabled&&!d.isJSXEnabled&&a.eat.call(void 0,c.TokenType.lessThan))return i.tsParseTypeAssertion.call(void 0),!1;if(m.isContextual.call(void 0,o.ContextualKeyword._module)&&a.lookaheadCharCode.call(void 0)===l.charCodes.leftCurlyBrace&&!m.hasFollowingLineBreak.call(void 0))return be(),!1;if(d.state.type&c.TokenType.IS_PREFIX)return a.next.call(void 0),w(),!1;if(T())return!0;for(;d.state.type&c.TokenType.IS_POSTFIX&&!m.canInsertSemicolon.call(void 0);)d.state.type===c.TokenType.preIncDec&&(d.state.type=c.TokenType.postIncDec),a.next.call(void 0);return!1}e.parseMaybeUnary=w;function T(){let e=d.state.tokens.length;return P()?!0:(E(e),d.state.tokens.length>e&&d.state.tokens[e].isOptionalChainStart&&(d.state.tokens[d.state.tokens.length-1].isOptionalChainEnd=!0),!1)}e.parseExprSubscripts=T;function E(e,n=!1){d.isFlowEnabled?t.flowParseSubscripts.call(void 0,e,n):D(e,n)}function D(e,t=!1){let n=new h(!1);do O(e,t,n);while(!n.stop&&!d.state.error)}e.baseParseSubscripts=D;function O(e,n,r){d.isTypeScriptEnabled?i.tsParseSubscript.call(void 0,e,n,r):d.isFlowEnabled?t.flowParseSubscript.call(void 0,e,n,r):k(e,n,r)}function k(e,t,n){if(!t&&a.eat.call(void 0,c.TokenType.doubleColon))N(),n.stop=!0,E(e,t);else if(a.match.call(void 0,c.TokenType.questionDot)){if(d.state.tokens[e].isOptionalChainStart=!0,t&&a.lookaheadType.call(void 0)===c.TokenType.parenL){n.stop=!0;return}a.next.call(void 0),d.state.tokens[d.state.tokens.length-1].subscriptStartIndex=e,a.eat.call(void 0,c.TokenType.bracketL)?(g(),m.expect.call(void 0,c.TokenType.bracketR)):a.eat.call(void 0,c.TokenType.parenL)?j():F()}else if(a.eat.call(void 0,c.TokenType.dot))d.state.tokens[d.state.tokens.length-1].subscriptStartIndex=e,F();else if(a.eat.call(void 0,c.TokenType.bracketL))d.state.tokens[d.state.tokens.length-1].subscriptStartIndex=e,g(),m.expect.call(void 0,c.TokenType.bracketR);else if(!t&&a.match.call(void 0,c.TokenType.parenL)){if(A()){let t=d.state.snapshot(),r=d.state.tokens.length;a.next.call(void 0),d.state.tokens[d.state.tokens.length-1].subscriptStartIndex=e;let i=d.getNextContextId.call(void 0);d.state.tokens[d.state.tokens.length-1].contextId=i,j(),d.state.tokens[d.state.tokens.length-1].contextId=i,ee()&&(d.state.restoreFromSnapshot(t),n.stop=!0,d.state.scopeDepth++,p.parseFunctionParams.call(void 0),M(r))}else{a.next.call(void 0),d.state.tokens[d.state.tokens.length-1].subscriptStartIndex=e;let t=d.getNextContextId.call(void 0);d.state.tokens[d.state.tokens.length-1].contextId=t,j(),d.state.tokens[d.state.tokens.length-1].contextId=t}}else a.match.call(void 0,c.TokenType.backQuote)?ae():n.stop=!0}e.baseParseSubscript=k;function A(){return d.state.tokens[d.state.tokens.length-1].contextualKeyword===o.ContextualKeyword._async&&!m.canInsertSemicolon.call(void 0)}e.atPossibleAsync=A;function j(){let e=!0;for(;!a.eat.call(void 0,c.TokenType.parenR)&&!d.state.error;){if(e)e=!1;else if(m.expect.call(void 0,c.TokenType.comma),a.eat.call(void 0,c.TokenType.parenR))break;ge(!1)}}e.parseCallExpressionArguments=j;function ee(){return a.match.call(void 0,c.TokenType.colon)||a.match.call(void 0,c.TokenType.arrow)}function M(e){d.isTypeScriptEnabled?i.tsStartParseAsyncArrowFromCallExpression.call(void 0):d.isFlowEnabled&&t.flowStartParseAsyncArrowFromCallExpression.call(void 0),m.expect.call(void 0,c.TokenType.arrow),fe(e)}function N(){let e=d.state.tokens.length;P(),E(e,!0)}function P(){if(a.eat.call(void 0,c.TokenType.modulo))return _e(),!1;if(a.match.call(void 0,c.TokenType.jsxText)||a.match.call(void 0,c.TokenType.jsxEmptyText))return L(),!1;if(a.match.call(void 0,c.TokenType.lessThan)&&d.isJSXEnabled)return d.state.type=c.TokenType.jsxTagStart,n.jsxParseElement.call(void 0),a.next.call(void 0),!1;let e=d.state.potentialArrowAt===d.state.start;switch(d.state.type){case c.TokenType.slash:case c.TokenType.assign:a.retokenizeSlashAsRegex.call(void 0);case c.TokenType._super:case c.TokenType._this:case c.TokenType.regexp:case c.TokenType.num:case c.TokenType.bigint:case c.TokenType.decimal:case c.TokenType.string:case c.TokenType._null:case c.TokenType._true:case c.TokenType._false:return a.next.call(void 0),!1;case c.TokenType._import:return a.next.call(void 0),a.match.call(void 0,c.TokenType.dot)&&(d.state.tokens[d.state.tokens.length-1].type=c.TokenType.name,a.next.call(void 0),_e()),!1;case c.TokenType.name:{let t=d.state.tokens.length,n=d.state.start,r=d.state.contextualKeyword;return _e(),r===o.ContextualKeyword._await?(ve(),!1):r===o.ContextualKeyword._async&&a.match.call(void 0,c.TokenType._function)&&!m.canInsertSemicolon.call(void 0)?(a.next.call(void 0),p.parseFunction.call(void 0,n,!1),!1):e&&r===o.ContextualKeyword._async&&!m.canInsertSemicolon.call(void 0)&&a.match.call(void 0,c.TokenType.name)?(d.state.scopeDepth++,f.parseBindingIdentifier.call(void 0,!1),m.expect.call(void 0,c.TokenType.arrow),fe(t),!0):a.match.call(void 0,c.TokenType._do)&&!m.canInsertSemicolon.call(void 0)?(a.next.call(void 0),p.parseBlock.call(void 0),!1):e&&!m.canInsertSemicolon.call(void 0)&&a.match.call(void 0,c.TokenType.arrow)?(d.state.scopeDepth++,f.markPriorBindingIdentifier.call(void 0,!1),m.expect.call(void 0,c.TokenType.arrow),fe(t),!0):(d.state.tokens[d.state.tokens.length-1].identifierRole=a.IdentifierRole.Access,!1)}case c.TokenType._do:return a.next.call(void 0),p.parseBlock.call(void 0),!1;case c.TokenType.parenL:return R(e);case c.TokenType.bracketL:return a.next.call(void 0),he(c.TokenType.bracketR,!0),!1;case c.TokenType.braceL:return oe(!1,!1),!1;case c.TokenType._function:return I(),!1;case c.TokenType.at:p.parseDecorators.call(void 0);case c.TokenType._class:return p.parseClass.call(void 0,!1),!1;case c.TokenType._new:return re(),!1;case c.TokenType.backQuote:return ae(),!1;case c.TokenType.doubleColon:return a.next.call(void 0),N(),!1;case c.TokenType.hash:{let e=a.lookaheadCharCode.call(void 0);return u.IS_IDENTIFIER_START[e]||e===l.charCodes.backslash?F():a.next.call(void 0),!1}default:return m.unexpected.call(void 0),!1}}e.parseExprAtom=P;function F(){a.eat.call(void 0,c.TokenType.hash),_e()}function I(){let e=d.state.start;_e(),a.eat.call(void 0,c.TokenType.dot)&&_e(),p.parseFunction.call(void 0,e,!1)}function L(){a.next.call(void 0)}e.parseLiteral=L;function te(){m.expect.call(void 0,c.TokenType.parenL),g(),m.expect.call(void 0,c.TokenType.parenR)}e.parseParenExpression=te;function R(e){let t=d.state.snapshot(),n=d.state.tokens.length;m.expect.call(void 0,c.TokenType.parenL);let r=!0;for(;!a.match.call(void 0,c.TokenType.parenR)&&!d.state.error;){if(r)r=!1;else if(m.expect.call(void 0,c.TokenType.comma),a.match.call(void 0,c.TokenType.parenR))break;if(a.match.call(void 0,c.TokenType.ellipsis)){f.parseRest.call(void 0,!1),B();break}_(!1,!0)}return m.expect.call(void 0,c.TokenType.parenR),e&&ne()&&z()?(d.state.restoreFromSnapshot(t),d.state.scopeDepth++,p.parseFunctionParams.call(void 0),z(),fe(n),!d.state.error||(d.state.restoreFromSnapshot(t),R(!1),!1)):!1}function ne(){return a.match.call(void 0,c.TokenType.colon)||!m.canInsertSemicolon.call(void 0)}function z(){return d.isTypeScriptEnabled?i.tsParseArrow.call(void 0):d.isFlowEnabled?t.flowParseArrow.call(void 0):a.eat.call(void 0,c.TokenType.arrow)}e.parseArrow=z;function B(){(d.isTypeScriptEnabled||d.isFlowEnabled)&&r.typedParseParenItem.call(void 0)}function re(){m.expect.call(void 0,c.TokenType._new),a.eat.call(void 0,c.TokenType.dot)?_e():(ie(),d.isFlowEnabled&&t.flowStartParseNewArguments.call(void 0),a.eat.call(void 0,c.TokenType.parenL)&&he(c.TokenType.parenR))}function ie(){N(),a.eat.call(void 0,c.TokenType.questionDot)}function ae(){for(a.nextTemplateToken.call(void 0),a.nextTemplateToken.call(void 0);!a.match.call(void 0,c.TokenType.backQuote)&&!d.state.error;)m.expect.call(void 0,c.TokenType.dollarBraceL),g(),a.nextTemplateToken.call(void 0),a.nextTemplateToken.call(void 0);a.next.call(void 0)}e.parseTemplate=ae;function oe(e,t){let n=d.getNextContextId.call(void 0),r=!0;for(a.next.call(void 0),d.state.tokens[d.state.tokens.length-1].contextId=n;!a.eat.call(void 0,c.TokenType.braceR)&&!d.state.error;){if(r)r=!1;else if(m.expect.call(void 0,c.TokenType.comma),a.eat.call(void 0,c.TokenType.braceR))break;let i=!1;if(a.match.call(void 0,c.TokenType.ellipsis)){let n=d.state.tokens.length;if(f.parseSpread.call(void 0),e&&(d.state.tokens.length===n+2&&f.markPriorBindingIdentifier.call(void 0,t),a.eat.call(void 0,c.TokenType.braceR)))break}else e||(i=a.eat.call(void 0,c.TokenType.star)),!e&&m.isContextual.call(void 0,o.ContextualKeyword._async)?(i&&m.unexpected.call(void 0),_e(),a.match.call(void 0,c.TokenType.colon)||a.match.call(void 0,c.TokenType.parenL)||a.match.call(void 0,c.TokenType.braceR)||a.match.call(void 0,c.TokenType.eq)||a.match.call(void 0,c.TokenType.comma)||(a.match.call(void 0,c.TokenType.star)&&(a.next.call(void 0),i=!0),ue(n))):ue(n),V(e,t,n)}d.state.tokens[d.state.tokens.length-1].contextId=n}e.parseObj=oe;function se(e){return!e&&(a.match.call(void 0,c.TokenType.string)||a.match.call(void 0,c.TokenType.num)||a.match.call(void 0,c.TokenType.bracketL)||a.match.call(void 0,c.TokenType.name)||!!(d.state.type&c.TokenType.IS_KEYWORD))}function ce(e,t){let n=d.state.start;return a.match.call(void 0,c.TokenType.parenL)?(e&&m.unexpected.call(void 0),de(n,!1),!0):se(e)?(ue(t),de(n,!1),!0):!1}function le(e,t){if(a.eat.call(void 0,c.TokenType.colon)){e?f.parseMaybeDefault.call(void 0,t):_(!1);return}let n;n=e?d.state.scopeDepth===0?a.IdentifierRole.ObjectShorthandTopLevelDeclaration:t?a.IdentifierRole.ObjectShorthandBlockScopedDeclaration:a.IdentifierRole.ObjectShorthandFunctionScopedDeclaration:a.IdentifierRole.ObjectShorthand,d.state.tokens[d.state.tokens.length-1].identifierRole=n,f.parseMaybeDefault.call(void 0,t,!0)}function V(e,n,r){d.isTypeScriptEnabled?i.tsStartParseObjPropValue.call(void 0):d.isFlowEnabled&&t.flowStartParseObjPropValue.call(void 0),ce(e,r)||le(e,n)}function ue(e){d.isFlowEnabled&&t.flowParseVariance.call(void 0),a.eat.call(void 0,c.TokenType.bracketL)?(d.state.tokens[d.state.tokens.length-1].contextId=e,_(),m.expect.call(void 0,c.TokenType.bracketR),d.state.tokens[d.state.tokens.length-1].contextId=e):(a.match.call(void 0,c.TokenType.num)||a.match.call(void 0,c.TokenType.string)||a.match.call(void 0,c.TokenType.bigint)||a.match.call(void 0,c.TokenType.decimal)?P():F(),d.state.tokens[d.state.tokens.length-1].identifierRole=a.IdentifierRole.ObjectKey,d.state.tokens[d.state.tokens.length-1].contextId=e)}e.parsePropertyName=ue;function de(e,t){let n=d.getNextContextId.call(void 0);d.state.scopeDepth++;let r=d.state.tokens.length,i=t;p.parseFunctionParams.call(void 0,i,n),pe(e,n);let a=d.state.tokens.length;d.state.scopes.push(new s.Scope(r,a,!0)),d.state.scopeDepth--}e.parseMethod=de;function fe(e){me(!0);let t=d.state.tokens.length;d.state.scopes.push(new s.Scope(e,t,!0)),d.state.scopeDepth--}e.parseArrowExpression=fe;function pe(e,n=0){d.isTypeScriptEnabled?i.tsParseFunctionBodyAndFinish.call(void 0,e,n):d.isFlowEnabled?t.flowParseFunctionBodyAndFinish.call(void 0,n):me(!1,n)}e.parseFunctionBodyAndFinish=pe;function me(e,t=0){e&&!a.match.call(void 0,c.TokenType.braceL)?_():p.parseBlock.call(void 0,!0,t)}e.parseFunctionBody=me;function he(e,t=!1){let n=!0;for(;!a.eat.call(void 0,e)&&!d.state.error;){if(n)n=!1;else if(m.expect.call(void 0,c.TokenType.comma),a.eat.call(void 0,e))break;ge(t)}}function ge(e){e&&a.match.call(void 0,c.TokenType.comma)||(a.match.call(void 0,c.TokenType.ellipsis)?(f.parseSpread.call(void 0),B()):a.match.call(void 0,c.TokenType.question)?a.next.call(void 0):_(!1,!0))}function _e(){a.next.call(void 0),d.state.tokens[d.state.tokens.length-1].type=c.TokenType.name}e.parseIdentifier=_e;function ve(){w()}function ye(){a.next.call(void 0),!a.match.call(void 0,c.TokenType.semi)&&!m.canInsertSemicolon.call(void 0)&&(a.eat.call(void 0,c.TokenType.star),_())}function be(){m.expectContextual.call(void 0,o.ContextualKeyword._module),m.expect.call(void 0,c.TokenType.braceL),p.parseBlockBody.call(void 0,c.TokenType.braceR)}})),Zd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=wd(),n=hd(),r=K(),i=vd(),a=Xd(),o=Qd(),s=yd();function c(e){return(e.type===r.TokenType.name||!!(e.type&r.TokenType.IS_KEYWORD))&&e.contextualKeyword!==n.ContextualKeyword._from}function l(e){let n=t.pushTypeContext.call(void 0,0);s.expect.call(void 0,e||r.TokenType.colon),ue(),t.popTypeContext.call(void 0,n)}function u(){s.expect.call(void 0,r.TokenType.modulo),s.expectContextual.call(void 0,n.ContextualKeyword._checks),t.eat.call(void 0,r.TokenType.parenL)&&(a.parseExpression.call(void 0),s.expect.call(void 0,r.TokenType.parenR))}function d(){let e=t.pushTypeContext.call(void 0,0);s.expect.call(void 0,r.TokenType.colon),t.match.call(void 0,r.TokenType.modulo)?u():(ue(),t.match.call(void 0,r.TokenType.modulo)&&u()),t.popTypeContext.call(void 0,e)}function f(){t.next.call(void 0),S(!0)}function p(){t.next.call(void 0),a.parseIdentifier.call(void 0),t.match.call(void 0,r.TokenType.lessThan)&&k(),s.expect.call(void 0,r.TokenType.parenL),ie(),s.expect.call(void 0,r.TokenType.parenR),d(),s.semicolon.call(void 0)}function m(){t.match.call(void 0,r.TokenType._class)?f():t.match.call(void 0,r.TokenType._function)?p():t.match.call(void 0,r.TokenType._var)?h():s.eatContextual.call(void 0,n.ContextualKeyword._module)?t.eat.call(void 0,r.TokenType.dot)?v():g():s.isContextual.call(void 0,n.ContextualKeyword._type)?y():s.isContextual.call(void 0,n.ContextualKeyword._opaque)?b():s.isContextual.call(void 0,n.ContextualKeyword._interface)?x():t.match.call(void 0,r.TokenType._export)?_():s.unexpected.call(void 0)}function h(){t.next.call(void 0),fe(),s.semicolon.call(void 0)}function g(){for(t.match.call(void 0,r.TokenType.string)?a.parseExprAtom.call(void 0):a.parseIdentifier.call(void 0),s.expect.call(void 0,r.TokenType.braceL);!t.match.call(void 0,r.TokenType.braceR)&&!i.state.error;)t.match.call(void 0,r.TokenType._import)?(t.next.call(void 0),o.parseImport.call(void 0)):s.unexpected.call(void 0);s.expect.call(void 0,r.TokenType.braceR)}function _(){s.expect.call(void 0,r.TokenType._export),t.eat.call(void 0,r.TokenType._default)?t.match.call(void 0,r.TokenType._function)||t.match.call(void 0,r.TokenType._class)?m():(ue(),s.semicolon.call(void 0)):t.match.call(void 0,r.TokenType._var)||t.match.call(void 0,r.TokenType._function)||t.match.call(void 0,r.TokenType._class)||s.isContextual.call(void 0,n.ContextualKeyword._opaque)?m():t.match.call(void 0,r.TokenType.star)||t.match.call(void 0,r.TokenType.braceL)||s.isContextual.call(void 0,n.ContextualKeyword._interface)||s.isContextual.call(void 0,n.ContextualKeyword._type)||s.isContextual.call(void 0,n.ContextualKeyword._opaque)?o.parseExport.call(void 0):s.unexpected.call(void 0)}function v(){s.expectContextual.call(void 0,n.ContextualKeyword._exports),de(),s.semicolon.call(void 0)}function y(){t.next.call(void 0),E()}function b(){t.next.call(void 0),D(!0)}function x(){t.next.call(void 0),S()}function S(e=!1){if(T(),t.match.call(void 0,r.TokenType.lessThan)&&k(),t.eat.call(void 0,r.TokenType._extends))do C();while(!e&&t.eat.call(void 0,r.TokenType.comma));if(s.isContextual.call(void 0,n.ContextualKeyword._mixins)){t.next.call(void 0);do C();while(t.eat.call(void 0,r.TokenType.comma))}if(s.isContextual.call(void 0,n.ContextualKeyword._implements)){t.next.call(void 0);do C();while(t.eat.call(void 0,r.TokenType.comma))}I(e,!1,e)}function C(){R(!1),t.match.call(void 0,r.TokenType.lessThan)&&A()}function w(){S()}function T(){a.parseIdentifier.call(void 0)}function E(){T(),t.match.call(void 0,r.TokenType.lessThan)&&k(),l(r.TokenType.eq),s.semicolon.call(void 0)}function D(e){s.expectContextual.call(void 0,n.ContextualKeyword._type),T(),t.match.call(void 0,r.TokenType.lessThan)&&k(),t.match.call(void 0,r.TokenType.colon)&&l(r.TokenType.colon),e||l(r.TokenType.eq),s.semicolon.call(void 0)}function O(){pe(),fe(),t.eat.call(void 0,r.TokenType.eq)&&ue()}function k(){let e=t.pushTypeContext.call(void 0,0);
234
- // istanbul ignore else: this condition is already checked at all call sites
235
- t.match.call(void 0,r.TokenType.lessThan)||t.match.call(void 0,r.TokenType.typeParameterStart)?t.next.call(void 0):s.unexpected.call(void 0);do O(),t.match.call(void 0,r.TokenType.greaterThan)||s.expect.call(void 0,r.TokenType.comma);while(!t.match.call(void 0,r.TokenType.greaterThan)&&!i.state.error);s.expect.call(void 0,r.TokenType.greaterThan),t.popTypeContext.call(void 0,e)}e.flowParseTypeParameterDeclaration=k;function A(){let e=t.pushTypeContext.call(void 0,0);for(s.expect.call(void 0,r.TokenType.lessThan);!t.match.call(void 0,r.TokenType.greaterThan)&&!i.state.error;)ue(),t.match.call(void 0,r.TokenType.greaterThan)||s.expect.call(void 0,r.TokenType.comma);s.expect.call(void 0,r.TokenType.greaterThan),t.popTypeContext.call(void 0,e)}function j(){if(s.expectContextual.call(void 0,n.ContextualKeyword._interface),t.eat.call(void 0,r.TokenType._extends))do C();while(t.eat.call(void 0,r.TokenType.comma));I(!1,!1,!1)}function ee(){t.match.call(void 0,r.TokenType.num)||t.match.call(void 0,r.TokenType.string)?a.parseExprAtom.call(void 0):a.parseIdentifier.call(void 0)}function M(){t.lookaheadType.call(void 0)===r.TokenType.colon?(ee(),l()):ue(),s.expect.call(void 0,r.TokenType.bracketR),l()}function N(){ee(),s.expect.call(void 0,r.TokenType.bracketR),s.expect.call(void 0,r.TokenType.bracketR),t.match.call(void 0,r.TokenType.lessThan)||t.match.call(void 0,r.TokenType.parenL)?P():(t.eat.call(void 0,r.TokenType.question),l())}function P(){for(t.match.call(void 0,r.TokenType.lessThan)&&k(),s.expect.call(void 0,r.TokenType.parenL);!t.match.call(void 0,r.TokenType.parenR)&&!t.match.call(void 0,r.TokenType.ellipsis)&&!i.state.error;)re(),t.match.call(void 0,r.TokenType.parenR)||s.expect.call(void 0,r.TokenType.comma);t.eat.call(void 0,r.TokenType.ellipsis)&&re(),s.expect.call(void 0,r.TokenType.parenR),l()}function F(){P()}function I(e,a,o){let c;for(a&&t.match.call(void 0,r.TokenType.braceBarL)?(s.expect.call(void 0,r.TokenType.braceBarL),c=r.TokenType.braceBarR):(s.expect.call(void 0,r.TokenType.braceL),c=r.TokenType.braceR);!t.match.call(void 0,c)&&!i.state.error;){if(o&&s.isContextual.call(void 0,n.ContextualKeyword._proto)){let n=t.lookaheadType.call(void 0);n!==r.TokenType.colon&&n!==r.TokenType.question&&(t.next.call(void 0),e=!1)}if(e&&s.isContextual.call(void 0,n.ContextualKeyword._static)){let e=t.lookaheadType.call(void 0);e!==r.TokenType.colon&&e!==r.TokenType.question&&t.next.call(void 0)}if(pe(),t.eat.call(void 0,r.TokenType.bracketL))t.eat.call(void 0,r.TokenType.bracketL)?N():M();else if(t.match.call(void 0,r.TokenType.parenL)||t.match.call(void 0,r.TokenType.lessThan))F();else{if(s.isContextual.call(void 0,n.ContextualKeyword._get)||s.isContextual.call(void 0,n.ContextualKeyword._set)){let e=t.lookaheadType.call(void 0);(e===r.TokenType.name||e===r.TokenType.string||e===r.TokenType.num)&&t.next.call(void 0)}L()}te()}s.expect.call(void 0,c)}function L(){if(t.match.call(void 0,r.TokenType.ellipsis)){if(s.expect.call(void 0,r.TokenType.ellipsis),t.eat.call(void 0,r.TokenType.comma)||t.eat.call(void 0,r.TokenType.semi),t.match.call(void 0,r.TokenType.braceR))return;ue()}else ee(),t.match.call(void 0,r.TokenType.lessThan)||t.match.call(void 0,r.TokenType.parenL)?P():(t.eat.call(void 0,r.TokenType.question),l())}function te(){t.eat.call(void 0,r.TokenType.semi)||t.eat.call(void 0,r.TokenType.comma)||t.match.call(void 0,r.TokenType.braceR)||t.match.call(void 0,r.TokenType.braceBarR)||s.unexpected.call(void 0)}function R(e){for(e||a.parseIdentifier.call(void 0);t.eat.call(void 0,r.TokenType.dot);)a.parseIdentifier.call(void 0)}function ne(){R(!0),t.match.call(void 0,r.TokenType.lessThan)&&A()}function z(){s.expect.call(void 0,r.TokenType._typeof),ae()}function B(){for(s.expect.call(void 0,r.TokenType.bracketL);i.state.pos<i.input.length&&!t.match.call(void 0,r.TokenType.bracketR)&&(ue(),!t.match.call(void 0,r.TokenType.bracketR));)s.expect.call(void 0,r.TokenType.comma);s.expect.call(void 0,r.TokenType.bracketR)}function re(){let e=t.lookaheadType.call(void 0);e===r.TokenType.colon||e===r.TokenType.question?(a.parseIdentifier.call(void 0),t.eat.call(void 0,r.TokenType.question),l()):ue()}function ie(){for(;!t.match.call(void 0,r.TokenType.parenR)&&!t.match.call(void 0,r.TokenType.ellipsis)&&!i.state.error;)re(),t.match.call(void 0,r.TokenType.parenR)||s.expect.call(void 0,r.TokenType.comma);t.eat.call(void 0,r.TokenType.ellipsis)&&re()}function ae(){let e=!1,o=i.state.noAnonFunctionType;switch(i.state.type){case r.TokenType.name:if(s.isContextual.call(void 0,n.ContextualKeyword._interface)){j();return}a.parseIdentifier.call(void 0),ne();return;case r.TokenType.braceL:I(!1,!1,!1);return;case r.TokenType.braceBarL:I(!1,!0,!1);return;case r.TokenType.bracketL:B();return;case r.TokenType.lessThan:k(),s.expect.call(void 0,r.TokenType.parenL),ie(),s.expect.call(void 0,r.TokenType.parenR),s.expect.call(void 0,r.TokenType.arrow),ue();return;case r.TokenType.parenL:if(t.next.call(void 0),!t.match.call(void 0,r.TokenType.parenR)&&!t.match.call(void 0,r.TokenType.ellipsis)){if(t.match.call(void 0,r.TokenType.name)){let n=t.lookaheadType.call(void 0);e=n!==r.TokenType.question&&n!==r.TokenType.colon}else e=!0}if(e){if(i.state.noAnonFunctionType=!1,ue(),i.state.noAnonFunctionType=o,i.state.noAnonFunctionType||!(t.match.call(void 0,r.TokenType.comma)||t.match.call(void 0,r.TokenType.parenR)&&t.lookaheadType.call(void 0)===r.TokenType.arrow)){s.expect.call(void 0,r.TokenType.parenR);return}t.eat.call(void 0,r.TokenType.comma)}ie(),s.expect.call(void 0,r.TokenType.parenR),s.expect.call(void 0,r.TokenType.arrow),ue();return;case r.TokenType.minus:t.next.call(void 0),a.parseLiteral.call(void 0);return;case r.TokenType.string:case r.TokenType.num:case r.TokenType._true:case r.TokenType._false:case r.TokenType._null:case r.TokenType._this:case r.TokenType._void:case r.TokenType.star:t.next.call(void 0);return;default:if(i.state.type===r.TokenType._typeof){z();return}if(i.state.type&r.TokenType.IS_KEYWORD){t.next.call(void 0),i.state.tokens[i.state.tokens.length-1].type=r.TokenType.name;return}}s.unexpected.call(void 0)}function oe(){for(ae();!s.canInsertSemicolon.call(void 0)&&(t.match.call(void 0,r.TokenType.bracketL)||t.match.call(void 0,r.TokenType.questionDot));)t.eat.call(void 0,r.TokenType.questionDot),s.expect.call(void 0,r.TokenType.bracketL),t.eat.call(void 0,r.TokenType.bracketR)||(ue(),s.expect.call(void 0,r.TokenType.bracketR))}function se(){t.eat.call(void 0,r.TokenType.question)?se():oe()}function ce(){se(),!i.state.noAnonFunctionType&&t.eat.call(void 0,r.TokenType.arrow)&&ue()}function le(){for(t.eat.call(void 0,r.TokenType.bitwiseAND),ce();t.eat.call(void 0,r.TokenType.bitwiseAND);)ce()}function V(){for(t.eat.call(void 0,r.TokenType.bitwiseOR),le();t.eat.call(void 0,r.TokenType.bitwiseOR);)le()}function ue(){V()}function de(){l()}e.flowParseTypeAnnotation=de;function fe(){a.parseIdentifier.call(void 0),t.match.call(void 0,r.TokenType.colon)&&de()}function pe(){(t.match.call(void 0,r.TokenType.plus)||t.match.call(void 0,r.TokenType.minus))&&(t.next.call(void 0),i.state.tokens[i.state.tokens.length-1].isType=!0)}e.flowParseVariance=pe;function me(e){t.match.call(void 0,r.TokenType.colon)&&d(),a.parseFunctionBody.call(void 0,!1,e)}e.flowParseFunctionBodyAndFinish=me;function he(e,n,o){if(t.match.call(void 0,r.TokenType.questionDot)&&t.lookaheadType.call(void 0)===r.TokenType.lessThan){if(n){o.stop=!0;return}t.next.call(void 0),A(),s.expect.call(void 0,r.TokenType.parenL),a.parseCallExpressionArguments.call(void 0)}else{if(!n&&t.match.call(void 0,r.TokenType.lessThan)){let e=i.state.snapshot();if(A(),s.expect.call(void 0,r.TokenType.parenL),a.parseCallExpressionArguments.call(void 0),i.state.error)i.state.restoreFromSnapshot(e);else return}a.baseParseSubscript.call(void 0,e,n,o)}}e.flowParseSubscript=he;function ge(){if(t.match.call(void 0,r.TokenType.lessThan)){let e=i.state.snapshot();A(),i.state.error&&i.state.restoreFromSnapshot(e)}}e.flowStartParseNewArguments=ge;function _e(){if(t.match.call(void 0,r.TokenType.name)&&i.state.contextualKeyword===n.ContextualKeyword._interface){let e=t.pushTypeContext.call(void 0,0);return t.next.call(void 0),w(),t.popTypeContext.call(void 0,e),!0}return s.isContextual.call(void 0,n.ContextualKeyword._enum)?(Ie(),!0):!1}e.flowTryParseStatement=_e;function ve(){return s.isContextual.call(void 0,n.ContextualKeyword._enum)?(Ie(),!0):!1}e.flowTryParseExportDefaultExpression=ve;function ye(e){if(e===n.ContextualKeyword._declare){if(t.match.call(void 0,r.TokenType._class)||t.match.call(void 0,r.TokenType.name)||t.match.call(void 0,r.TokenType._function)||t.match.call(void 0,r.TokenType._var)||t.match.call(void 0,r.TokenType._export)){let e=t.pushTypeContext.call(void 0,1);m(),t.popTypeContext.call(void 0,e)}}else if(t.match.call(void 0,r.TokenType.name)){if(e===n.ContextualKeyword._interface){let e=t.pushTypeContext.call(void 0,1);w(),t.popTypeContext.call(void 0,e)}else if(e===n.ContextualKeyword._type){let e=t.pushTypeContext.call(void 0,1);E(),t.popTypeContext.call(void 0,e)}else if(e===n.ContextualKeyword._opaque){let e=t.pushTypeContext.call(void 0,1);D(!1),t.popTypeContext.call(void 0,e)}}s.semicolon.call(void 0)}e.flowParseIdentifierStatement=ye;function be(){return s.isContextual.call(void 0,n.ContextualKeyword._type)||s.isContextual.call(void 0,n.ContextualKeyword._interface)||s.isContextual.call(void 0,n.ContextualKeyword._opaque)||s.isContextual.call(void 0,n.ContextualKeyword._enum)}e.flowShouldParseExportDeclaration=be;function xe(){return t.match.call(void 0,r.TokenType.name)&&(i.state.contextualKeyword===n.ContextualKeyword._type||i.state.contextualKeyword===n.ContextualKeyword._interface||i.state.contextualKeyword===n.ContextualKeyword._opaque||i.state.contextualKeyword===n.ContextualKeyword._enum)}e.flowShouldDisallowExportDefaultSpecifier=xe;function Se(){if(s.isContextual.call(void 0,n.ContextualKeyword._type)){let e=t.pushTypeContext.call(void 0,1);t.next.call(void 0),t.match.call(void 0,r.TokenType.braceL)?(o.parseExportSpecifiers.call(void 0),o.parseExportFrom.call(void 0)):E(),t.popTypeContext.call(void 0,e)}else if(s.isContextual.call(void 0,n.ContextualKeyword._opaque)){let e=t.pushTypeContext.call(void 0,1);t.next.call(void 0),D(!1),t.popTypeContext.call(void 0,e)}else if(s.isContextual.call(void 0,n.ContextualKeyword._interface)){let e=t.pushTypeContext.call(void 0,1);t.next.call(void 0),w(),t.popTypeContext.call(void 0,e)}else o.parseStatement.call(void 0,!0)}e.flowParseExportDeclaration=Se;function Ce(){return t.match.call(void 0,r.TokenType.star)||s.isContextual.call(void 0,n.ContextualKeyword._type)&&t.lookaheadType.call(void 0)===r.TokenType.star}e.flowShouldParseExportStar=Ce;function we(){if(s.eatContextual.call(void 0,n.ContextualKeyword._type)){let e=t.pushTypeContext.call(void 0,2);o.baseParseExportStar.call(void 0),t.popTypeContext.call(void 0,e)}else o.baseParseExportStar.call(void 0)}e.flowParseExportStar=we;function H(e){if(e&&t.match.call(void 0,r.TokenType.lessThan)&&A(),s.isContextual.call(void 0,n.ContextualKeyword._implements)){let e=t.pushTypeContext.call(void 0,0);t.next.call(void 0),i.state.tokens[i.state.tokens.length-1].type=r.TokenType._implements;do T(),t.match.call(void 0,r.TokenType.lessThan)&&A();while(t.eat.call(void 0,r.TokenType.comma));t.popTypeContext.call(void 0,e)}}e.flowAfterParseClassSuper=H;function Te(){t.match.call(void 0,r.TokenType.lessThan)&&(k(),t.match.call(void 0,r.TokenType.parenL)||s.unexpected.call(void 0))}e.flowStartParseObjPropValue=Te;function Ee(){let e=t.pushTypeContext.call(void 0,0);t.eat.call(void 0,r.TokenType.question),t.match.call(void 0,r.TokenType.colon)&&de(),t.popTypeContext.call(void 0,e)}e.flowParseAssignableListItemTypes=Ee;function De(){if(t.match.call(void 0,r.TokenType._typeof)||s.isContextual.call(void 0,n.ContextualKeyword._type)){let e=t.lookaheadTypeAndKeyword.call(void 0);(c(e)||e.type===r.TokenType.braceL||e.type===r.TokenType.star)&&t.next.call(void 0)}}e.flowStartParseImportSpecifiers=De;function Oe(){let e=i.state.contextualKeyword===n.ContextualKeyword._type||i.state.type===r.TokenType._typeof;e?t.next.call(void 0):a.parseIdentifier.call(void 0),s.isContextual.call(void 0,n.ContextualKeyword._as)&&!s.isLookaheadContextual.call(void 0,n.ContextualKeyword._as)?(a.parseIdentifier.call(void 0),e&&!t.match.call(void 0,r.TokenType.name)&&!(i.state.type&r.TokenType.IS_KEYWORD)||a.parseIdentifier.call(void 0)):(e&&(t.match.call(void 0,r.TokenType.name)||i.state.type&r.TokenType.IS_KEYWORD)&&a.parseIdentifier.call(void 0),s.eatContextual.call(void 0,n.ContextualKeyword._as)&&a.parseIdentifier.call(void 0))}e.flowParseImportSpecifier=Oe;function ke(){if(t.match.call(void 0,r.TokenType.lessThan)){let e=t.pushTypeContext.call(void 0,0);k(),t.popTypeContext.call(void 0,e)}}e.flowStartParseFunctionParams=ke;function Ae(){t.match.call(void 0,r.TokenType.colon)&&de()}e.flowAfterParseVarHead=Ae;function je(){if(t.match.call(void 0,r.TokenType.colon)){let e=i.state.noAnonFunctionType;i.state.noAnonFunctionType=!0,de(),i.state.noAnonFunctionType=e}}e.flowStartParseAsyncArrowFromCallExpression=je;function Me(e,n){if(t.match.call(void 0,r.TokenType.lessThan)){let o=i.state.snapshot(),c=a.baseParseMaybeAssign.call(void 0,e,n);if(i.state.error)i.state.restoreFromSnapshot(o),i.state.type=r.TokenType.typeParameterStart;else return c;let l=t.pushTypeContext.call(void 0,0);if(k(),t.popTypeContext.call(void 0,l),c=a.baseParseMaybeAssign.call(void 0,e,n),c)return!0;s.unexpected.call(void 0)}return a.baseParseMaybeAssign.call(void 0,e,n)}e.flowParseMaybeAssign=Me;function Ne(){if(t.match.call(void 0,r.TokenType.colon)){let e=t.pushTypeContext.call(void 0,0),n=i.state.snapshot(),a=i.state.noAnonFunctionType;i.state.noAnonFunctionType=!0,d(),i.state.noAnonFunctionType=a,s.canInsertSemicolon.call(void 0)&&s.unexpected.call(void 0),t.match.call(void 0,r.TokenType.arrow)||s.unexpected.call(void 0),i.state.error&&i.state.restoreFromSnapshot(n),t.popTypeContext.call(void 0,e)}return t.eat.call(void 0,r.TokenType.arrow)}e.flowParseArrow=Ne;function Pe(e,o=!1){if(i.state.tokens[i.state.tokens.length-1].contextualKeyword===n.ContextualKeyword._async&&t.match.call(void 0,r.TokenType.lessThan)){let e=i.state.snapshot();if(Fe()&&!i.state.error)return;i.state.restoreFromSnapshot(e)}a.baseParseSubscripts.call(void 0,e,o)}e.flowParseSubscripts=Pe;function Fe(){i.state.scopeDepth++;let e=i.state.tokens.length;return o.parseFunctionParams.call(void 0),a.parseArrow.call(void 0)?(a.parseArrowExpression.call(void 0,e),!0):!1}function Ie(){s.expectContextual.call(void 0,n.ContextualKeyword._enum),i.state.tokens[i.state.tokens.length-1].type=r.TokenType._enum,a.parseIdentifier.call(void 0),Le()}function Le(){s.eatContextual.call(void 0,n.ContextualKeyword._of)&&t.next.call(void 0),s.expect.call(void 0,r.TokenType.braceL),Re(),s.expect.call(void 0,r.TokenType.braceR)}function Re(){for(;!t.match.call(void 0,r.TokenType.braceR)&&!i.state.error&&!t.eat.call(void 0,r.TokenType.ellipsis);)ze(),t.match.call(void 0,r.TokenType.braceR)||s.expect.call(void 0,r.TokenType.comma)}function ze(){a.parseIdentifier.call(void 0),t.eat.call(void 0,r.TokenType.eq)&&t.next.call(void 0)}})),Qd=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=ef(),n=Zd(),r=qd(),i=wd(),a=hd(),o=gd(),s=K(),c=_d(),l=vd(),u=Xd(),d=Kd(),f=yd();function p(){if(R(s.TokenType.eof),l.state.scopes.push(new o.Scope(0,l.state.tokens.length,!0)),l.state.scopeDepth!==0)throw Error(`Invalid scope depth at end of file: ${l.state.scopeDepth}`);return new t.File(l.state.tokens,l.state.scopes)}e.parseTopLevel=p;function m(e){l.isFlowEnabled&&n.flowTryParseStatement.call(void 0)||(i.match.call(void 0,s.TokenType.at)&&_(),h(e))}e.parseStatement=m;function h(e){if(l.isTypeScriptEnabled&&r.tsTryParseStatementContent.call(void 0))return;let t=l.state.type;switch(t){case s.TokenType._break:case s.TokenType._continue:x();return;case s.TokenType._debugger:S();return;case s.TokenType._do:C();return;case s.TokenType._for:w();return;case s.TokenType._function:if(i.lookaheadType.call(void 0)===s.TokenType.dot)break;e||f.unexpected.call(void 0),D();return;case s.TokenType._class:e||f.unexpected.call(void 0),oe(!0);return;case s.TokenType._if:O();return;case s.TokenType._return:k();return;case s.TokenType._switch:A();return;case s.TokenType._throw:j();return;case s.TokenType._try:M();return;case s.TokenType._let:case s.TokenType._const:e||f.unexpected.call(void 0);case s.TokenType._var:N(t!==s.TokenType._var);return;case s.TokenType._while:P();return;case s.TokenType.braceL:te();return;case s.TokenType.semi:F();return;case s.TokenType._export:case s.TokenType._import:{let e=i.lookaheadType.call(void 0);if(e===s.TokenType.parenL||e===s.TokenType.dot)break;i.next.call(void 0),t===s.TokenType._import?je():_e();return}case s.TokenType.name:if(l.state.contextualKeyword===a.ContextualKeyword._async){let e=l.state.start,t=l.state.snapshot();if(i.next.call(void 0),i.match.call(void 0,s.TokenType._function)&&!f.canInsertSemicolon.call(void 0)){f.expect.call(void 0,s.TokenType._function),ie(e,!0);return}l.state.restoreFromSnapshot(t)}else if(l.state.contextualKeyword===a.ContextualKeyword._using&&!f.hasFollowingLineBreak.call(void 0)&&i.lookaheadType.call(void 0)===s.TokenType.name){N(!0);return}else if(g()){f.expectContextual.call(void 0,a.ContextualKeyword._await),N(!0);return}}let n=l.state.tokens.length;u.parseExpression.call(void 0);let o=null;if(l.state.tokens.length===n+1){let e=l.state.tokens[l.state.tokens.length-1];e.type===s.TokenType.name&&(o=e.contextualKeyword)}o==null?f.semicolon.call(void 0):i.eat.call(void 0,s.TokenType.colon)?I():L(o)}function g(){if(!f.isContextual.call(void 0,a.ContextualKeyword._await))return!1;let e=l.state.snapshot();return i.next.call(void 0),!f.isContextual.call(void 0,a.ContextualKeyword._using)||f.hasPrecedingLineBreak.call(void 0)||(i.next.call(void 0),!i.match.call(void 0,s.TokenType.name)||f.hasPrecedingLineBreak.call(void 0))?(l.state.restoreFromSnapshot(e),!1):(l.state.restoreFromSnapshot(e),!0)}function _(){for(;i.match.call(void 0,s.TokenType.at);)v()}e.parseDecorators=_;function v(){if(i.next.call(void 0),i.eat.call(void 0,s.TokenType.parenL))u.parseExpression.call(void 0),f.expect.call(void 0,s.TokenType.parenR);else{for(u.parseIdentifier.call(void 0);i.eat.call(void 0,s.TokenType.dot);)u.parseIdentifier.call(void 0);y()}}function y(){l.isTypeScriptEnabled?r.tsParseMaybeDecoratorArguments.call(void 0):b()}function b(){i.eat.call(void 0,s.TokenType.parenL)&&u.parseCallExpressionArguments.call(void 0)}e.baseParseMaybeDecoratorArguments=b;function x(){i.next.call(void 0),f.isLineTerminator.call(void 0)||(u.parseIdentifier.call(void 0),f.semicolon.call(void 0))}function S(){i.next.call(void 0),f.semicolon.call(void 0)}function C(){i.next.call(void 0),m(!1),f.expect.call(void 0,s.TokenType._while),u.parseParenExpression.call(void 0),i.eat.call(void 0,s.TokenType.semi)}function w(){l.state.scopeDepth++;let e=l.state.tokens.length;E();let t=l.state.tokens.length;l.state.scopes.push(new o.Scope(e,t,!1)),l.state.scopeDepth--}function T(){return!(!f.isContextual.call(void 0,a.ContextualKeyword._using)||f.isLookaheadContextual.call(void 0,a.ContextualKeyword._of))}function E(){i.next.call(void 0);let e=!1;if(f.isContextual.call(void 0,a.ContextualKeyword._await)&&(e=!0,i.next.call(void 0)),f.expect.call(void 0,s.TokenType.parenL),i.match.call(void 0,s.TokenType.semi)){e&&f.unexpected.call(void 0),ne();return}let t=g();if(t||i.match.call(void 0,s.TokenType._var)||i.match.call(void 0,s.TokenType._let)||i.match.call(void 0,s.TokenType._const)||T()){if(t&&f.expectContextual.call(void 0,a.ContextualKeyword._await),i.next.call(void 0),B(!0,l.state.type!==s.TokenType._var),i.match.call(void 0,s.TokenType._in)||f.isContextual.call(void 0,a.ContextualKeyword._of)){z(e);return}ne()}else u.parseExpression.call(void 0,!0),i.match.call(void 0,s.TokenType._in)||f.isContextual.call(void 0,a.ContextualKeyword._of)?z(e):(e&&f.unexpected.call(void 0),ne())}function D(){let e=l.state.start;i.next.call(void 0),ie(e,!0)}function O(){i.next.call(void 0),u.parseParenExpression.call(void 0),m(!1),i.eat.call(void 0,s.TokenType._else)&&m(!1)}function k(){i.next.call(void 0),f.isLineTerminator.call(void 0)||(u.parseExpression.call(void 0),f.semicolon.call(void 0))}function A(){i.next.call(void 0),u.parseParenExpression.call(void 0),l.state.scopeDepth++;let e=l.state.tokens.length;for(f.expect.call(void 0,s.TokenType.braceL);!i.match.call(void 0,s.TokenType.braceR)&&!l.state.error;)if(i.match.call(void 0,s.TokenType._case)||i.match.call(void 0,s.TokenType._default)){let e=i.match.call(void 0,s.TokenType._case);i.next.call(void 0),e&&u.parseExpression.call(void 0),f.expect.call(void 0,s.TokenType.colon)}else m(!0);i.next.call(void 0);let t=l.state.tokens.length;l.state.scopes.push(new o.Scope(e,t,!1)),l.state.scopeDepth--}function j(){i.next.call(void 0),u.parseExpression.call(void 0),f.semicolon.call(void 0)}function ee(){d.parseBindingAtom.call(void 0,!0),l.isTypeScriptEnabled&&r.tsTryParseTypeAnnotation.call(void 0)}function M(){if(i.next.call(void 0),te(),i.match.call(void 0,s.TokenType._catch)){i.next.call(void 0);let e=null;if(i.match.call(void 0,s.TokenType.parenL)&&(l.state.scopeDepth++,e=l.state.tokens.length,f.expect.call(void 0,s.TokenType.parenL),ee(),f.expect.call(void 0,s.TokenType.parenR)),te(),e!=null){let t=l.state.tokens.length;l.state.scopes.push(new o.Scope(e,t,!1)),l.state.scopeDepth--}}i.eat.call(void 0,s.TokenType._finally)&&te()}function N(e){i.next.call(void 0),B(!1,e),f.semicolon.call(void 0)}e.parseVarStatement=N;function P(){i.next.call(void 0),u.parseParenExpression.call(void 0),m(!1)}function F(){i.next.call(void 0)}function I(){m(!0)}function L(e){l.isTypeScriptEnabled?r.tsParseIdentifierStatement.call(void 0,e):l.isFlowEnabled?n.flowParseIdentifierStatement.call(void 0,e):f.semicolon.call(void 0)}function te(e=!1,t=0){let n=l.state.tokens.length;l.state.scopeDepth++,f.expect.call(void 0,s.TokenType.braceL),t&&(l.state.tokens[l.state.tokens.length-1].contextId=t),R(s.TokenType.braceR),t&&(l.state.tokens[l.state.tokens.length-1].contextId=t);let r=l.state.tokens.length;l.state.scopes.push(new o.Scope(n,r,e)),l.state.scopeDepth--}e.parseBlock=te;function R(e){for(;!i.eat.call(void 0,e)&&!l.state.error;)m(!0)}e.parseBlockBody=R;function ne(){f.expect.call(void 0,s.TokenType.semi),i.match.call(void 0,s.TokenType.semi)||u.parseExpression.call(void 0),f.expect.call(void 0,s.TokenType.semi),i.match.call(void 0,s.TokenType.parenR)||u.parseExpression.call(void 0),f.expect.call(void 0,s.TokenType.parenR),m(!1)}function z(e){e?f.eatContextual.call(void 0,a.ContextualKeyword._of):i.next.call(void 0),u.parseExpression.call(void 0),f.expect.call(void 0,s.TokenType.parenR),m(!1)}function B(e,t){for(;;){if(re(t),i.eat.call(void 0,s.TokenType.eq)){let t=l.state.tokens.length-1;u.parseMaybeAssign.call(void 0,e),l.state.tokens[t].rhsEndIndex=l.state.tokens.length}if(!i.eat.call(void 0,s.TokenType.comma))break}}function re(e){d.parseBindingAtom.call(void 0,e),l.isTypeScriptEnabled?r.tsAfterParseVarHead.call(void 0):l.isFlowEnabled&&n.flowAfterParseVarHead.call(void 0)}function ie(e,t,n=!1){i.match.call(void 0,s.TokenType.star)&&i.next.call(void 0),t&&!n&&!i.match.call(void 0,s.TokenType.name)&&!i.match.call(void 0,s.TokenType._yield)&&f.unexpected.call(void 0);let r=null;i.match.call(void 0,s.TokenType.name)&&(t||(r=l.state.tokens.length,l.state.scopeDepth++),d.parseBindingIdentifier.call(void 0,!1));let a=l.state.tokens.length;l.state.scopeDepth++,ae(),u.parseFunctionBodyAndFinish.call(void 0,e);let c=l.state.tokens.length;l.state.scopes.push(new o.Scope(a,c,!0)),l.state.scopeDepth--,r!==null&&(l.state.scopes.push(new o.Scope(r,c,!0)),l.state.scopeDepth--)}e.parseFunction=ie;function ae(e=!1,t=0){l.isTypeScriptEnabled?r.tsStartParseFunctionParams.call(void 0):l.isFlowEnabled&&n.flowStartParseFunctionParams.call(void 0),f.expect.call(void 0,s.TokenType.parenL),t&&(l.state.tokens[l.state.tokens.length-1].contextId=t),d.parseBindingList.call(void 0,s.TokenType.parenR,!1,!1,e,t),t&&(l.state.tokens[l.state.tokens.length-1].contextId=t)}e.parseFunctionParams=ae;function oe(e,t=!1){let n=l.getNextContextId.call(void 0);i.next.call(void 0),l.state.tokens[l.state.tokens.length-1].contextId=n,l.state.tokens[l.state.tokens.length-1].isExpression=!e;let r=null;e||(r=l.state.tokens.length,l.state.scopeDepth++),he(e,t),ge();let a=l.state.tokens.length;if(le(n),!l.state.error&&(l.state.tokens[a].contextId=n,l.state.tokens[l.state.tokens.length-1].contextId=n,r!==null)){let e=l.state.tokens.length;l.state.scopes.push(new o.Scope(r,e,!1)),l.state.scopeDepth--}}e.parseClass=oe;function se(){return i.match.call(void 0,s.TokenType.eq)||i.match.call(void 0,s.TokenType.semi)||i.match.call(void 0,s.TokenType.braceR)||i.match.call(void 0,s.TokenType.bang)||i.match.call(void 0,s.TokenType.colon)}function ce(){return i.match.call(void 0,s.TokenType.parenL)||i.match.call(void 0,s.TokenType.lessThan)}function le(e){for(f.expect.call(void 0,s.TokenType.braceL);!i.eat.call(void 0,s.TokenType.braceR)&&!l.state.error;){if(i.eat.call(void 0,s.TokenType.semi))continue;if(i.match.call(void 0,s.TokenType.at)){v();continue}let t=l.state.start;V(t,e)}}function V(e,t){l.isTypeScriptEnabled&&r.tsParseModifiers.call(void 0,[a.ContextualKeyword._declare,a.ContextualKeyword._public,a.ContextualKeyword._protected,a.ContextualKeyword._private,a.ContextualKeyword._override]);let n=!1;if(i.match.call(void 0,s.TokenType.name)&&l.state.contextualKeyword===a.ContextualKeyword._static){if(u.parseIdentifier.call(void 0),ce()){de(e,!1);return}if(se()){me();return}if(l.state.tokens[l.state.tokens.length-1].type=s.TokenType._static,n=!0,i.match.call(void 0,s.TokenType.braceL)){l.state.tokens[l.state.tokens.length-1].contextId=t,te();return}}ue(e,n,t)}function ue(e,t,n){if(l.isTypeScriptEnabled&&r.tsTryParseClassMemberWithIsStatic.call(void 0,t))return;if(i.eat.call(void 0,s.TokenType.star)){fe(n),de(e,!1);return}fe(n);let o=!1,c=l.state.tokens[l.state.tokens.length-1];c.contextualKeyword===a.ContextualKeyword._constructor&&(o=!0),pe(),ce()?de(e,o):se()?me():c.contextualKeyword===a.ContextualKeyword._async&&!f.isLineTerminator.call(void 0)?(l.state.tokens[l.state.tokens.length-1].type=s.TokenType._async,i.match.call(void 0,s.TokenType.star)&&i.next.call(void 0),fe(n),pe(),de(e,!1)):(c.contextualKeyword===a.ContextualKeyword._get||c.contextualKeyword===a.ContextualKeyword._set)&&!(f.isLineTerminator.call(void 0)&&i.match.call(void 0,s.TokenType.star))?(c.contextualKeyword===a.ContextualKeyword._get?l.state.tokens[l.state.tokens.length-1].type=s.TokenType._get:l.state.tokens[l.state.tokens.length-1].type=s.TokenType._set,fe(n),de(e,!1)):c.contextualKeyword===a.ContextualKeyword._accessor&&!f.isLineTerminator.call(void 0)?(fe(n),me()):f.isLineTerminator.call(void 0)?me():f.unexpected.call(void 0)}function de(e,t){l.isTypeScriptEnabled?r.tsTryParseTypeParameters.call(void 0):l.isFlowEnabled&&i.match.call(void 0,s.TokenType.lessThan)&&n.flowParseTypeParameterDeclaration.call(void 0),u.parseMethod.call(void 0,e,t)}function fe(e){u.parsePropertyName.call(void 0,e)}e.parseClassPropertyName=fe;function pe(){if(l.isTypeScriptEnabled){let e=i.pushTypeContext.call(void 0,0);i.eat.call(void 0,s.TokenType.question),i.popTypeContext.call(void 0,e)}}e.parsePostMemberNameModifiers=pe;function me(){if(l.isTypeScriptEnabled?(i.eatTypeToken.call(void 0,s.TokenType.bang),r.tsTryParseTypeAnnotation.call(void 0)):l.isFlowEnabled&&i.match.call(void 0,s.TokenType.colon)&&n.flowParseTypeAnnotation.call(void 0),i.match.call(void 0,s.TokenType.eq)){let e=l.state.tokens.length;i.next.call(void 0),u.parseMaybeAssign.call(void 0),l.state.tokens[e].rhsEndIndex=l.state.tokens.length}f.semicolon.call(void 0)}e.parseClassProperty=me;function he(e,t=!1){(!l.isTypeScriptEnabled||e&&!t||!f.isContextual.call(void 0,a.ContextualKeyword._implements))&&(i.match.call(void 0,s.TokenType.name)&&d.parseBindingIdentifier.call(void 0,!0),l.isTypeScriptEnabled?r.tsTryParseTypeParameters.call(void 0):l.isFlowEnabled&&i.match.call(void 0,s.TokenType.lessThan)&&n.flowParseTypeParameterDeclaration.call(void 0))}function ge(){let e=!1;i.eat.call(void 0,s.TokenType._extends)?(u.parseExprSubscripts.call(void 0),e=!0):e=!1,l.isTypeScriptEnabled?r.tsAfterParseClassSuper.call(void 0,e):l.isFlowEnabled&&n.flowAfterParseClassSuper.call(void 0,e)}function _e(){let e=l.state.tokens.length-1;l.isTypeScriptEnabled&&r.tsTryParseExport.call(void 0)||(Ce()?we():be()?(u.parseIdentifier.call(void 0),i.match.call(void 0,s.TokenType.comma)&&i.lookaheadType.call(void 0)===s.TokenType.star?(f.expect.call(void 0,s.TokenType.comma),f.expect.call(void 0,s.TokenType.star),f.expectContextual.call(void 0,a.ContextualKeyword._as),u.parseIdentifier.call(void 0)):xe(),Se()):i.eat.call(void 0,s.TokenType._default)?ve():Ee()?ye():(De(),Se()),l.state.tokens[e].rhsEndIndex=l.state.tokens.length)}e.parseExport=_e;function ve(){if(l.isTypeScriptEnabled&&r.tsTryParseExportDefaultExpression.call(void 0)||l.isFlowEnabled&&n.flowTryParseExportDefaultExpression.call(void 0))return;let e=l.state.start;i.eat.call(void 0,s.TokenType._function)?ie(e,!0,!0):f.isContextual.call(void 0,a.ContextualKeyword._async)&&i.lookaheadType.call(void 0)===s.TokenType._function?(f.eatContextual.call(void 0,a.ContextualKeyword._async),i.eat.call(void 0,s.TokenType._function),ie(e,!0,!0)):i.match.call(void 0,s.TokenType._class)?oe(!0,!0):i.match.call(void 0,s.TokenType.at)?(_(),oe(!0,!0)):(u.parseMaybeAssign.call(void 0),f.semicolon.call(void 0))}function ye(){l.isTypeScriptEnabled?r.tsParseExportDeclaration.call(void 0):l.isFlowEnabled?n.flowParseExportDeclaration.call(void 0):m(!0)}function be(){if(l.isTypeScriptEnabled&&r.tsIsDeclarationStart.call(void 0)||l.isFlowEnabled&&n.flowShouldDisallowExportDefaultSpecifier.call(void 0))return!1;if(i.match.call(void 0,s.TokenType.name))return l.state.contextualKeyword!==a.ContextualKeyword._async;if(!i.match.call(void 0,s.TokenType._default))return!1;let e=i.nextTokenStart.call(void 0),t=i.lookaheadTypeAndKeyword.call(void 0),o=t.type===s.TokenType.name&&t.contextualKeyword===a.ContextualKeyword._from;if(t.type===s.TokenType.comma)return!0;if(o){let t=l.input.charCodeAt(i.nextTokenStartSince.call(void 0,e+4));return t===c.charCodes.quotationMark||t===c.charCodes.apostrophe}return!1}function xe(){i.eat.call(void 0,s.TokenType.comma)&&De()}function Se(){f.eatContextual.call(void 0,a.ContextualKeyword._from)&&(u.parseExprAtom.call(void 0),Ie()),f.semicolon.call(void 0)}e.parseExportFrom=Se;function Ce(){return l.isFlowEnabled?n.flowShouldParseExportStar.call(void 0):i.match.call(void 0,s.TokenType.star)}function we(){l.isFlowEnabled?n.flowParseExportStar.call(void 0):H()}function H(){f.expect.call(void 0,s.TokenType.star),f.isContextual.call(void 0,a.ContextualKeyword._as)?Te():Se()}e.baseParseExportStar=H;function Te(){i.next.call(void 0),l.state.tokens[l.state.tokens.length-1].type=s.TokenType._as,u.parseIdentifier.call(void 0),xe(),Se()}function Ee(){return l.isTypeScriptEnabled&&r.tsIsDeclarationStart.call(void 0)||l.isFlowEnabled&&n.flowShouldParseExportDeclaration.call(void 0)||l.state.type===s.TokenType._var||l.state.type===s.TokenType._const||l.state.type===s.TokenType._let||l.state.type===s.TokenType._function||l.state.type===s.TokenType._class||f.isContextual.call(void 0,a.ContextualKeyword._async)||i.match.call(void 0,s.TokenType.at)}function De(){let e=!0;for(f.expect.call(void 0,s.TokenType.braceL);!i.eat.call(void 0,s.TokenType.braceR)&&!l.state.error;){if(e)e=!1;else if(f.expect.call(void 0,s.TokenType.comma),i.eat.call(void 0,s.TokenType.braceR))break;Oe()}}e.parseExportSpecifiers=De;function Oe(){l.isTypeScriptEnabled?r.tsParseExportSpecifier.call(void 0):(u.parseIdentifier.call(void 0),l.state.tokens[l.state.tokens.length-1].identifierRole=i.IdentifierRole.ExportAccess,f.eatContextual.call(void 0,a.ContextualKeyword._as)&&u.parseIdentifier.call(void 0))}function ke(){let e=l.state.snapshot();return f.expectContextual.call(void 0,a.ContextualKeyword._module),f.eatContextual.call(void 0,a.ContextualKeyword._from)?f.isContextual.call(void 0,a.ContextualKeyword._from)?(l.state.restoreFromSnapshot(e),!0):(l.state.restoreFromSnapshot(e),!1):i.match.call(void 0,s.TokenType.comma)?(l.state.restoreFromSnapshot(e),!1):(l.state.restoreFromSnapshot(e),!0)}function Ae(){f.isContextual.call(void 0,a.ContextualKeyword._module)&&ke()&&i.next.call(void 0)}function je(){if(l.isTypeScriptEnabled&&i.match.call(void 0,s.TokenType.name)&&i.lookaheadType.call(void 0)===s.TokenType.eq)r.tsParseImportEqualsDeclaration.call(void 0);else{if(l.isTypeScriptEnabled&&f.isContextual.call(void 0,a.ContextualKeyword._type)){let e=i.lookaheadTypeAndKeyword.call(void 0);if(e.type===s.TokenType.name&&e.contextualKeyword!==a.ContextualKeyword._from){if(f.expectContextual.call(void 0,a.ContextualKeyword._type),i.lookaheadType.call(void 0)===s.TokenType.eq){r.tsParseImportEqualsDeclaration.call(void 0);return}}else(e.type===s.TokenType.star||e.type===s.TokenType.braceL)&&f.expectContextual.call(void 0,a.ContextualKeyword._type)}i.match.call(void 0,s.TokenType.string)||(Ae(),Pe(),f.expectContextual.call(void 0,a.ContextualKeyword._from)),u.parseExprAtom.call(void 0),Ie(),f.semicolon.call(void 0)}}e.parseImport=je;function Me(){return i.match.call(void 0,s.TokenType.name)}function Ne(){d.parseImportedIdentifier.call(void 0)}function Pe(){l.isFlowEnabled&&n.flowStartParseImportSpecifiers.call(void 0);let e=!0;if(!(Me()&&(Ne(),!i.eat.call(void 0,s.TokenType.comma)))){if(i.match.call(void 0,s.TokenType.star))i.next.call(void 0),f.expectContextual.call(void 0,a.ContextualKeyword._as),Ne();else for(f.expect.call(void 0,s.TokenType.braceL);!i.eat.call(void 0,s.TokenType.braceR)&&!l.state.error;){if(e)e=!1;else if(i.eat.call(void 0,s.TokenType.colon)&&f.unexpected.call(void 0,`ES2015 named imports do not destructure. Use another statement for destructuring after the import.`),f.expect.call(void 0,s.TokenType.comma),i.eat.call(void 0,s.TokenType.braceR))break;Fe()}}}function Fe(){l.isTypeScriptEnabled?r.tsParseImportSpecifier.call(void 0):l.isFlowEnabled?n.flowParseImportSpecifier.call(void 0):(d.parseImportedIdentifier.call(void 0),f.isContextual.call(void 0,a.ContextualKeyword._as)&&(l.state.tokens[l.state.tokens.length-1].identifierRole=i.IdentifierRole.ImportAccess,i.next.call(void 0),d.parseImportedIdentifier.call(void 0)))}function Ie(){(i.match.call(void 0,s.TokenType._with)||f.isContextual.call(void 0,a.ContextualKeyword._assert)&&!f.hasPrecedingLineBreak.call(void 0))&&(i.next.call(void 0),u.parseObj.call(void 0,!1,!1))}})),$d=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=wd(),n=_d(),r=vd(),i=Qd();function a(){return r.state.pos===0&&r.input.charCodeAt(0)===n.charCodes.numberSign&&r.input.charCodeAt(1)===n.charCodes.exclamationMark&&t.skipLineComment.call(void 0,2),t.nextToken.call(void 0),i.parseTopLevel.call(void 0)}e.parseFile=a})),ef=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=vd(),n=$d();e.File=class{constructor(e,t){this.tokens=e,this.scopes=t}};function r(e,r,i,a){if(a&&i)throw Error(`Cannot combine flow and typescript plugins.`);t.initParser.call(void 0,e,r,i,a);let o=n.parseFile.call(void 0);if(t.state.error)throw t.augmentError.call(void 0,t.state.error);return o}e.parse=r})),tf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=hd();function n(e){let n=e.currentIndex(),r=0,i=e.currentToken();do{let a=e.tokens[n];if(a.isOptionalChainStart&&r++,a.isOptionalChainEnd&&r--,r+=a.numNullishCoalesceStarts,r-=a.numNullishCoalesceEnds,a.contextualKeyword===t.ContextualKeyword._await&&a.identifierRole==null&&a.scopeDepth===i.scopeDepth)return!0;n+=1}while(r>0&&n<e.tokens.length);return!1}e.default=n})),nf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=K(),r=t(tf());e.default=class e{__init(){this.resultCode=``}__init2(){this.resultMappings=Array(this.tokens.length)}__init3(){this.tokenIndex=0}constructor(t,n,r,i,a){this.code=t,this.tokens=n,this.isFlowEnabled=r,this.disableESTransforms=i,this.helperManager=a,e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this)}snapshot(){return{resultCode:this.resultCode,tokenIndex:this.tokenIndex}}restoreToSnapshot(e){this.resultCode=e.resultCode,this.tokenIndex=e.tokenIndex}dangerouslyGetAndRemoveCodeSinceSnapshot(e){let t=this.resultCode.slice(e.resultCode.length);return this.resultCode=e.resultCode,t}reset(){this.resultCode=``,this.resultMappings=Array(this.tokens.length),this.tokenIndex=0}matchesContextualAtIndex(e,t){return this.matches1AtIndex(e,n.TokenType.name)&&this.tokens[e].contextualKeyword===t}identifierNameAtIndex(e){return this.identifierNameForToken(this.tokens[e])}identifierNameAtRelativeIndex(e){return this.identifierNameForToken(this.tokenAtRelativeIndex(e))}identifierName(){return this.identifierNameForToken(this.currentToken())}identifierNameForToken(e){return this.code.slice(e.start,e.end)}rawCodeForToken(e){return this.code.slice(e.start,e.end)}stringValueAtIndex(e){return this.stringValueForToken(this.tokens[e])}stringValue(){return this.stringValueForToken(this.currentToken())}stringValueForToken(e){return this.code.slice(e.start+1,e.end-1)}matches1AtIndex(e,t){return this.tokens[e].type===t}matches2AtIndex(e,t,n){return this.tokens[e].type===t&&this.tokens[e+1].type===n}matches3AtIndex(e,t,n,r){return this.tokens[e].type===t&&this.tokens[e+1].type===n&&this.tokens[e+2].type===r}matches1(e){return this.tokens[this.tokenIndex].type===e}matches2(e,t){return this.tokens[this.tokenIndex].type===e&&this.tokens[this.tokenIndex+1].type===t}matches3(e,t,n){return this.tokens[this.tokenIndex].type===e&&this.tokens[this.tokenIndex+1].type===t&&this.tokens[this.tokenIndex+2].type===n}matches4(e,t,n,r){return this.tokens[this.tokenIndex].type===e&&this.tokens[this.tokenIndex+1].type===t&&this.tokens[this.tokenIndex+2].type===n&&this.tokens[this.tokenIndex+3].type===r}matches5(e,t,n,r,i){return this.tokens[this.tokenIndex].type===e&&this.tokens[this.tokenIndex+1].type===t&&this.tokens[this.tokenIndex+2].type===n&&this.tokens[this.tokenIndex+3].type===r&&this.tokens[this.tokenIndex+4].type===i}matchesContextual(e){return this.matchesContextualAtIndex(this.tokenIndex,e)}matchesContextIdAndLabel(e,t){return this.matches1(e)&&this.currentToken().contextId===t}previousWhitespaceAndComments(){let e=this.code.slice(this.tokenIndex>0?this.tokens[this.tokenIndex-1].end:0,this.tokenIndex<this.tokens.length?this.tokens[this.tokenIndex].start:this.code.length);return this.isFlowEnabled&&(e=e.replace(/@flow/g,``)),e}replaceToken(e){this.resultCode+=this.previousWhitespaceAndComments(),this.appendTokenPrefix(),this.resultMappings[this.tokenIndex]=this.resultCode.length,this.resultCode+=e,this.appendTokenSuffix(),this.tokenIndex++}replaceTokenTrimmingLeftWhitespace(e){this.resultCode+=this.previousWhitespaceAndComments().replace(/[^\r\n]/g,``),this.appendTokenPrefix(),this.resultMappings[this.tokenIndex]=this.resultCode.length,this.resultCode+=e,this.appendTokenSuffix(),this.tokenIndex++}removeInitialToken(){this.replaceToken(``)}removeToken(){this.replaceTokenTrimmingLeftWhitespace(``)}removeBalancedCode(){let e=0;for(;!this.isAtEnd();){if(this.matches1(n.TokenType.braceL))e++;else if(this.matches1(n.TokenType.braceR)){if(e===0)return;e--}this.removeToken()}}copyExpectedToken(e){if(this.tokens[this.tokenIndex].type!==e)throw Error(`Expected token ${e}`);this.copyToken()}copyToken(){this.resultCode+=this.previousWhitespaceAndComments(),this.appendTokenPrefix(),this.resultMappings[this.tokenIndex]=this.resultCode.length,this.resultCode+=this.code.slice(this.tokens[this.tokenIndex].start,this.tokens[this.tokenIndex].end),this.appendTokenSuffix(),this.tokenIndex++}copyTokenWithPrefix(e){this.resultCode+=this.previousWhitespaceAndComments(),this.appendTokenPrefix(),this.resultCode+=e,this.resultMappings[this.tokenIndex]=this.resultCode.length,this.resultCode+=this.code.slice(this.tokens[this.tokenIndex].start,this.tokens[this.tokenIndex].end),this.appendTokenSuffix(),this.tokenIndex++}appendTokenPrefix(){let e=this.currentToken();if((e.numNullishCoalesceStarts||e.isOptionalChainStart)&&(e.isAsyncOperation=r.default.call(void 0,this)),!this.disableESTransforms){if(e.numNullishCoalesceStarts)for(let t=0;t<e.numNullishCoalesceStarts;t++)e.isAsyncOperation?(this.resultCode+=`await `,this.resultCode+=this.helperManager.getHelperName(`asyncNullishCoalesce`)):this.resultCode+=this.helperManager.getHelperName(`nullishCoalesce`),this.resultCode+=`(`;e.isOptionalChainStart&&(e.isAsyncOperation&&(this.resultCode+=`await `),this.tokenIndex>0&&this.tokenAtRelativeIndex(-1).type===n.TokenType._delete?e.isAsyncOperation?this.resultCode+=this.helperManager.getHelperName(`asyncOptionalChainDelete`):this.resultCode+=this.helperManager.getHelperName(`optionalChainDelete`):e.isAsyncOperation?this.resultCode+=this.helperManager.getHelperName(`asyncOptionalChain`):this.resultCode+=this.helperManager.getHelperName(`optionalChain`),this.resultCode+=`([`)}}appendTokenSuffix(){let e=this.currentToken();if(e.isOptionalChainEnd&&!this.disableESTransforms&&(this.resultCode+=`])`),e.numNullishCoalesceEnds&&!this.disableESTransforms)for(let t=0;t<e.numNullishCoalesceEnds;t++)this.resultCode+=`))`}appendCode(e){this.resultCode+=e}currentToken(){return this.tokens[this.tokenIndex]}currentTokenCode(){let e=this.currentToken();return this.code.slice(e.start,e.end)}tokenAtRelativeIndex(e){return this.tokens[this.tokenIndex+e]}currentIndex(){return this.tokenIndex}nextToken(){if(this.tokenIndex===this.tokens.length)throw Error(`Unexpectedly reached end of input.`);this.tokenIndex++}previousToken(){this.tokenIndex--}finish(){if(this.tokenIndex!==this.tokens.length)throw Error(`Tried to finish processing tokens before reaching the end.`);return this.resultCode+=this.previousWhitespaceAndComments(),{code:this.resultCode,mappings:this.resultMappings}}isAtEnd(){return this.tokenIndex===this.tokens.length}}})),rf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=hd(),n=K();function r(e,r,l,u){let d=r.snapshot(),f=a(r),p=[],m=[],h=[],g=null,_=[],v=[],y=r.currentToken().contextId;if(y==null)throw Error(`Expected non-null class context ID on class open-brace.`);for(r.nextToken();!r.matchesContextIdAndLabel(n.TokenType.braceR,y);)if(r.matchesContextual(t.ContextualKeyword._constructor)&&!r.currentToken().isType)({constructorInitializerStatements:p,constructorInsertPos:g}=o(r));else if(r.matches1(n.TokenType.semi))u||v.push({start:r.currentIndex(),end:r.currentIndex()+1}),r.nextToken();else if(r.currentToken().isType)r.nextToken();else{let a=r.currentIndex(),d=!1,f=!1,b=!1;for(;s(r.currentToken());)r.matches1(n.TokenType._static)&&(d=!0),r.matches1(n.TokenType.hash)&&(f=!0),(r.matches1(n.TokenType._declare)||r.matches1(n.TokenType._abstract))&&(b=!0),r.nextToken();if(d&&r.matches1(n.TokenType.braceL)||f){i(r,y);continue}if(r.matchesContextual(t.ContextualKeyword._constructor)&&!r.currentToken().isType){({constructorInitializerStatements:p,constructorInsertPos:g}=o(r));continue}let x=r.currentIndex();if(c(r),r.matches1(n.TokenType.lessThan)||r.matches1(n.TokenType.parenL)){i(r,y);continue}for(;r.currentToken().isType;)r.nextToken();if(r.matches1(n.TokenType.eq)){let t=r.currentIndex(),n=r.currentToken().rhsEndIndex;if(n==null)throw Error(`Expected rhsEndIndex on class field assignment.`);for(r.nextToken();r.currentIndex()<n;)e.processToken();let i;d?(i=l.claimFreeName(`__initStatic`),h.push(i)):(i=l.claimFreeName(`__init`),m.push(i)),_.push({initializerName:i,equalsIndex:t,start:x,end:r.currentIndex()})}else(!u||b)&&v.push({start:a,end:r.currentIndex()})}return r.restoreToSnapshot(d),u?{headerInfo:f,constructorInitializerStatements:p,instanceInitializerNames:[],staticInitializerNames:[],constructorInsertPos:g,fields:[],rangesToRemove:v}:{headerInfo:f,constructorInitializerStatements:p,instanceInitializerNames:m,staticInitializerNames:h,constructorInsertPos:g,fields:_,rangesToRemove:v}}e.default=r;function i(e,t){for(e.nextToken();e.currentToken().contextId!==t;)e.nextToken();for(;s(e.tokenAtRelativeIndex(-1));)e.previousToken()}function a(e){let t=e.currentToken(),r=t.contextId;if(r==null)throw Error(`Expected context ID on class token.`);let i=t.isExpression;if(i==null)throw Error(`Expected isExpression on class token.`);let a=null,o=!1;for(e.nextToken(),e.matches1(n.TokenType.name)&&(a=e.identifierName());!e.matchesContextIdAndLabel(n.TokenType.braceL,r);)e.matches1(n.TokenType._extends)&&!e.currentToken().isType&&(o=!0),e.nextToken();return{isExpression:i,className:a,hasSuperclass:o}}function o(e){let t=[];e.nextToken();let r=e.currentToken().contextId;if(r==null)throw Error(`Expected context ID on open-paren starting constructor params.`);for(;!e.matchesContextIdAndLabel(n.TokenType.parenR,r);)if(e.currentToken().contextId===r){if(e.nextToken(),s(e.currentToken())){for(e.nextToken();s(e.currentToken());)e.nextToken();let r=e.currentToken();if(r.type!==n.TokenType.name)throw Error(`Expected identifier after access modifiers in constructor arg.`);let i=e.identifierNameForToken(r);t.push(`this.${i} = ${i}`)}}else e.nextToken();for(e.nextToken();e.currentToken().isType;)e.nextToken();let i=e.currentIndex(),a=!1;for(;!e.matchesContextIdAndLabel(n.TokenType.braceR,r);){if(!a&&e.matches2(n.TokenType._super,n.TokenType.parenL)){e.nextToken();let t=e.currentToken().contextId;if(t==null)throw Error(`Expected a context ID on the super call`);for(;!e.matchesContextIdAndLabel(n.TokenType.parenR,t);)e.nextToken();i=e.currentIndex(),a=!0}e.nextToken()}return e.nextToken(),{constructorInitializerStatements:t,constructorInsertPos:i}}function s(e){return[n.TokenType._async,n.TokenType._get,n.TokenType._set,n.TokenType.plus,n.TokenType.minus,n.TokenType._readonly,n.TokenType._static,n.TokenType._public,n.TokenType._private,n.TokenType._protected,n.TokenType._override,n.TokenType._abstract,n.TokenType.star,n.TokenType._declare,n.TokenType.hash].includes(e.type)}function c(e){if(e.matches1(n.TokenType.bracketL)){let t=e.currentToken().contextId;if(t==null)throw Error(`Expected class context ID on computed name open bracket.`);for(;!e.matchesContextIdAndLabel(n.TokenType.bracketR,t);)e.nextToken();e.nextToken()}else e.nextToken()}})),af=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=K();function n(e){if(e.removeInitialToken(),e.removeToken(),e.removeToken(),e.removeToken(),e.matches1(t.TokenType.parenL))e.removeToken(),e.removeToken(),e.removeToken();else for(;e.matches1(t.TokenType.dot);)e.removeToken(),e.removeToken()}e.default=n})),of=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=wd(),n=K();e.EMPTY_DECLARATION_INFO={typeDeclarations:/* @__PURE__ */ new Set,valueDeclarations:/* @__PURE__ */ new Set};function r(e){let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set;for(let a=0;a<e.tokens.length;a++){let o=e.tokens[a];o.type===n.TokenType.name&&t.isTopLevelDeclaration.call(void 0,o)&&(o.isType?r.add(e.identifierNameForToken(o)):i.add(e.identifierNameForToken(o)))}return{typeDeclarations:r,valueDeclarations:i}}e.default=r})),sf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=hd(),n=K();function r(e){let r=e.currentIndex();for(;!e.matches1AtIndex(r,n.TokenType.braceR);)r++;return e.matchesContextualAtIndex(r+1,t.ContextualKeyword._from)&&e.matches1AtIndex(r+2,n.TokenType.string)}e.default=r})),cf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=hd(),n=K();function r(e){(e.matches2(n.TokenType._with,n.TokenType.braceL)||e.matches2(n.TokenType.name,n.TokenType.braceL)&&e.matchesContextual(t.ContextualKeyword._assert))&&(e.removeToken(),e.removeToken(),e.removeBalancedCode(),e.removeToken())}e.removeMaybeImportAttributes=r})),lf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=K();function n(e,n,r,i){if(!e||n)return!1;let a=r.currentToken();if(a.rhsEndIndex==null)throw Error(`Expected non-null rhsEndIndex on export token.`);let o=a.rhsEndIndex-r.currentIndex();if(o!==3&&!(o===4&&r.matches1AtIndex(a.rhsEndIndex-1,t.TokenType.semi)))return!1;let s=r.tokenAtRelativeIndex(2);if(s.type!==t.TokenType.name)return!1;let c=r.identifierNameForToken(s);return i.typeDeclarations.has(c)&&!i.valueDeclarations.has(c)}e.default=n})),uf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=wd(),r=hd(),i=K(),a=t(af()),o=of(),s=t(o),c=t(Td()),l=t(sf()),u=cf(),d=t(lf()),f=t(Od());e.default=class e extends f.default{__init(){this.hadExport=!1}__init2(){this.hadNamedExport=!1}__init3(){this.hadDefaultExport=!1}constructor(t,n,r,i,a,c,l,u,d,f,p,m){super(),this.rootTransformer=t,this.tokens=n,this.importProcessor=r,this.nameManager=i,this.helperManager=a,this.reactHotLoaderTransformer=c,this.enableLegacyBabel5ModuleInterop=l,this.enableLegacyTypeScriptModuleInterop=u,this.isTypeScriptTransformEnabled=d,this.isFlowTransformEnabled=f,this.preserveDynamicImport=p,this.keepUnusedImports=m,e.prototype.__init.call(this),e.prototype.__init2.call(this),e.prototype.__init3.call(this),this.declarationInfo=d?s.default.call(void 0,n):o.EMPTY_DECLARATION_INFO}getPrefixCode(){let e=``;return this.hadExport&&(e+=`Object.defineProperty(exports, "__esModule", {value: true});`),e}getSuffixCode(){return this.enableLegacyBabel5ModuleInterop&&this.hadDefaultExport&&!this.hadNamedExport?`
236
- module.exports = exports.default;
237
- `:``}process(){return this.tokens.matches3(i.TokenType._import,i.TokenType.name,i.TokenType.eq)?this.processImportEquals():this.tokens.matches1(i.TokenType._import)?(this.processImport(),!0):this.tokens.matches2(i.TokenType._export,i.TokenType.eq)?(this.tokens.replaceToken(`module.exports`),!0):this.tokens.matches1(i.TokenType._export)&&!this.tokens.currentToken().isType?(this.hadExport=!0,this.processExport()):this.tokens.matches2(i.TokenType.name,i.TokenType.postIncDec)&&this.processPostIncDec()?!0:this.tokens.matches1(i.TokenType.name)||this.tokens.matches1(i.TokenType.jsxName)?this.processIdentifier():this.tokens.matches1(i.TokenType.eq)?this.processAssignment():this.tokens.matches1(i.TokenType.assign)?this.processComplexAssignment():this.tokens.matches1(i.TokenType.preIncDec)?this.processPreIncDec():!1}processImportEquals(){let e=this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+1);return this.importProcessor.shouldAutomaticallyElideImportedName(e)?a.default.call(void 0,this.tokens):this.tokens.replaceToken(`const`),!0}processImport(){if(this.tokens.matches2(i.TokenType._import,i.TokenType.parenL)){if(this.preserveDynamicImport){this.tokens.copyToken();return}let e=this.enableLegacyTypeScriptModuleInterop?``:`${this.helperManager.getHelperName(`interopRequireWildcard`)}(`;this.tokens.replaceToken(`Promise.resolve().then(() => ${e}require`);let t=this.tokens.currentToken().contextId;if(t==null)throw Error(`Expected context ID on dynamic import invocation.`);for(this.tokens.copyToken();!this.tokens.matchesContextIdAndLabel(i.TokenType.parenR,t);)this.rootTransformer.processToken();this.tokens.replaceToken(e?`)))`:`))`)}else{if(this.removeImportAndDetectIfShouldElide())this.tokens.removeToken();else{let e=this.tokens.stringValue();this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(e)),this.tokens.appendCode(this.importProcessor.claimImportCode(e))}u.removeMaybeImportAttributes.call(void 0,this.tokens),this.tokens.matches1(i.TokenType.semi)&&this.tokens.removeToken()}}removeImportAndDetectIfShouldElide(){if(this.tokens.removeInitialToken(),this.tokens.matchesContextual(r.ContextualKeyword._type)&&!this.tokens.matches1AtIndex(this.tokens.currentIndex()+1,i.TokenType.comma)&&!this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+1,r.ContextualKeyword._from))return this.removeRemainingImport(),!0;if(this.tokens.matches1(i.TokenType.name)||this.tokens.matches1(i.TokenType.star))return this.removeRemainingImport(),!1;if(this.tokens.matches1(i.TokenType.string))return!1;let e=!1,t=!1;for(;!this.tokens.matches1(i.TokenType.string);)(!e&&this.tokens.matches1(i.TokenType.braceL)||this.tokens.matches1(i.TokenType.comma))&&(this.tokens.removeToken(),this.tokens.matches1(i.TokenType.braceR)||(t=!0),(this.tokens.matches2(i.TokenType.name,i.TokenType.comma)||this.tokens.matches2(i.TokenType.name,i.TokenType.braceR)||this.tokens.matches4(i.TokenType.name,i.TokenType.name,i.TokenType.name,i.TokenType.comma)||this.tokens.matches4(i.TokenType.name,i.TokenType.name,i.TokenType.name,i.TokenType.braceR))&&(e=!0)),this.tokens.removeToken();return this.keepUnusedImports?!1:this.isTypeScriptTransformEnabled?!e:this.isFlowTransformEnabled?t&&!e:!1}removeRemainingImport(){for(;!this.tokens.matches1(i.TokenType.string);)this.tokens.removeToken()}processIdentifier(){let e=this.tokens.currentToken();if(e.shadowsGlobal)return!1;if(e.identifierRole===n.IdentifierRole.ObjectShorthand)return this.processObjectShorthand();if(e.identifierRole!==n.IdentifierRole.Access)return!1;let t=this.importProcessor.getIdentifierReplacement(this.tokens.identifierNameForToken(e));if(!t)return!1;let r=this.tokens.currentIndex()+1;for(;r<this.tokens.tokens.length&&this.tokens.tokens[r].type===i.TokenType.parenR;)r++;return this.tokens.tokens[r].type===i.TokenType.parenL?this.tokens.tokenAtRelativeIndex(1).type===i.TokenType.parenL&&this.tokens.tokenAtRelativeIndex(-1).type!==i.TokenType._new?(this.tokens.replaceToken(`${t}.call(void 0, `),this.tokens.removeToken(),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(i.TokenType.parenR)):this.tokens.replaceToken(`(0, ${t})`):this.tokens.replaceToken(t),!0}processObjectShorthand(){let e=this.tokens.identifierName(),t=this.importProcessor.getIdentifierReplacement(e);return t?(this.tokens.replaceToken(`${e}: ${t}`),!0):!1}processExport(){if(this.tokens.matches2(i.TokenType._export,i.TokenType._enum)||this.tokens.matches3(i.TokenType._export,i.TokenType._const,i.TokenType._enum))return this.hadNamedExport=!0,!1;if(this.tokens.matches2(i.TokenType._export,i.TokenType._default))return this.tokens.matches3(i.TokenType._export,i.TokenType._default,i.TokenType._enum)?(this.hadDefaultExport=!0,!1):(this.processExportDefault(),!0);if(this.tokens.matches2(i.TokenType._export,i.TokenType.braceL))return this.processExportBindings(),!0;if(this.tokens.matches2(i.TokenType._export,i.TokenType.name)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+1,r.ContextualKeyword._type)){if(this.tokens.removeInitialToken(),this.tokens.removeToken(),this.tokens.matches1(i.TokenType.braceL)){for(;!this.tokens.matches1(i.TokenType.braceR);)this.tokens.removeToken();this.tokens.removeToken()}else this.tokens.removeToken(),this.tokens.matches1(i.TokenType._as)&&(this.tokens.removeToken(),this.tokens.removeToken());return this.tokens.matchesContextual(r.ContextualKeyword._from)&&this.tokens.matches1AtIndex(this.tokens.currentIndex()+1,i.TokenType.string)&&(this.tokens.removeToken(),this.tokens.removeToken(),u.removeMaybeImportAttributes.call(void 0,this.tokens)),!0}if(this.hadNamedExport=!0,this.tokens.matches2(i.TokenType._export,i.TokenType._var)||this.tokens.matches2(i.TokenType._export,i.TokenType._let)||this.tokens.matches2(i.TokenType._export,i.TokenType._const))return this.processExportVar(),!0;if(this.tokens.matches2(i.TokenType._export,i.TokenType._function)||this.tokens.matches3(i.TokenType._export,i.TokenType.name,i.TokenType._function))return this.processExportFunction(),!0;if(this.tokens.matches2(i.TokenType._export,i.TokenType._class)||this.tokens.matches3(i.TokenType._export,i.TokenType._abstract,i.TokenType._class)||this.tokens.matches2(i.TokenType._export,i.TokenType.at))return this.processExportClass(),!0;if(this.tokens.matches2(i.TokenType._export,i.TokenType.star))return this.processExportStar(),!0;throw Error(`Unrecognized export syntax.`)}processAssignment(){let e=this.tokens.currentIndex(),t=this.tokens.tokens[e-1];if(t.isType||t.type!==i.TokenType.name||t.shadowsGlobal||e>=2&&this.tokens.matches1AtIndex(e-2,i.TokenType.dot)||e>=2&&[i.TokenType._var,i.TokenType._let,i.TokenType._const].includes(this.tokens.tokens[e-2].type))return!1;let n=this.importProcessor.resolveExportBinding(this.tokens.identifierNameForToken(t));return n?(this.tokens.copyToken(),this.tokens.appendCode(` ${n} =`),!0):!1}processComplexAssignment(){let e=this.tokens.currentIndex(),t=this.tokens.tokens[e-1];if(t.type!==i.TokenType.name||t.shadowsGlobal||e>=2&&this.tokens.matches1AtIndex(e-2,i.TokenType.dot))return!1;let n=this.importProcessor.resolveExportBinding(this.tokens.identifierNameForToken(t));return n?(this.tokens.appendCode(` = ${n}`),this.tokens.copyToken(),!0):!1}processPreIncDec(){let e=this.tokens.currentIndex(),t=this.tokens.tokens[e+1];if(t.type!==i.TokenType.name||t.shadowsGlobal||e+2<this.tokens.tokens.length&&(this.tokens.matches1AtIndex(e+2,i.TokenType.dot)||this.tokens.matches1AtIndex(e+2,i.TokenType.bracketL)||this.tokens.matches1AtIndex(e+2,i.TokenType.parenL)))return!1;let n=this.tokens.identifierNameForToken(t),r=this.importProcessor.resolveExportBinding(n);return r?(this.tokens.appendCode(`${r} = `),this.tokens.copyToken(),!0):!1}processPostIncDec(){let e=this.tokens.currentIndex(),t=this.tokens.tokens[e],n=this.tokens.tokens[e+1];if(t.type!==i.TokenType.name||t.shadowsGlobal||e>=1&&this.tokens.matches1AtIndex(e-1,i.TokenType.dot))return!1;let r=this.tokens.identifierNameForToken(t),a=this.importProcessor.resolveExportBinding(r);if(!a)return!1;let o=this.tokens.rawCodeForToken(n),s=this.importProcessor.getIdentifierReplacement(r)||r;if(o===`++`)this.tokens.replaceToken(`(${s} = ${a} = ${s} + 1, ${s} - 1)`);else if(o===`--`)this.tokens.replaceToken(`(${s} = ${a} = ${s} - 1, ${s} + 1)`);else throw Error(`Unexpected operator: ${o}`);return this.tokens.removeToken(),!0}processExportDefault(){let e=!0;if(this.tokens.matches4(i.TokenType._export,i.TokenType._default,i.TokenType._function,i.TokenType.name)||this.tokens.matches5(i.TokenType._export,i.TokenType._default,i.TokenType.name,i.TokenType._function,i.TokenType.name)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+2,r.ContextualKeyword._async)){this.tokens.removeInitialToken(),this.tokens.removeToken();let e=this.processNamedFunction();this.tokens.appendCode(` exports.default = ${e};`)}else if(this.tokens.matches4(i.TokenType._export,i.TokenType._default,i.TokenType._class,i.TokenType.name)||this.tokens.matches5(i.TokenType._export,i.TokenType._default,i.TokenType._abstract,i.TokenType._class,i.TokenType.name)||this.tokens.matches3(i.TokenType._export,i.TokenType._default,i.TokenType.at)){this.tokens.removeInitialToken(),this.tokens.removeToken(),this.copyDecorators(),this.tokens.matches1(i.TokenType._abstract)&&this.tokens.removeToken();let e=this.rootTransformer.processNamedClass();this.tokens.appendCode(` exports.default = ${e};`)}else if(d.default.call(void 0,this.isTypeScriptTransformEnabled,this.keepUnusedImports,this.tokens,this.declarationInfo))e=!1,this.tokens.removeInitialToken(),this.tokens.removeToken(),this.tokens.removeToken();else if(this.reactHotLoaderTransformer){let e=this.nameManager.claimFreeName(`_default`);this.tokens.replaceToken(`let ${e}; exports.`),this.tokens.copyToken(),this.tokens.appendCode(` = ${e} =`),this.reactHotLoaderTransformer.setExtractedDefaultExportName(e)}else this.tokens.replaceToken(`exports.`),this.tokens.copyToken(),this.tokens.appendCode(` =`);e&&(this.hadDefaultExport=!0)}copyDecorators(){for(;this.tokens.matches1(i.TokenType.at);)if(this.tokens.copyToken(),this.tokens.matches1(i.TokenType.parenL))this.tokens.copyExpectedToken(i.TokenType.parenL),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(i.TokenType.parenR);else{for(this.tokens.copyExpectedToken(i.TokenType.name);this.tokens.matches1(i.TokenType.dot);)this.tokens.copyExpectedToken(i.TokenType.dot),this.tokens.copyExpectedToken(i.TokenType.name);this.tokens.matches1(i.TokenType.parenL)&&(this.tokens.copyExpectedToken(i.TokenType.parenL),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(i.TokenType.parenR))}}processExportVar(){this.isSimpleExportVar()?this.processSimpleExportVar():this.processComplexExportVar()}isSimpleExportVar(){let e=this.tokens.currentIndex();if(e++,e++,!this.tokens.matches1AtIndex(e,i.TokenType.name))return!1;for(e++;e<this.tokens.tokens.length&&this.tokens.tokens[e].isType;)e++;return!!this.tokens.matches1AtIndex(e,i.TokenType.eq)}processSimpleExportVar(){this.tokens.removeInitialToken(),this.tokens.copyToken();let e=this.tokens.identifierName();for(;!this.tokens.matches1(i.TokenType.eq);)this.rootTransformer.processToken();let t=this.tokens.currentToken().rhsEndIndex;if(t==null)throw Error(`Expected = token with an end index.`);for(;this.tokens.currentIndex()<t;)this.rootTransformer.processToken();this.tokens.appendCode(`; exports.${e} = ${e}`)}processComplexExportVar(){this.tokens.removeInitialToken(),this.tokens.removeToken();let e=this.tokens.matches1(i.TokenType.braceL);e&&this.tokens.appendCode(`(`);let t=0;for(;;)if(this.tokens.matches1(i.TokenType.braceL)||this.tokens.matches1(i.TokenType.dollarBraceL)||this.tokens.matches1(i.TokenType.bracketL))t++,this.tokens.copyToken();else if(this.tokens.matches1(i.TokenType.braceR)||this.tokens.matches1(i.TokenType.bracketR))t--,this.tokens.copyToken();else if(t===0&&!this.tokens.matches1(i.TokenType.name)&&!this.tokens.currentToken().isType)break;else if(this.tokens.matches1(i.TokenType.eq)){let e=this.tokens.currentToken().rhsEndIndex;if(e==null)throw Error(`Expected = token with an end index.`);for(;this.tokens.currentIndex()<e;)this.rootTransformer.processToken()}else{let e=this.tokens.currentToken();if(n.isDeclaration.call(void 0,e)){let t=this.tokens.identifierName(),r=this.importProcessor.getIdentifierReplacement(t);if(r===null)throw Error(`Expected a replacement for ${t} in \`export var\` syntax.`);n.isObjectShorthandDeclaration.call(void 0,e)&&(r=`${t}: ${r}`),this.tokens.replaceToken(r)}else this.rootTransformer.processToken()}if(e){let e=this.tokens.currentToken().rhsEndIndex;if(e==null)throw Error(`Expected = token with an end index.`);for(;this.tokens.currentIndex()<e;)this.rootTransformer.processToken();this.tokens.appendCode(`)`)}}processExportFunction(){this.tokens.replaceToken(``);let e=this.processNamedFunction();this.tokens.appendCode(` exports.${e} = ${e};`)}processNamedFunction(){if(this.tokens.matches1(i.TokenType._function))this.tokens.copyToken();else if(this.tokens.matches2(i.TokenType.name,i.TokenType._function)){if(!this.tokens.matchesContextual(r.ContextualKeyword._async))throw Error(`Expected async keyword in function export.`);this.tokens.copyToken(),this.tokens.copyToken()}if(this.tokens.matches1(i.TokenType.star)&&this.tokens.copyToken(),!this.tokens.matches1(i.TokenType.name))throw Error(`Expected identifier for exported function name.`);let e=this.tokens.identifierName();if(this.tokens.copyToken(),this.tokens.currentToken().isType)for(this.tokens.removeInitialToken();this.tokens.currentToken().isType;)this.tokens.removeToken();return this.tokens.copyExpectedToken(i.TokenType.parenL),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(i.TokenType.parenR),this.rootTransformer.processPossibleTypeRange(),this.tokens.copyExpectedToken(i.TokenType.braceL),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(i.TokenType.braceR),e}processExportClass(){this.tokens.removeInitialToken(),this.copyDecorators(),this.tokens.matches1(i.TokenType._abstract)&&this.tokens.removeToken();let e=this.rootTransformer.processNamedClass();this.tokens.appendCode(` exports.${e} = ${e};`)}processExportBindings(){this.tokens.removeInitialToken(),this.tokens.removeToken();let e=l.default.call(void 0,this.tokens),t=[];for(;;){if(this.tokens.matches1(i.TokenType.braceR)){this.tokens.removeToken();break}let n=c.default.call(void 0,this.tokens);for(;this.tokens.currentIndex()<n.endIndex;)this.tokens.removeToken();if(!(n.isType||!e&&this.shouldElideExportedIdentifier(n.leftName))){let e=n.rightName;e==="default"?this.hadDefaultExport=!0:this.hadNamedExport=!0;let r=n.leftName,i=this.importProcessor.getIdentifierReplacement(r);t.push(`exports.${e} = ${i||r};`)}if(this.tokens.matches1(i.TokenType.braceR)){this.tokens.removeToken();break}if(this.tokens.matches2(i.TokenType.comma,i.TokenType.braceR)){this.tokens.removeToken(),this.tokens.removeToken();break}if(this.tokens.matches1(i.TokenType.comma))this.tokens.removeToken();else throw Error(`Unexpected token: ${JSON.stringify(this.tokens.currentToken())}`)}if(this.tokens.matchesContextual(r.ContextualKeyword._from)){this.tokens.removeToken();let e=this.tokens.stringValue();this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(e)),u.removeMaybeImportAttributes.call(void 0,this.tokens)}else this.tokens.appendCode(t.join(` `));this.tokens.matches1(i.TokenType.semi)&&this.tokens.removeToken()}processExportStar(){for(this.tokens.removeInitialToken();!this.tokens.matches1(i.TokenType.string);)this.tokens.removeToken();let e=this.tokens.stringValue();this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(e)),u.removeMaybeImportAttributes.call(void 0,this.tokens),this.tokens.matches1(i.TokenType.semi)&&this.tokens.removeToken()}shouldElideExportedIdentifier(e){return this.isTypeScriptTransformEnabled&&!this.keepUnusedImports&&!this.declarationInfo.valueDeclarations.has(e)}}})),df=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=hd(),r=K(),i=t(af()),a=of(),o=t(a),s=t(Td()),c=Ad(),l=t(sf()),u=cf(),d=t(lf()),f=t(Od());e.default=class extends f.default{constructor(e,t,n,r,i,s,l,u){super(),this.tokens=e,this.nameManager=t,this.helperManager=n,this.reactHotLoaderTransformer=r,this.isTypeScriptTransformEnabled=i,this.isFlowTransformEnabled=s,this.keepUnusedImports=l,this.nonTypeIdentifiers=i&&!l?c.getNonTypeIdentifiers.call(void 0,e,u):/* @__PURE__ */ new Set,this.declarationInfo=i&&!l?o.default.call(void 0,e):a.EMPTY_DECLARATION_INFO,this.injectCreateRequireForImportRequire=!!u.injectCreateRequireForImportRequire}process(){if(this.tokens.matches3(r.TokenType._import,r.TokenType.name,r.TokenType.eq))return this.processImportEquals();if(this.tokens.matches4(r.TokenType._import,r.TokenType.name,r.TokenType.name,r.TokenType.eq)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+1,n.ContextualKeyword._type)){this.tokens.removeInitialToken();for(let e=0;e<7;e++)this.tokens.removeToken();return!0}if(this.tokens.matches2(r.TokenType._export,r.TokenType.eq))return this.tokens.replaceToken(`module.exports`),!0;if(this.tokens.matches5(r.TokenType._export,r.TokenType._import,r.TokenType.name,r.TokenType.name,r.TokenType.eq)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+2,n.ContextualKeyword._type)){this.tokens.removeInitialToken();for(let e=0;e<8;e++)this.tokens.removeToken();return!0}if(this.tokens.matches1(r.TokenType._import))return this.processImport();if(this.tokens.matches2(r.TokenType._export,r.TokenType._default))return this.processExportDefault();if(this.tokens.matches2(r.TokenType._export,r.TokenType.braceL))return this.processNamedExports();if(this.tokens.matches2(r.TokenType._export,r.TokenType.name)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+1,n.ContextualKeyword._type)){if(this.tokens.removeInitialToken(),this.tokens.removeToken(),this.tokens.matches1(r.TokenType.braceL)){for(;!this.tokens.matches1(r.TokenType.braceR);)this.tokens.removeToken();this.tokens.removeToken()}else this.tokens.removeToken(),this.tokens.matches1(r.TokenType._as)&&(this.tokens.removeToken(),this.tokens.removeToken());return this.tokens.matchesContextual(n.ContextualKeyword._from)&&this.tokens.matches1AtIndex(this.tokens.currentIndex()+1,r.TokenType.string)&&(this.tokens.removeToken(),this.tokens.removeToken(),u.removeMaybeImportAttributes.call(void 0,this.tokens)),!0}return!1}processImportEquals(){let e=this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+1);return this.shouldAutomaticallyElideImportedName(e)?i.default.call(void 0,this.tokens):this.injectCreateRequireForImportRequire?(this.tokens.replaceToken(`const`),this.tokens.copyToken(),this.tokens.copyToken(),this.tokens.replaceToken(this.helperManager.getHelperName(`require`))):this.tokens.replaceToken(`const`),!0}processImport(){if(this.tokens.matches2(r.TokenType._import,r.TokenType.parenL))return!1;let e=this.tokens.snapshot();if(this.removeImportTypeBindings()){for(this.tokens.restoreToSnapshot(e);!this.tokens.matches1(r.TokenType.string);)this.tokens.removeToken();this.tokens.removeToken(),u.removeMaybeImportAttributes.call(void 0,this.tokens),this.tokens.matches1(r.TokenType.semi)&&this.tokens.removeToken()}return!0}removeImportTypeBindings(){if(this.tokens.copyExpectedToken(r.TokenType._import),this.tokens.matchesContextual(n.ContextualKeyword._type)&&!this.tokens.matches1AtIndex(this.tokens.currentIndex()+1,r.TokenType.comma)&&!this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+1,n.ContextualKeyword._from))return!0;if(this.tokens.matches1(r.TokenType.string))return this.tokens.copyToken(),!1;this.tokens.matchesContextual(n.ContextualKeyword._module)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+2,n.ContextualKeyword._from)&&this.tokens.copyToken();let e=!1,t=!1,i=!1;if(this.tokens.matches1(r.TokenType.name)&&(this.shouldAutomaticallyElideImportedName(this.tokens.identifierName())?(this.tokens.removeToken(),this.tokens.matches1(r.TokenType.comma)&&this.tokens.removeToken()):(e=!0,this.tokens.copyToken(),this.tokens.matches1(r.TokenType.comma)&&(i=!0,this.tokens.removeToken()))),this.tokens.matches1(r.TokenType.star))this.shouldAutomaticallyElideImportedName(this.tokens.identifierNameAtRelativeIndex(2))?(this.tokens.removeToken(),this.tokens.removeToken(),this.tokens.removeToken()):(i&&this.tokens.appendCode(`,`),e=!0,this.tokens.copyExpectedToken(r.TokenType.star),this.tokens.copyExpectedToken(r.TokenType.name),this.tokens.copyExpectedToken(r.TokenType.name));else if(this.tokens.matches1(r.TokenType.braceL)){for(i&&this.tokens.appendCode(`,`),this.tokens.copyToken();!this.tokens.matches1(r.TokenType.braceR);){t=!0;let n=s.default.call(void 0,this.tokens);if(n.isType||this.shouldAutomaticallyElideImportedName(n.rightName)){for(;this.tokens.currentIndex()<n.endIndex;)this.tokens.removeToken();this.tokens.matches1(r.TokenType.comma)&&this.tokens.removeToken()}else{for(e=!0;this.tokens.currentIndex()<n.endIndex;)this.tokens.copyToken();this.tokens.matches1(r.TokenType.comma)&&this.tokens.copyToken()}}this.tokens.copyExpectedToken(r.TokenType.braceR)}return this.keepUnusedImports?!1:this.isTypeScriptTransformEnabled?!e:this.isFlowTransformEnabled?t&&!e:!1}shouldAutomaticallyElideImportedName(e){return this.isTypeScriptTransformEnabled&&!this.keepUnusedImports&&!this.nonTypeIdentifiers.has(e)}processExportDefault(){if(d.default.call(void 0,this.isTypeScriptTransformEnabled,this.keepUnusedImports,this.tokens,this.declarationInfo))return this.tokens.removeInitialToken(),this.tokens.removeToken(),this.tokens.removeToken(),!0;if(!(this.tokens.matches4(r.TokenType._export,r.TokenType._default,r.TokenType._function,r.TokenType.name)||this.tokens.matches5(r.TokenType._export,r.TokenType._default,r.TokenType.name,r.TokenType._function,r.TokenType.name)&&this.tokens.matchesContextualAtIndex(this.tokens.currentIndex()+2,n.ContextualKeyword._async)||this.tokens.matches4(r.TokenType._export,r.TokenType._default,r.TokenType._class,r.TokenType.name)||this.tokens.matches5(r.TokenType._export,r.TokenType._default,r.TokenType._abstract,r.TokenType._class,r.TokenType.name))&&this.reactHotLoaderTransformer){let e=this.nameManager.claimFreeName(`_default`);return this.tokens.replaceToken(`let ${e}; export`),this.tokens.copyToken(),this.tokens.appendCode(` ${e} =`),this.reactHotLoaderTransformer.setExtractedDefaultExportName(e),!0}return!1}processNamedExports(){if(!this.isTypeScriptTransformEnabled)return!1;this.tokens.copyExpectedToken(r.TokenType._export),this.tokens.copyExpectedToken(r.TokenType.braceL);let e=l.default.call(void 0,this.tokens),t=!1;for(;!this.tokens.matches1(r.TokenType.braceR);){let n=s.default.call(void 0,this.tokens);if(n.isType||!e&&this.shouldElideExportedName(n.leftName)){for(;this.tokens.currentIndex()<n.endIndex;)this.tokens.removeToken();this.tokens.matches1(r.TokenType.comma)&&this.tokens.removeToken()}else{for(t=!0;this.tokens.currentIndex()<n.endIndex;)this.tokens.copyToken();this.tokens.matches1(r.TokenType.comma)&&this.tokens.copyToken()}}return this.tokens.copyExpectedToken(r.TokenType.braceR),!this.keepUnusedImports&&e&&!t&&(this.tokens.removeToken(),this.tokens.removeToken(),u.removeMaybeImportAttributes.call(void 0,this.tokens)),!0}shouldElideExportedName(e){return this.isTypeScriptTransformEnabled&&!this.keepUnusedImports&&this.declarationInfo.typeDeclarations.has(e)&&!this.declarationInfo.valueDeclarations.has(e)}}})),ff=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=hd(),r=K(),i=t(Od());e.default=class extends i.default{constructor(e,t,n){super(),this.rootTransformer=e,this.tokens=t,this.isImportsTransformEnabled=n}process(){return this.rootTransformer.processPossibleArrowParamEnd()||this.rootTransformer.processPossibleAsyncArrowWithTypeParams()||this.rootTransformer.processPossibleTypeRange()?!0:this.tokens.matches1(r.TokenType._enum)?(this.processEnum(),!0):this.tokens.matches2(r.TokenType._export,r.TokenType._enum)?(this.processNamedExportEnum(),!0):this.tokens.matches3(r.TokenType._export,r.TokenType._default,r.TokenType._enum)?(this.processDefaultExportEnum(),!0):!1}processNamedExportEnum(){if(this.isImportsTransformEnabled){this.tokens.removeInitialToken();let e=this.tokens.identifierNameAtRelativeIndex(1);this.processEnum(),this.tokens.appendCode(` exports.${e} = ${e};`)}else this.tokens.copyToken(),this.processEnum()}processDefaultExportEnum(){this.tokens.removeInitialToken(),this.tokens.removeToken();let e=this.tokens.identifierNameAtRelativeIndex(1);this.processEnum(),this.isImportsTransformEnabled?this.tokens.appendCode(` exports.default = ${e};`):this.tokens.appendCode(` export default ${e};`)}processEnum(){this.tokens.replaceToken(`const`),this.tokens.copyExpectedToken(r.TokenType.name);let e=!1;this.tokens.matchesContextual(n.ContextualKeyword._of)&&(this.tokens.removeToken(),e=this.tokens.matchesContextual(n.ContextualKeyword._symbol),this.tokens.removeToken());let t=this.tokens.matches3(r.TokenType.braceL,r.TokenType.name,r.TokenType.eq);this.tokens.appendCode(` = require("flow-enums-runtime")`);let i=!e&&!t;for(this.tokens.replaceTokenTrimmingLeftWhitespace(i?`.Mirrored([`:`({`);!this.tokens.matches1(r.TokenType.braceR);){if(this.tokens.matches1(r.TokenType.ellipsis)){this.tokens.removeToken();break}this.processEnumElement(e,t),this.tokens.matches1(r.TokenType.comma)&&this.tokens.copyToken()}this.tokens.replaceToken(i?`]);`:`});`)}processEnumElement(e,t){if(e){let e=this.tokens.identifierName();this.tokens.copyToken(),this.tokens.appendCode(`: Symbol("${e}")`)}else t?(this.tokens.copyToken(),this.tokens.replaceTokenTrimmingLeftWhitespace(`:`),this.tokens.copyToken()):this.tokens.replaceToken(`"${this.tokens.identifierName()}"`)}}})),pf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}function n(e){let t,n=e[0],r=1;for(;r<e.length;){let i=e[r],a=e[r+1];if(r+=2,(i===`optionalAccess`||i===`optionalCall`)&&n==null)return;i===`access`||i===`optionalAccess`?(t=n,n=a(n)):(i===`call`||i===`optionalCall`)&&(n=a((...e)=>n.call(t,...e)),t=void 0)}return n}var r=K(),i=t(Od());let a=`jest`,o=[`mock`,`unmock`,`enableAutomock`,`disableAutomock`];e.default=class e extends i.default{__init(){this.hoistedFunctionNames=[]}constructor(t,n,r,i){super(),this.rootTransformer=t,this.tokens=n,this.nameManager=r,this.importProcessor=i,e.prototype.__init.call(this)}process(){return this.tokens.currentToken().scopeDepth===0&&this.tokens.matches4(r.TokenType.name,r.TokenType.dot,r.TokenType.name,r.TokenType.parenL)&&this.tokens.identifierName()===a?!n([this,`access`,e=>e.importProcessor,`optionalAccess`,e=>e.getGlobalNames,`call`,e=>e(),`optionalAccess`,e=>e.has,`call`,e=>e(a)])&&this.extractHoistedCalls():!1}getHoistedCode(){return this.hoistedFunctionNames.length>0?this.hoistedFunctionNames.map(e=>`${e}();`).join(``):``}extractHoistedCalls(){this.tokens.removeToken();let e=!1;for(;this.tokens.matches3(r.TokenType.dot,r.TokenType.name,r.TokenType.parenL);){let t=this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+1);if(o.includes(t)){let t=this.nameManager.claimFreeName(`__jestHoist`);this.hoistedFunctionNames.push(t),this.tokens.replaceToken(`function ${t}(){${a}.`),this.tokens.copyToken(),this.tokens.copyToken(),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(r.TokenType.parenR),this.tokens.appendCode(`;}`),e=!1}else e?this.tokens.copyToken():this.tokens.replaceToken(`${a}.`),this.tokens.copyToken(),this.tokens.copyToken(),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(r.TokenType.parenR),e=!0}return!0}}})),mf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=K(),r=t(Od());e.default=class extends r.default{constructor(e){super(),this.tokens=e}process(){if(this.tokens.matches1(n.TokenType.num)){let e=this.tokens.currentTokenCode();if(e.includes(`_`))return this.tokens.replaceToken(e.replace(/_/g,``)),!0}return!1}}})),hf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=K(),r=t(Od());e.default=class extends r.default{constructor(e,t){super(),this.tokens=e,this.nameManager=t}process(){return this.tokens.matches2(n.TokenType._catch,n.TokenType.braceL)?(this.tokens.copyToken(),this.tokens.appendCode(` (${this.nameManager.claimFreeName(`e`)})`),!0):!1}}})),gf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=K(),r=t(Od());e.default=class extends r.default{constructor(e,t){super(),this.tokens=e,this.nameManager=t}process(){if(this.tokens.matches1(n.TokenType.nullishCoalescing)){let e=this.tokens.currentToken();return this.tokens.tokens[e.nullishStartIndex].isAsyncOperation?this.tokens.replaceTokenTrimmingLeftWhitespace(`, async () => (`):this.tokens.replaceTokenTrimmingLeftWhitespace(`, () => (`),!0}if(this.tokens.matches1(n.TokenType._delete)&&this.tokens.tokenAtRelativeIndex(1).isOptionalChainStart)return this.tokens.removeInitialToken(),!0;let e=this.tokens.currentToken().subscriptStartIndex;if(e!=null&&this.tokens.tokens[e].isOptionalChainStart&&this.tokens.tokenAtRelativeIndex(-1).type!==n.TokenType._super){let t=this.nameManager.claimFreeName(`_`),r;if(r=e>0&&this.tokens.matches1AtIndex(e-1,n.TokenType._delete)&&this.isLastSubscriptInChain()?`${t} => delete ${t}`:`${t} => ${t}`,this.tokens.tokens[e].isAsyncOperation&&(r=`async ${r}`),this.tokens.matches2(n.TokenType.questionDot,n.TokenType.parenL)||this.tokens.matches2(n.TokenType.questionDot,n.TokenType.lessThan))this.justSkippedSuper()&&this.tokens.appendCode(`.bind(this)`),this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalCall', ${r}`);else if(this.tokens.matches2(n.TokenType.questionDot,n.TokenType.bracketL))this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${r}`);else if(this.tokens.matches1(n.TokenType.questionDot))this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${r}.`);else if(this.tokens.matches1(n.TokenType.dot))this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${r}.`);else if(this.tokens.matches1(n.TokenType.bracketL))this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${r}[`);else if(this.tokens.matches1(n.TokenType.parenL))this.justSkippedSuper()&&this.tokens.appendCode(`.bind(this)`),this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'call', ${r}(`);else throw Error(`Unexpected subscript operator in optional chain.`);return!0}return!1}isLastSubscriptInChain(){let e=0;for(let t=this.tokens.currentIndex()+1;;t++){if(t>=this.tokens.tokens.length)throw Error(`Reached the end of the code while finding the end of the access chain.`);if(this.tokens.tokens[t].isOptionalChainStart?e++:this.tokens.tokens[t].isOptionalChainEnd&&e--,e<0)return!0;if(e===0&&this.tokens.tokens[t].subscriptStartIndex!=null)return!1}}justSkippedSuper(){let e=0,t=this.tokens.currentIndex()-1;for(;;){if(t<0)throw Error(`Reached the start of the code while finding the start of the access chain.`);if(this.tokens.tokens[t].isOptionalChainStart?e--:this.tokens.tokens[t].isOptionalChainEnd&&e++,e<0)return!1;if(e===0&&this.tokens.tokens[t].subscriptStartIndex!=null)return this.tokens.tokens[t-1].type===n.TokenType._super;t--}}}})),_f=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=wd(),r=K(),i=t(Od());e.default=class extends i.default{constructor(e,t,n,r){super(),this.rootTransformer=e,this.tokens=t,this.importProcessor=n,this.options=r}process(){let e=this.tokens.currentIndex();if(this.tokens.identifierName()===`createReactClass`){let t=this.importProcessor&&this.importProcessor.getIdentifierReplacement(`createReactClass`);return t?this.tokens.replaceToken(`(0, ${t})`):this.tokens.copyToken(),this.tryProcessCreateClassCall(e),!0}if(this.tokens.matches3(r.TokenType.name,r.TokenType.dot,r.TokenType.name)&&this.tokens.identifierName()===`React`&&this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+2)===`createClass`){let t=this.importProcessor&&this.importProcessor.getIdentifierReplacement(`React`)||`React`;return t?(this.tokens.replaceToken(t),this.tokens.copyToken(),this.tokens.copyToken()):(this.tokens.copyToken(),this.tokens.copyToken(),this.tokens.copyToken()),this.tryProcessCreateClassCall(e),!0}return!1}tryProcessCreateClassCall(e){let t=this.findDisplayName(e);t&&this.classNeedsDisplayName()&&(this.tokens.copyExpectedToken(r.TokenType.parenL),this.tokens.copyExpectedToken(r.TokenType.braceL),this.tokens.appendCode(`displayName: '${t}',`),this.rootTransformer.processBalancedCode(),this.tokens.copyExpectedToken(r.TokenType.braceR),this.tokens.copyExpectedToken(r.TokenType.parenR))}findDisplayName(e){return e<2?null:this.tokens.matches2AtIndex(e-2,r.TokenType.name,r.TokenType.eq)||e>=2&&this.tokens.tokens[e-2].identifierRole===n.IdentifierRole.ObjectKey?this.tokens.identifierNameAtIndex(e-2):this.tokens.matches2AtIndex(e-2,r.TokenType._export,r.TokenType._default)?this.getDisplayNameFromFilename():null}getDisplayNameFromFilename(){let e=(this.options.filePath||`unknown`).split(`/`),t=e[e.length-1],n=t.lastIndexOf(`.`),r=n===-1?t:t.slice(0,n);return r===`index`&&e[e.length-2]?e[e.length-2]:r}classNeedsDisplayName(){let e=this.tokens.currentIndex();if(!this.tokens.matches2(r.TokenType.parenL,r.TokenType.braceL))return!1;let t=e+1,i=this.tokens.tokens[t].contextId;if(i==null)throw Error(`Expected non-null context ID on object open-brace.`);for(;e<this.tokens.tokens.length;e++){let t=this.tokens.tokens[e];if(t.type===r.TokenType.braceR&&t.contextId===i){e++;break}if(this.tokens.identifierNameAtIndex(e)===`displayName`&&this.tokens.tokens[e].identifierRole===n.IdentifierRole.ObjectKey&&t.contextId===i)return!1}if(e===this.tokens.tokens.length)throw Error(`Unexpected end of input when processing React class.`);return this.tokens.matches1AtIndex(e,r.TokenType.parenR)||this.tokens.matches2AtIndex(e,r.TokenType.comma,r.TokenType.parenR)}}})),vf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=wd(),r=t(Od());e.default=class e extends r.default{__init(){this.extractedDefaultExportName=null}constructor(t,n){super(),this.tokens=t,this.filePath=n,e.prototype.__init.call(this)}setExtractedDefaultExportName(e){this.extractedDefaultExportName=e}getPrefixCode(){return`
238
- (function () {
239
- var enterModule = require('react-hot-loader').enterModule;
240
- enterModule && enterModule(module);
241
- })();`.replace(/\s+/g,` `).trim()}getSuffixCode(){let e=/* @__PURE__ */ new Set;for(let t of this.tokens.tokens)!t.isType&&n.isTopLevelDeclaration.call(void 0,t)&&t.identifierRole!==n.IdentifierRole.ImportDeclaration&&e.add(this.tokens.identifierNameForToken(t));let t=Array.from(e).map(e=>({variableName:e,uniqueLocalName:e}));return this.extractedDefaultExportName&&t.push({variableName:this.extractedDefaultExportName,uniqueLocalName:`default`}),`
242
- ;(function () {
243
- var reactHotLoader = require('react-hot-loader').default;
244
- var leaveModule = require('react-hot-loader').leaveModule;
245
- if (!reactHotLoader) {
246
- return;
247
- }
248
- ${t.map(({variableName:e,uniqueLocalName:t})=>` reactHotLoader.register(${e}, "${t}", ${JSON.stringify(this.filePath||``)});`).join(`
249
- `)}
250
- leaveModule(module);
251
- })();`}process(){return!1}}})),yf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=xd();let n=/* @__PURE__ */ new Set(/* @__PURE__ */ `break.case.catch.class.const.continue.debugger.default.delete.do.else.export.extends.finally.for.function.if.import.in.instanceof.new.return.super.switch.this.throw.try.typeof.var.void.while.with.yield.enum.implements.interface.let.package.private.protected.public.static.await.false.null.true`.split(`.`));function r(e){if(e.length===0||!t.IS_IDENTIFIER_START[e.charCodeAt(0)])return!1;for(let n=1;n<e.length;n++)if(!t.IS_IDENTIFIER_CHAR[e.charCodeAt(n)])return!1;return!n.has(e)}e.default=r})),bf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=K(),r=t(yf()),i=t(Od());e.default=class extends i.default{constructor(e,t,n){super(),this.rootTransformer=e,this.tokens=t,this.isImportsTransformEnabled=n}process(){return this.rootTransformer.processPossibleArrowParamEnd()||this.rootTransformer.processPossibleAsyncArrowWithTypeParams()||this.rootTransformer.processPossibleTypeRange()?!0:this.tokens.matches1(n.TokenType._public)||this.tokens.matches1(n.TokenType._protected)||this.tokens.matches1(n.TokenType._private)||this.tokens.matches1(n.TokenType._abstract)||this.tokens.matches1(n.TokenType._readonly)||this.tokens.matches1(n.TokenType._override)||this.tokens.matches1(n.TokenType.nonNullAssertion)?(this.tokens.removeInitialToken(),!0):this.tokens.matches1(n.TokenType._enum)||this.tokens.matches2(n.TokenType._const,n.TokenType._enum)?(this.processEnum(),!0):this.tokens.matches2(n.TokenType._export,n.TokenType._enum)||this.tokens.matches3(n.TokenType._export,n.TokenType._const,n.TokenType._enum)?(this.processEnum(!0),!0):!1}processEnum(e=!1){for(this.tokens.removeInitialToken();this.tokens.matches1(n.TokenType._const)||this.tokens.matches1(n.TokenType._enum);)this.tokens.removeToken();let t=this.tokens.identifierName();this.tokens.removeToken(),e&&!this.isImportsTransformEnabled&&this.tokens.appendCode(`export `),this.tokens.appendCode(`var ${t}; (function (${t})`),this.tokens.copyExpectedToken(n.TokenType.braceL),this.processEnumBody(t),this.tokens.copyExpectedToken(n.TokenType.braceR),e&&this.isImportsTransformEnabled?this.tokens.appendCode(`)(${t} || (exports.${t} = ${t} = {}));`):this.tokens.appendCode(`)(${t} || (${t} = {}));`)}processEnumBody(e){let t=null;for(;!this.tokens.matches1(n.TokenType.braceR);){let{nameStringCode:r,variableName:i}=this.extractEnumKeyInfo(this.tokens.currentToken());this.tokens.removeInitialToken(),this.tokens.matches3(n.TokenType.eq,n.TokenType.string,n.TokenType.comma)||this.tokens.matches3(n.TokenType.eq,n.TokenType.string,n.TokenType.braceR)?this.processStringLiteralEnumMember(e,r,i):this.tokens.matches1(n.TokenType.eq)?this.processExplicitValueEnumMember(e,r,i):this.processImplicitValueEnumMember(e,r,i,t),this.tokens.matches1(n.TokenType.comma)&&this.tokens.removeToken(),t=i??`${e}[${r}]`}}extractEnumKeyInfo(e){if(e.type===n.TokenType.name){let t=this.tokens.identifierNameForToken(e);return{nameStringCode:`"${t}"`,variableName:r.default.call(void 0,t)?t:null}}if(e.type===n.TokenType.string){let t=this.tokens.stringValueForToken(e);return{nameStringCode:this.tokens.code.slice(e.start,e.end),variableName:r.default.call(void 0,t)?t:null}}throw Error(`Expected name or string at beginning of enum element.`)}processStringLiteralEnumMember(e,t,n){n==null?(this.tokens.appendCode(`${e}[${t}]`),this.tokens.copyToken(),this.tokens.copyToken(),this.tokens.appendCode(`;`)):(this.tokens.appendCode(`const ${n}`),this.tokens.copyToken(),this.tokens.copyToken(),this.tokens.appendCode(`; ${e}[${t}] = ${n};`))}processExplicitValueEnumMember(e,t,n){let r=this.tokens.currentToken().rhsEndIndex;if(r==null)throw Error(`Expected rhsEndIndex on enum assign.`);if(n!=null){for(this.tokens.appendCode(`const ${n}`),this.tokens.copyToken();this.tokens.currentIndex()<r;)this.rootTransformer.processToken();this.tokens.appendCode(`; ${e}[${e}[${t}] = ${n}] = ${t};`)}else{for(this.tokens.appendCode(`${e}[${e}[${t}]`),this.tokens.copyToken();this.tokens.currentIndex()<r;)this.rootTransformer.processToken();this.tokens.appendCode(`] = ${t};`)}}processImplicitValueEnumMember(e,t,n,r){let i=r==null?`0`:`${r} + 1`;n!=null&&(this.tokens.appendCode(`const ${n} = ${i}; `),i=n),this.tokens.appendCode(`${e}[${e}[${t}] = ${i}] = ${t};`)}}})),xf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=hd(),r=K(),i=t(rf()),a=t(uf()),o=t(df()),s=t(ff()),c=t(pf()),l=t(kd()),u=t(mf()),d=t(hf()),f=t(gf()),p=t(_f()),m=t(vf()),h=t(bf());e.default=class e{__init(){this.transformers=[]}__init2(){this.generatedVariables=[]}constructor(t,n,r,i){e.prototype.__init.call(this),e.prototype.__init2.call(this),this.nameManager=t.nameManager,this.helperManager=t.helperManager;let{tokenProcessor:g,importProcessor:_}=t;this.tokens=g,this.isImportsTransformEnabled=n.includes(`imports`),this.isReactHotLoaderTransformEnabled=n.includes(`react-hot-loader`),this.disableESTransforms=!!i.disableESTransforms,i.disableESTransforms||(this.transformers.push(new f.default(g,this.nameManager)),this.transformers.push(new u.default(g)),this.transformers.push(new d.default(g,this.nameManager))),n.includes(`jsx`)&&(i.jsxRuntime!==`preserve`&&this.transformers.push(new l.default(this,g,_,this.nameManager,i)),this.transformers.push(new p.default(this,g,_,i)));let v=null;if(n.includes(`react-hot-loader`)){if(!i.filePath)throw Error(`filePath is required when using the react-hot-loader transform.`);v=new m.default(g,i.filePath),this.transformers.push(v)}if(n.includes(`imports`)){if(_===null)throw Error(`Expected non-null importProcessor with imports transform enabled.`);this.transformers.push(new a.default(this,g,_,this.nameManager,this.helperManager,v,r,!!i.enableLegacyTypeScriptModuleInterop,n.includes(`typescript`),n.includes(`flow`),!!i.preserveDynamicImport,!!i.keepUnusedImports))}else this.transformers.push(new o.default(g,this.nameManager,this.helperManager,v,n.includes(`typescript`),n.includes(`flow`),!!i.keepUnusedImports,i));n.includes(`flow`)&&this.transformers.push(new s.default(this,g,n.includes(`imports`))),n.includes(`typescript`)&&this.transformers.push(new h.default(this,g,n.includes(`imports`))),n.includes(`jest`)&&this.transformers.push(new c.default(this,g,this.nameManager,_))}transform(){this.tokens.reset(),this.processBalancedCode();let e=this.isImportsTransformEnabled?`"use strict";`:``;for(let t of this.transformers)e+=t.getPrefixCode();e+=this.helperManager.emitHelpers(),e+=this.generatedVariables.map(e=>` var ${e};`).join(``);for(let t of this.transformers)e+=t.getHoistedCode();let t=``;for(let e of this.transformers)t+=e.getSuffixCode();let n=this.tokens.finish(),{code:r}=n;if(r.startsWith(`#!`)){let i=r.indexOf(`
252
- `);return i===-1&&(i=r.length,r+=`
253
- `),{code:r.slice(0,i+1)+e+r.slice(i+1)+t,mappings:this.shiftMappings(n.mappings,e.length)}}return{code:e+r+t,mappings:this.shiftMappings(n.mappings,e.length)}}processBalancedCode(){let e=0,t=0;for(;!this.tokens.isAtEnd();){if(this.tokens.matches1(r.TokenType.braceL)||this.tokens.matches1(r.TokenType.dollarBraceL))e++;else if(this.tokens.matches1(r.TokenType.braceR)){if(e===0)return;e--}if(this.tokens.matches1(r.TokenType.parenL))t++;else if(this.tokens.matches1(r.TokenType.parenR)){if(t===0)return;t--}this.processToken()}}processToken(){if(this.tokens.matches1(r.TokenType._class))this.processClass();else{for(let e of this.transformers)if(e.process())return;this.tokens.copyToken()}}processNamedClass(){if(!this.tokens.matches2(r.TokenType._class,r.TokenType.name))throw Error(`Expected identifier for exported class name.`);let e=this.tokens.identifierNameAtIndex(this.tokens.currentIndex()+1);return this.processClass(),e}processClass(){let e=i.default.call(void 0,this,this.tokens,this.nameManager,this.disableESTransforms),t=(e.headerInfo.isExpression||!e.headerInfo.className)&&e.staticInitializerNames.length+e.instanceInitializerNames.length>0,n=e.headerInfo.className;t&&(n=this.nameManager.claimFreeName(`_class`),this.generatedVariables.push(n),this.tokens.appendCode(` (${n} =`));let a=this.tokens.currentToken().contextId;if(a==null)throw Error(`Expected class to have a context ID.`);for(this.tokens.copyExpectedToken(r.TokenType._class);!this.tokens.matchesContextIdAndLabel(r.TokenType.braceL,a);)this.processToken();this.processClassBody(e,n);let o=e.staticInitializerNames.map(e=>`${n}.${e}()`);t?this.tokens.appendCode(`, ${o.map(e=>`${e}, `).join(``)}${n})`):e.staticInitializerNames.length>0&&this.tokens.appendCode(` ${o.map(e=>`${e};`).join(` `)}`)}processClassBody(e,t){let{headerInfo:n,constructorInsertPos:i,constructorInitializerStatements:a,fields:o,instanceInitializerNames:s,rangesToRemove:c}=e,l=0,u=0,d=this.tokens.currentToken().contextId;if(d==null)throw Error(`Expected non-null context ID on class.`);this.tokens.copyExpectedToken(r.TokenType.braceL),this.isReactHotLoaderTransformEnabled&&this.tokens.appendCode(`__reactstandin__regenerateByEval(key, code) {this[key] = eval(code);}`);let f=a.length+s.length>0;if(i===null&&f){let e=this.makeConstructorInitCode(a,s,t);if(n.hasSuperclass){let t=this.nameManager.claimFreeName(`args`);this.tokens.appendCode(`constructor(...${t}) { super(...${t}); ${e}; }`)}else this.tokens.appendCode(`constructor() { ${e}; }`)}for(;!this.tokens.matchesContextIdAndLabel(r.TokenType.braceR,d);)if(l<o.length&&this.tokens.currentIndex()===o[l].start){let e=!1;for(this.tokens.matches1(r.TokenType.bracketL)?this.tokens.copyTokenWithPrefix(`${o[l].initializerName}() {this`):this.tokens.matches1(r.TokenType.string)||this.tokens.matches1(r.TokenType.num)?(this.tokens.copyTokenWithPrefix(`${o[l].initializerName}() {this[`),e=!0):this.tokens.copyTokenWithPrefix(`${o[l].initializerName}() {this.`);this.tokens.currentIndex()<o[l].end;)e&&this.tokens.currentIndex()===o[l].equalsIndex&&this.tokens.appendCode(`]`),this.processToken();this.tokens.appendCode(`}`),l++}else if(u<c.length&&this.tokens.currentIndex()>=c[u].start){for(this.tokens.currentIndex()<c[u].end&&this.tokens.removeInitialToken();this.tokens.currentIndex()<c[u].end;)this.tokens.removeToken();u++}else this.tokens.currentIndex()===i&&(this.tokens.copyToken(),f&&this.tokens.appendCode(`;${this.makeConstructorInitCode(a,s,t)};`)),this.processToken();this.tokens.copyExpectedToken(r.TokenType.braceR)}makeConstructorInitCode(e,t,n){return[...e,...t.map(e=>`${n}.prototype.${e}.call(this)`)].join(`;`)}processPossibleArrowParamEnd(){if(this.tokens.matches2(r.TokenType.parenR,r.TokenType.colon)&&this.tokens.tokenAtRelativeIndex(1).isType){let e=this.tokens.currentIndex()+1;for(;this.tokens.tokens[e].isType;)e++;if(this.tokens.matches1AtIndex(e,r.TokenType.arrow)){for(this.tokens.removeInitialToken();this.tokens.currentIndex()<e;)this.tokens.removeToken();return this.tokens.replaceTokenTrimmingLeftWhitespace(`) =>`),!0}}return!1}processPossibleAsyncArrowWithTypeParams(){if(!this.tokens.matchesContextual(n.ContextualKeyword._async)&&!this.tokens.matches1(r.TokenType._async))return!1;let e=this.tokens.tokenAtRelativeIndex(1);if(e.type!==r.TokenType.lessThan||!e.isType)return!1;let t=this.tokens.currentIndex()+1;for(;this.tokens.tokens[t].isType;)t++;if(this.tokens.matches1AtIndex(t,r.TokenType.parenL)){for(this.tokens.replaceToken(`async (`),this.tokens.removeInitialToken();this.tokens.currentIndex()<t;)this.tokens.removeToken();return this.tokens.removeToken(),this.processBalancedCode(),this.processToken(),!0}return!1}processPossibleTypeRange(){if(this.tokens.currentToken().isType){for(this.tokens.removeInitialToken();this.tokens.currentToken().isType;)this.tokens.removeToken();return!0}return!1}shiftMappings(e,t){for(let n=0;n<e.length;n++){let r=e[n];r!==void 0&&(e[n]=r+t)}return e}}})),Sf=/* @__PURE__ */ o((e=>{e.__esModule=!0,e.LinesAndColumns=void 0;var t=`
254
- `,n=`\r`,r=function(){function e(e){this.string=e;for(var r=[0],i=0;i<e.length;)switch(e[i]){case t:i+=t.length,r.push(i);break;case n:i+=n.length,e[i]===t&&(i+=t.length),r.push(i);break;default:i++}this.offsets=r}return e.prototype.locationForIndex=function(e){if(e<0||e>this.string.length)return null;for(var t=0,n=this.offsets;n[t+1]<=e;)t++;var r=e-n[t];return{line:t,column:r}},e.prototype.indexForLocation=function(e){var t=e.line,n=e.column;return t<0||t>=this.offsets.length||n<0||n>this.lengthOfLine(t)?null:this.offsets[t]+n},e.prototype.lengthOfLine=function(e){var t=this.offsets[e];return(e===this.offsets.length-1?this.string.length:this.offsets[e+1])-t},e}();e.LinesAndColumns=r,e.default=r})),Cf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=t(Sf()),r=K();function i(e,t){if(t.length===0)return``;let i=Object.keys(t[0]).filter(e=>e!==`type`&&e!==`value`&&e!==`start`&&e!==`end`&&e!==`loc`),o=Object.keys(t[0].type).filter(e=>e!==`label`&&e!==`keyword`),s=[`Location`,`Label`,`Raw`,...i,...o],c=new n.default(e),l=[s,...t.map(d)],u=s.map(()=>0);for(let e of l)for(let t=0;t<e.length;t++)u[t]=Math.max(u[t],e[t].length);return l.map(e=>e.map((e,t)=>e.padEnd(u[t])).join(` `)).join(`
255
- `);function d(t){let n=e.slice(t.start,t.end);return[p(t.start,t.end),r.formatTokenType.call(void 0,t.type),a(String(n),14),...i.map(e=>f(t[e],e)),...o.map(e=>f(t.type[e],e))]}function f(e,t){return e===!0?t:e===!1||e===null?``:String(e)}function p(e,t){return`${m(e)}-${m(t)}`}function m(e){let t=c.locationForIndex(e);return t?`${t.line+1}:${t.column+1}`:`Unknown`}}e.default=i;function a(e,t){return e.length>t?`${e.slice(0,t-3)}...`:e}})),wf=/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=K(),r=t(Td());function i(e){let t=/* @__PURE__ */ new Set;for(let r=0;r<e.tokens.length;r++)e.matches1AtIndex(r,n.TokenType._import)&&!e.matches3AtIndex(r,n.TokenType._import,n.TokenType.name,n.TokenType.eq)&&a(e,r,t);return t}e.default=i;function a(e,t,r){t++,e.matches1AtIndex(t,n.TokenType.parenL)||(e.matches1AtIndex(t,n.TokenType.name)&&(r.add(e.identifierNameAtIndex(t)),t++,e.matches1AtIndex(t,n.TokenType.comma)&&t++),e.matches1AtIndex(t,n.TokenType.star)&&(t+=2,r.add(e.identifierNameAtIndex(t)),t++),e.matches1AtIndex(t,n.TokenType.braceL)&&(t++,o(e,t,r)))}function o(e,t,i){for(;;){if(e.matches1AtIndex(t,n.TokenType.braceR))return;let a=r.default.call(void 0,e,t);if(t=a.endIndex,a.isType||i.add(a.rightName),e.matches2AtIndex(t,n.TokenType.comma,n.TokenType.braceR)||e.matches1AtIndex(t,n.TokenType.braceR))return;if(e.matches1AtIndex(t,n.TokenType.comma))t++;else throw Error(`Unexpected token: ${JSON.stringify(e.tokens[t])}`)}}})),Tf=(/* @__PURE__ */ o((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){return e&&e.__esModule?e:{default:e}}var n=t(jd()),r=t(Id()),i=Ld(),a=t(Rd()),o=t(Bd()),s=Gd(),c=ef(),l=t(nf()),u=t(xf());t(Cf());var d=t(wf());function f(e,t){s.validateOptions.call(void 0,t);try{let n=p(e,t),i=new u.default(n,t.transforms,!!t.enableLegacyBabel5ModuleInterop,t).transform(),a={code:i.code};if(t.sourceMapOptions){if(!t.filePath)throw Error(`filePath must be specified when generating a source map.`);a={...a,sourceMap:r.default.call(void 0,i,t.filePath,t.sourceMapOptions,e,n.tokenProcessor.tokens)}}return a}catch(e){throw t.filePath&&(e.message=`Error transforming ${t.filePath}: ${e.message}`),e}}e.transform=f;function p(e,t){let r=t.transforms.includes(`jsx`),s=t.transforms.includes(`typescript`),u=t.transforms.includes(`flow`),f=t.disableESTransforms===!0,p=c.parse.call(void 0,e,r,s,u),m=p.tokens,h=p.scopes,g=new o.default(e,m),_=new i.HelperManager(g),v=new l.default(e,m,u,f,_),y=!!t.enableLegacyTypeScriptModuleInterop,b=null;return t.transforms.includes(`imports`)?(b=new n.default(g,v,y,t,t.transforms.includes(`typescript`),!!t.keepUnusedImports,_),b.preprocessTokens(),a.default.call(void 0,v,h,b.getGlobalNames()),t.transforms.includes(`typescript`)&&!t.keepUnusedImports&&b.pruneTypeOnlyImports()):t.transforms.includes(`typescript`)&&!t.keepUnusedImports&&a.default.call(void 0,v,h,d.default.call(void 0,v)),{tokenProcessor:v,scopes:h,nameManager:g,importProcessor:b,helperManager:_}}})))();function Ef(e,t){let n=e[t],r=t+1;for(;r<e.length&&e[r]!==n;)r+=e[r]===`\\`?2:1;return r+1}function Df(e,t,n){let r=``,i=0,a=t;for(;a<e.length;){let t=e[a],o=e[a+1];if(t===`/`&&o===`/`)for(;a<e.length&&e[a]!==`
256
- `;)a++;else if(t===`/`&&o===`*`){let t=e.indexOf(`*/`,a+2);a=t<0?e.length:t+2,r+=` `}else if(t===`"`||t===`'`)a=Ef(e,a),r+=`${t}${t}`;else if(t==="`"){for(r+="`",a++;a<e.length&&e[a]!=="`";)if(e[a]===`\\`)a+=2;else if(e[a]===`$`&&e[a+1]===`{`){let t=Df(e,a+2,`expression`);r+=` ${t.text} `,a=t.end}else a++;r+="`",a++}else{if(t===`{`&&i++,t===`}`){if(n===`expression`&&i===0)return{end:a+1,text:r};i--}r+=t,a++}}return{end:a,text:r}}const Of=e=>Df(e,0,`code`).text,kf=`@ryugi/report`,Af=`__ryugi_h`;function jf(e){let t=e.message,n=/\((\d+):(\d+)\)/.exec(t);return n?`report.tsx:${n[1]}:${Number(n[2])+1} ${t.replace(/\s*\(\d+:\d+\)/,``)}`:`report.tsx: ${t}`}const Mf=/^[a-z0-9][a-z0-9-]*$/,Nf=/^[\w.-]+\.(?:mjs|js|cjs)$/,Pf=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Ff=e=>typeof e==`string`?e:``;function If(e,t){if(!Pf(t))return`source.json must hold an object`;let n=Ff(t.title).trim();if(!n)return`title is required`;let r=Ff(t.script);if(!Nf.test(r)||r.startsWith(`.`))return`script must be a .mjs, .js or .cjs file in this folder`;let i=t.args??[];return!Array.isArray(i)||i.some(e=>typeof e!=`string`)?`args must be a list of strings`:{id:e,title:n,description:Ff(t.description),input:Ff(t.input),script:r,args:i}}const Lf=/* @__PURE__ */ new Set([`Stat`,`LineChart`,`BarChart`,`AreaChart`,`PieChart`,`ScatterChart`,`Table`]),Rf=/* @__PURE__ */ new Set([...Lf,`Callout`,`Section`,`Image`]),zf=/^assets\/(?:[\w-][\w.-]*\/)*[\w-][\w.-]*\.(?:png|jpe?g|gif|webp|avif|svg)$/i,Bf=[`fetch`,`XMLHttpRequest`,`WebSocket`,`EventSource`,`require`,`setInterval`,`setTimeout`,`document`,`window`,`localStorage`,`sessionStorage`,`globalThis`,`eval`,`Function`,`location`,`navigator`],Vf=[`createElement`,`constructor`,`__proto__`],Hf=[...Bf.map(e=>({name:e,pattern:RegExp(`(?<![.\\w$])${e}(?![\\w$])`)})),...Vf.map(e=>({name:e,pattern:RegExp(`(?<![\\w$])${e}(?![\\w$])`)})),{name:`import()`,pattern:/(?<![.\w$])import\s*\(/}],Uf=/^\s*import\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Wf=/^\.\/data\/([^/]+)\.json$/,Gf=RegExp(`${Af}\\(\\s*(?:'([^']*)'|"([^"]*)"|([A-Za-z_$][\\w$.]*))\\s*,\\s*`,`g`),Kf=/^(?:"([^"]*)"|'([^']*)')$/;function qf(e){try{let{code:t}=(0,Tf.transform)(e,{transforms:[`typescript`,`jsx`],jsxPragma:Af,jsxFragmentPragma:`__ryugi_fragment`,production:!0});return{code:t}}catch(e){return{error:jf(e)}}}function Jf(e,t){let n=/* @__PURE__ */ new Map;if(e[t]!==`{`)return n;let r=0,i=null,a=null,o=-1,s=t+1;for(let c=t;c<e.length;c++){let t=e[c];if(i)t===`\\`?c++:t===i&&(i=null);else if(t===`"`||t===`'`||t==="`")i=t;else if(t===`{`||t===`[`||t===`(`)r++;else if(t===`}`||t===`]`||t===`)`){if(r--,r===0)return a!==null&&n.set(a,e.slice(o,c).trim().replace(/,$/,``).trim()),n}else r===1&&(t===`:`&&a===null?(a=e.slice(s,c).trim(),o=c+1):t===`,`&&(a!==null&&n.set(a,e.slice(o,c).trim()),a=null,s=c+1))}return n}function Yf(e){let t=[];for(let n of e.matchAll(Gf)){let r=n[1]??n[2],i=r??n[3];t.push({tag:r===void 0?i:`<${r}>`,props:r===void 0?Jf(e,n.index+n[0].length):/* @__PURE__ */ new Map})}return t}const Xf=e=>{let t=e===void 0?null:Kf.exec(e);return t?t[1]??t[2]:void 0};function Zf(e){if(e===void 0)return null;let t=Xf(e);if(t!==void 0)return[t];if(!e.startsWith(`[`)||!e.endsWith(`]`))return null;let n=e.slice(1,-1).split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>Xf(e));return n.every(e=>e!==void 0)?[...new Set(n)]:null}function Qf(e){let t=[];for(let n of e){if(!Rf.has(n.tag))continue;let e=Xf(n.props.get(`id`));if(e===void 0)continue;let r=Xf(n.props.get(n.tag===`Image`?`caption`:`title`)),i=Xf(n.props.get(n.tag===`Table`?`rowKey`:`x`));t.push({id:e,tag:n.tag,...r===void 0?{}:{title:r},...i!==void 0&&Lf.has(n.tag)?{key:i}:{},sources:Zf(n.props.get(`source`))??[]})}return t}function $f(e){let t=qf(e);return`code`in t?Qf(Yf(t.code)):[]}function ep(e,{sources:t,assets:n=[]}){let r=[],i=e=>{r.includes(e)||r.push(e)};new TextEncoder().encode(e).byteLength>65536&&i(`report.tsx is over 64 KB; move data into a data source`);let a=qf(e);`error`in a&&i(a.error),(e.match(/\bexport\s+default\b/g)??[]).length!==1&&i(`report.tsx needs one export default component`);let o=/* @__PURE__ */ new Set;for(let[,n]of e.matchAll(Uf)){if(n===`@ryugi/report`)continue;let e=Wf.exec(n);!e||!Mf.test(e[1])?i(`import from "${n}" is not allowed; import from ${kf} or ./data/<source>.json`):(t.includes(e[1])||i(`${n}: there is no data source "${e[1]}"`),o.add(e[1]))}if(!(`code`in a))return r;let s=Of(a.code);for(let{name:e,pattern:t}of Hf)t.test(s)&&i(`${e} is not allowed in a report`);let c=/* @__PURE__ */ new Set;for(let e of Yf(a.code)){if(e.tag.startsWith(`<`)){i(`${e.tag} is a native element; use the ${kf} components`);continue}if(e.tag===`Param`&&e.props.has(`min`)!==e.props.has(`max`)&&i(`<Param> takes min and max together, or neither`),!Rf.has(e.tag))continue;let t=e.props.get(`id`),r=Xf(t);if(r===void 0){i(`<${e.tag}> needs id="<kebab-case>"`);continue}let a=`<${e.tag} id="${r}">`;if(Mf.test(r)||i(`${a}: an id is lowercase letters, digits and hyphens`),c.has(r)&&i(`id "${r}" is used twice`),c.add(r),e.tag===`Image`){e.props.has(`alt`)||i(`${a} needs alt text`);let t=Xf(e.props.get(`src`));t===void 0||!zf.test(t)?i(`${a}: src is an image file under assets/, written as a string such as "assets/chart.png"`):n.includes(t)||i(`${a}: ${t} does not exist`);continue}if(!Lf.has(e.tag))continue;let s=Zf(e.props.get(`source`));if(!s||s.length===0)i(`${a} needs source="<source-id>"`);else for(let e of s)o.has(e)||i(`${a}: source "${e}" is not imported from ./data/${e}.json`)}return r}const tp=[{label:`an absolute path`,pattern:/\/Users\/[^\s'"`]+/,shown:`/Users/…`},{label:`an absolute path`,pattern:/\/home\/[^\s'"`]+/,shown:`/home/…`},{label:`an absolute path`,pattern:/\b[A-Za-z]:\\{1,2}(?:Users|Documents and Settings)\b/,shown:`C:\\…`}],np=[{label:`what looks like an API key`,pattern:/\bsk-[A-Za-z0-9_-]{20,}/,shown:`sk-…`},{label:`what looks like a GitHub token`,pattern:/\b(?:ghp|gho|ghs|ghu|github_pat)_[A-Za-z0-9_]{20,}/,shown:`ghp_…`},{label:`what looks like an AWS access key`,pattern:/\bAKIA[0-9A-Z]{16}\b/,shown:`AKIA…`},{label:`what looks like a private key`,pattern:/-----BEGIN [A-Z ]*PRIVATE KEY-----/,shown:`-----BEGIN …`}],rp=/KEY|TOKEN|SECRET|PASSWORD|PASSWD|PRIVATE|CREDENTIAL|AUTH|COOKIE|SESSION|DSN/i;function ip(e,t={}){let n=Object.entries(t).filter(([e,t])=>rp.test(e)&&t.length>=8),r=[];for(let t of e){let e=t.secretsOnly||t.path.startsWith(`data/`)?np:[...tp,...np];for(let[i,a]of t.text.split(`
257
- `).entries()){let o=`publish scan: ${t.path}:${i+1}: `,s=n.find(([,e])=>a.includes(e));if(s){r.push(`${o}the value of ${s[0]} from .env; read it from env instead`);continue}let c=e.find(e=>e.pattern.test(a));if(!c)continue;let l=tp.includes(c)?`pass it as an argument or read it from env`:`read it from env instead`;r.push(`${o}${c.label} ("${c.shown}"); ${l}`)}}return r}const ap=`sources`,op=`source.json`;function sp(e){let t;try{t=d.default.readdirSync(p.default.join(e,ap),{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return{sources:[],issues:[]}}let n=[],r=[];for(let i of t){let t=`${ap}/${i}`;if(!Mf.test(i)){r.push(`${t}: a source id is lowercase letters, digits and hyphens`);continue}let a=p.default.join(e,ap,i,op),o;try{o=d.default.readFileSync(a,`utf8`)}catch{r.push(`${t}: ${op} not found`);continue}let s;try{s=JSON.parse(o)}catch{r.push(`${t}/${op}: not valid JSON`);continue}let c=If(i,s);typeof c==`string`?r.push(`${t}/${op}: ${c}`):d.default.existsSync(p.default.join(e,`sources`,i,c.script))?n.push(c):r.push(`${t}/${op}: script ${c.script} not found`)}return{sources:n,issues:r}}const cp=1048576,lp=/^ryugi:input (.+)$/gm,up=`data`;function dp(e){try{return JSON.parse(d.default.readFileSync(e,`utf8`))}catch{return null}}function fp(e){return e%cp==0?`${e/cp} MB`:e%1024==0?`${e/1024} KB`:`${e} B`}function pp(e){return p.default.resolve(e,`..`,`..`,`..`,`..`)}function mp(e){let t={};for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e||e.startsWith(`#`))continue;let r=/^(?:export\s+)?([A-Za-z_][\w.]*)\s*=\s*(.*)$/.exec(e);if(!r)continue;let i=r[2],a=i[0];i=(a===`"`||a===`'`)&&i.endsWith(a)&&i.length>=2?i.slice(1,-1):i.replace(/\s+#.*$/,``),t[r[1]]=i}return t}function hp(e){let t={};for(let n of[`.env`,`.env.local`])try{Object.assign(t,mp(d.default.readFileSync(p.default.join(e,n),`utf8`)))}catch{continue}return t}function gp(e,t){let n=0;try{for(let r of d.default.readdirSync(e))r!==t&&r.endsWith(`.json`)&&(n+=d.default.statSync(p.default.join(e,r)).size)}catch{return 0}return n}function _p(e,t){d.default.mkdirSync(p.default.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;d.default.writeFileSync(n,t),d.default.renameSync(n,e)}function vp(e,t,n,r){return new Promise(i=>{let a=(0,l.spawn)(e.node,[...w(`report script`),t,...n],{cwd:r,env:e.env,detached:process.platform!==`win32`,stdio:[`ignore`,`pipe`,`pipe`]}),o=[],s=0,c=``,u=!1,d=()=>{try{a.pid&&process.platform!==`win32`?process.kill(-a.pid,`SIGKILL`):a.kill(`SIGKILL`)}catch{a.kill(`SIGKILL`)}},f=e=>{if(u)return;u=!0,clearTimeout(p);let t=[...c.matchAll(lp)].at(-1)?.[1]?.trim();i(t?{...e,input:t}:e)},p=setTimeout(()=>{d(),f({error:`timed out after ${e.timeoutMs/1e3} s`})},e.timeoutMs);a.stdout.on(`data`,t=>{s+=t.byteLength,s>e.maxBytes?(d(),f({error:`printed more than ${fp(e.maxBytes)}`})):o.push(t)}),a.stderr.on(`data`,e=>{c=(c+e.toString(`utf8`)).slice(-16384)}),a.on(`error`,e=>f({error:`could not start: ${e.message}`})),a.on(`close`,e=>{if(e!==0){let t=c.replaceAll(lp,``).trim().slice(-4096);f({error:`exited with code ${e}${t?`: ${t}`:``}`})}else f({stdout:Buffer.concat(o).toString(`utf8`)})})})}function yp(e){let t={timeoutMs:e.timeoutMs??6e4,maxBytes:e.maxBytes??2*cp,maxTotalBytes:e.maxTotalBytes??10*cp,node:e.node??process.execPath,env:e.env??process.env},n=e.now??(()=>/* @__PURE__ */ new Date),r=/* @__PURE__ */ new Map,i=t=>p.default.join(e.stateDir,...t.split(`/`),`sources.json`),a=e=>dp(i(e))??{},o=(e,t,n)=>U(i(e),{...a(e),[t]:n}),s=async(e,r,i)=>{let s=n(),c=a(r)[i],l=(e,t=``)=>{let a={startedAt:s.toISOString(),durationMs:n().getTime()-s.getTime(),ok:!1,error:e,bytes:c?.bytes??0,input:t||c?.input||``,...c?.asOf?{asOf:c.asOf}:{}};return o(r,i,a),a},u=sp(e).sources.find(e=>e.id===i);if(!u)return l(`source ${i} not found`);let d=pp(e),f=await vp({...t,env:{...t.env,...hp(d)}},p.default.join(e,`sources`,i,u.script),u.args,d),m=f.input??u.input;if(f.error!==void 0)return l(f.error,m);let h=(f.stdout??``).trim();try{JSON.parse(h)}catch(e){return l(`did not print valid JSON: ${e.message}`,m)}let g=p.default.join(e,up),_=Buffer.byteLength(h);if(gp(g,`${i}.json`)+_>t.maxTotalBytes)return l(`the report data would pass ${fp(t.maxTotalBytes)}`,m);_p(p.default.join(g,`${i}.json`),h);let v=s.toISOString(),y={startedAt:v,durationMs:n().getTime()-s.getTime(),ok:!0,bytes:_,input:m,asOf:v};return o(r,i,y),y};return{run:(e,t,n)=>{let i=`${t}:${n}`,a=r.get(i);if(a)return a;let o=s(e,t,n).finally(()=>r.delete(i));return r.set(i,o),o},records:a,active:()=>r.size>0}}function bp(e,t){let n;try{n=d.default.readdirSync(p.default.join(e,t),{withFileTypes:!0})}catch{return[]}return n.flatMap(n=>{if(n.name.startsWith(`.`))return[];let r=`${t}/${n.name}`;return n.isDirectory()?bp(e,r):n.isFile()?[{path:r,text:d.default.readFileSync(p.default.join(e,r),`utf8`)}]:[]})}function xp(e){let t={};for(let n of[`.env`,`.env.local`])try{Object.assign(t,mp(d.default.readFileSync(p.default.join(pp(e),n),`utf8`)))}catch{continue}return t}const Sp=(e,t)=>yp({stateDir:p.default.join(p.default.dirname(p.default.dirname(e)),`.state`)}).records(`report/${t}`);function Cp(e,t){let n=p.default.join(e,H.report),r=Object.entries(Sp(e,t)).flatMap(([e,t])=>t.input?[{path:`${ap}/${e} (last run input)`,text:t.input,secretsOnly:!0}]:[]);return ip([...d.default.existsSync(n)?[{path:H.report,text:d.default.readFileSync(n,`utf8`)}]:[],...bp(e,ap),...bp(e,up),...r],xp(e))}const wp=`comments.json`;function Tp(e,t=`assets`){let n;try{n=d.default.readdirSync(p.default.join(e,t),{withFileTypes:!0})}catch{return[]}return n.flatMap(n=>{let r=`${t}/${n.name}`;return n.isDirectory()?Tp(e,r):n.isFile()?[r]:[]})}const Ep=/<Report\b[^>]*?\btitle=(?:"([^"]*)"|'([^']*)'|\{\s*(?:"([^"]*)"|'([^']*)')\s*\})/,Dp=/^\s*import\s+[^'"]*?\s+from\s+['"]\.\/data\/([a-z0-9][a-z0-9-]*)\.json['"]/gm;function Op(e){let t=Ep.exec(e);return(t?.[1]??t?.[2]??t?.[3]??t?.[4])?.trim()||void 0}function kp(e,t,n){let{sources:r,issues:i}=sp(e),a=r.map(e=>e.id),o=[...i,...ep(n,{sources:a,assets:Tp(e)})];for(let[,r]of n.matchAll(Dp))a.includes(r)&&(d.default.existsSync(p.default.join(e,`data`,`${r}.json`))||o.push(`data/${r}.json is missing; run ryugi report refresh --artifact report/${t}`));return o}function Ap(e,t){let n;try{n=d.default.readFileSync(p.default.join(e,H.report),`utf8`)}catch{return{title:t,warnings:[`${H.report} not found`],version:ir(e,wp)}}return{title:Op(n)??t,warnings:[...kp(e,t,n),...Cp(e,t)],version:ir(e,wp)}}const jp=e=>e.replaceAll(/[&<>"]/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`})[e]),Mp=e=>JSON.stringify(e).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`);function Np(e,t){let n={};for(let r of t)try{n[r]=JSON.parse(d.default.readFileSync(p.default.join(e,up,`${r}.json`),`utf8`))}catch{continue}return n}function Pp(e){let t=``;try{t=d.default.readFileSync(p.default.join(e,H.report),`utf8`)}catch{t=``}let n=Np(e,sp(e).sources.map(e=>e.id)),r=`${t}\0${Object.keys(n).sort().join(`,`)}`;return{pageKey:(0,u.createHash)(`sha1`).update(r).digest(`hex`).slice(0,12),data:n}}function Fp(e,t,n,r={}){let i;try{i=d.default.readFileSync(p.default.join(e,H.report),`utf8`)}catch{return null}let{sources:a}=sp(e),o={source:i,data:Np(e,a.map(e=>e.id)),sources:Object.fromEntries(a.map(e=>[e.id,{title:e.title,...r[e.id]?.asOf?{asOf:r[e.id].asOf}:{}}]))};return`<!doctype html>
258
- <html lang="en">
259
- <head>
260
- <meta charset="utf-8">
261
- <meta name="viewport" content="width=device-width, initial-scale=1">
262
- <title>${jp(Op(i)??t)}</title>
263
- </head>
264
- <body>
265
- <div id="ryugi-report-root"></div>
266
- <script type="application/json" id="ryugi-report-config">${Mp(o)}<\/script>
267
- <script type="module" src="${jp(n)}"><\/script>
268
- </body>
269
- </html>
270
- `}const Ip=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Lp=e=>`{ ${Object.keys(e).join(`, `)} }`;function Rp(e){if(Array.isArray(e)){let t=e[0];return Ip(t)?`array of ${e.length} · ${Lp(t)}`:`array of ${e.length}`}return Ip(e)?`object · ${Lp(e)}`:e===null?`null`:typeof e}const zp=65536;function Bp(e){try{let t=d.default.readFileSync(e,`utf8`);return t.length>zp?`${t.slice(0,zp)}\n…`:t}catch{return``}}function Vp(e){try{let t=d.default.readFileSync(e,`utf8`);return{bytes:Buffer.byteLength(t),shape:Rp(JSON.parse(t))}}catch{return{bytes:0,shape:null}}}function Hp(e,t){return sp(e).sources.map(n=>{let r=t[n.id],i=`${up}/${n.id}.json`;return{id:n.id,title:n.title,description:n.description,input:r?.input||n.input,script:n.script,code:Bp(p.default.join(e,ap,n.id,n.script)),file:i,...Vp(p.default.join(e,i)),...r?{ok:r.ok,durationMs:r.durationMs,...r.asOf?{asOf:r.asOf}:{},...r.error?{error:r.error}:{}}:{}}})}function Up(e){try{return $f(d.default.readFileSync(p.default.join(e,H.report),`utf8`))}catch{return[]}}function Wp(e,t){let n=Fp(e,t,`/_ryugi/runtime/ryugi-report.js`,Sp(e,t));return new Map(n===null?[]:[[`index.html`,Buffer.from(n)]])}const Gp=(e,t)=>Hp(e,Sp(e,t)).map(({error:e,...t})=>t),Kp={threads:(e,t,n)=>{let r=new Map(e.reportComments.list(t,n,!0).map(e=>[e.id,e]));return e.reportComments.comments(t).threads.map(e=>{let t=r.get(e.id);return{...e,...t,anchor:t?.dataChanged?{...e.anchor,dataChanged:!0}:e.anchor,messages:e.messages.map(({avatar:e,...t})=>t)}})}},qp=Symbol(`relayed-by-owner`),Jp=e=>Object.assign(e,{[qp]:!0}),Yp=e=>e[qp]===!0,Xp=/^[a-z0-9][a-z0-9-]{0,63}$/,Zp=e=>typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e)||typeof e==`string`&&e.length<=200,Qp=e=>typeof e==`string`&&e.length>0&&e.length<=200;function $p(e){if(!Va(e))return null;let{series:t,x:n}=e;return Qp(t)&&(Qp(n)||typeof n==`number`&&Number.isFinite(n))?{series:t,x:n}:null}function em(e){if(!Va(e))return;let t={};if(Qp(e.tag)&&(t.tag=e.tag),Qp(e.title)&&(t.title=e.title),e.value!==void 0){let n=JSON.stringify(e.value);n!==void 0&&n.length<=4e3&&(t.value=JSON.parse(n))}if(Va(e.params)){let n=Object.entries(e.params).filter(([e,t])=>Qp(e)&&Zp(t)).slice(0,20);n.length&&(t.params=Object.fromEntries(n))}if(Va(e.data)){let n=Object.entries(e.data).filter(([e,t])=>Xp.test(e)&&typeof t==`string`&&/^[0-9a-f]{40}$/.test(t));n.length&&(t.data=Object.fromEntries(n))}return Object.keys(t).length?t:void 0}function tm(e){if(!Va(e))return null;let{block:t,point:n,row:r,snapshot:i}=e;if(typeof t!=`string`||!Xp.test(t)||n!==void 0&&r!==void 0)return null;let a={block:t};if(n!==void 0){let e=$p(n);if(!e)return null;a.point=e}if(r!==void 0){if(!Qp(r))return null;a.row=r}let o=em(i);return o&&(a.snapshot=o),a}const nm={read:tm,same:(e,t)=>e.block===t.block&&e.row===t.row&&e.point?.series===t.point?.series&&e.point?.x===t.point?.x,missing:`a new thread needs a report anchor (the block id); dropped it`},rm=()=>({version:1,threads:[]}),im=e=>Ga(e,nm),am=(e,t,n,r,i,a)=>Za(e,t,n,r,i,a,nm);function om(e,t,n,r,i){return t.op===`create`?{...e,threads:[...e.threads,eo(t.anchor,`human`,t.text,n,r,i)]}:no(e,t,n,r,i)}function sm(e,t,n,r,i){if(t.op!==`add`)return uo(e,t,n,r,i);let a=eo(t.anchor,`agent`,t.text,n,r,{name:i});return{file:{...e,threads:[...e.threads,a]},threadId:a.id,messageId:a.messages[0].id}}function cm(e,t,n){if(!Array.isArray(e)||n===void 0)return;let r=t.row??(t.point?String(t.point.x):void 0);if(r===void 0)return;let i=e.find(e=>Va(e)&&String(e[n])===r);if(i)return t.point?i[t.point.series]:i}const lm={empty:rm,saved:im,merge:am,human:(e,t,n,r,i)=>om(e,t,n,r,i),agent:sm};function um(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.op!==`create`){let t=ms(e);return t&&t.op!==`create`?t:null}let n=tm(t.anchor);return n&&fs(t.text)&&t.text.length>0?{op:`create`,anchor:n,text:t.text}:null}function dm(e){if(typeof e!=`object`||!e)return null;let t=e,n=fs(t.text)&&t.text.length>0?t.text:null;if(t.op===`add`){if(!n)return null;let e=tm({block:t.block,point:t.point,row:t.row});return e?{op:`add`,block:e.block,...e.point?{point:e.point}:{},...e.row?{row:e.row}:{},text:n}:null}return typeof t.threadId!=`string`||t.threadId.length===0?null:t.op===`reply`?n?{op:`reply`,threadId:t.threadId,text:n}:null:t.op===`resolve`?{op:`resolve`,threadId:t.threadId}:null}function fm(e){try{return $f(d.default.readFileSync(p.default.join(e,H.report),`utf8`))}catch{return null}}function pm(e,t){try{let n=d.default.readFileSync(p.default.join(e,up,`${t}.json`));return{sha:u.default.createHash(`sha1`).update(n).digest(`hex`),value:JSON.parse(n.toString(`utf8`))}}catch{return null}}function mm(e){let t=/* @__PURE__ */ new Map,n=$o(e.stateDir,`report`),r=t=>p.default.join(e.root,`report`,t),i=t=>Es(e.stateDir,`report/${t}`),a=n=>{let i=t.get(n);return i||(i=vs(p.default.join(r(n),`comments.json`),lm,e.names,{artifact:`report/${n}`,savesDir:p.default.join(e.stateDir,`report`,n,`comment-saves`)}),t.set(n,i)),i},o=(e,t)=>{let n=r(e),i=fm(n)?.find(e=>e.id===t.block);if(!i)return t;let a={},o=t.snapshot?.value;for(let e of i.sources){let r=pm(n,e);r&&(a[e]=r.sha,o===void 0&&(t.point||t.row)&&(o=cm(r.value,t,i.key)))}return{block:t.block,...t.point?{point:t.point}:{},...t.row?{row:t.row}:{},snapshot:{tag:i.tag,...i.title?{title:i.title}:{},...o===void 0?{}:{value:o},...t.snapshot?.params?{params:t.snapshot.params}:{},...Object.keys(a).length?{data:a}:{}}}},s=e=>{let t=r(e),n=fm(t),i=/* @__PURE__ */ new Map,o=e=>(i.has(e)||i.set(e,pm(t,e)?.sha??null),i.get(e)),s=[],c=[];for(let t of a(e).current().threads){n&&!n.some(e=>e.id===t.anchor.block)&&s.push(t.id);let e=t.anchor.snapshot?.data??{};Object.entries(e).some(([e,t])=>o(e)!==t)&&c.push(t.id)}return{orphans:s,dataChanged:c}},c=e=>({comments:a(e).current(),...s(e),listening:i(e)}),l=t=>e.broadcast({type:ke,artifact:`report/${t}`,...c(t)}),u=e=>{let{orphans:t,dataChanged:n}=s(e);return e=>({...e,block:e.anchor.block,orphan:t.includes(e.id),dataChanged:n.includes(e.id),waitingOn:ro(e),messages:e.messages.map(({avatar:e,...t})=>t)})};return{comments:e=>a(e).current(),listening:i,state:c,apply(e,t){return a(e).apply(t.op===`create`?{...t,anchor:o(e,t.anchor)}:t),l(e),c(e)},applyAgent(e,t,n){let i;if(t.op===`add`){let n=fm(r(e));if(!n)throw Error(`report/${e} has no readable report.tsx yet`);if(!n.some(e=>e.id===t.block))throw Error(`no block ${t.block} in report/${e}; its blocks are: ${n.map(e=>e.id).join(`, `)}`);let{text:a,op:s,...c}=t;i={op:`add`,anchor:o(e,c),text:a}}else i=t;let{threadId:s,messageId:c}=a(e).applyAgent(i,n);return l(e),{threadId:s,...c?{messageId:c}:{}}},list(e,t,r){a(e).sync()&&l(e);let i=a(e).current(),o=u(e);if(r)return i.threads.filter(e=>!e.messages.every(e=>e.deleted)).map(o);let{threads:s,newest:c}=co(i,n.get(e,t));return c&&n.set(e,t,c),s.map(o)},sync(e){a(e).sync()&&l(e)},reportChanged(e){t.has(e)&&l(e)}}}const hm=/^\/api\/report\/([^/]+)\/refresh$/,gm=/^\/api\/report\/([^/]+)\/history(?:\/(\d+))?$/,_m=/^\/api\/report\/([^/]+)\/state$/,vm=/^\/api\/report\/([^/]+)\/comments$/,ym=/^\/api\/agent\/report\/([^/]+)\/comments$/,bm=/^(?:127\.\d+\.\d+\.\d+|::1|::ffff:127\.\d+\.\d+\.\d+)$/,xm=e=>Yp(e)||bm.test(e.socket.remoteAddress??``);function Sm(e,t){try{return Rp(JSON.parse(d.default.readFileSync(p.default.join(e,up,`${t}.json`),`utf8`)))}catch{return null}}const Cm={relay:`background`,path:hm,auth:`viewer`,methods:[`POST`],handle:async(e,t,n,{match:r})=>{if(!xm(e)){B(t,403,{error:`data sources only run from this machine`});return}let i=r[1],a=W(n.root,`report`,i);if(!a){B(t,404,{error:`report/${i} not found`});return}let o=await yc(e),s=o&&typeof o==`object`&&typeof o.source==`string`?o.source:null,{sources:c,issues:l}=sp(a),u=s?[s]:c.map(e=>e.id),d=await Promise.all(u.map(e=>n.sourceRunner.run(a,`report/${i}`,e)));B(t,200,{issues:l,sources:u.map((e,t)=>({id:e,...d[t],shape:d[t].ok?Sm(a,e):null}))})}},wm={path:_m,auth:`viewer`,handle:(e,t,n,{match:r})=>{let i=r[1];W(n.root,`report`,i)?B(t,200,n.reportComments.state(i)):B(t,404,{error:`report/${i} not found`})}},Tm={path:vm,methods:[`POST`],auth:`same-origin`,handle:async(e,t,n,{match:r})=>{let i=r[1];if(!W(n.root,`report`,i)){B(t,404,{error:`report/${i} not found`});return}let a=um(await yc(e));if(!a)B(t,400,{error:`not a report comment op`});else try{B(t,200,n.reportComments.apply(i,a))}catch(e){B(t,400,{error:e.message})}}},Em={path:ym,methods:[`POST`],auth:`agent`,handle:async(e,t,n,{match:r})=>{let i=r[1];if(!W(n.root,`report`,i)){B(t,404,{error:`report/${i} not found`});return}let a=await yc(e),o=typeof a==`object`&&a?a:{},s=dm(o);if(!s)B(t,400,{error:`not an agent comment op: use add {block, point?, row?, text}, reply {threadId, text} or resolve {threadId}; text must not be empty`});else try{B(t,200,n.reportComments.applyAgent(i,s,bc(o)))}catch(e){B(t,400,{error:e.message})}}},Dm={path:gm,auth:`viewer`,handle:(e,t,n,{match:r})=>{let i=r[1],a=W(n.root,`report`,i);if(!a){B(t,404,{error:`report/${i} not found`});return}if(r[2]===void 0){B(t,200,{entries:n.reportHistory.list(i,a)});return}let o=n.reportHistory.diff(i,Number(r[2]));o===null?B(t,404,{error:`no history entry ${r[2]}`}):B(t,200,{lines:o})}},Om=/^(?:report\.tsx|sources\/.+|data\/[^/]+\.json)$/,km={read:Ap,threads:(e,t)=>e.reportComments.comments(t).threads,meta:(e,t,n)=>({sources:Hp(n,e.sourceRunner.records(`report/${t}`)),blocks:Up(n),...Pp(n)}),state:(e,t,n,r)=>({extra:`version`in r?{ran:e.ranVersions.get(`report/${t}`)===r.version}:{}}),onFilesChanged:(e,t,n,r)=>{(r.includes(`report.tsx`)||r.length===0)&&e.reportHistory.record(t,n),r.includes(`comments.json`)&&e.reportComments.sync(t),(r.some(e=>e!==`comments.json`)||r.length===0)&&e.reportComments.reportChanged(t)},check:{evidence:Ci},publishFiles:Wp,payloadNotFromSource:[`sources`],pull:{generated:()=>[`index.html`]},publish:(e,t,n)=>({title:n,sources:Gp(e,t)}),review:Kp,routes:[Cm,wm,Dm,Tm,Em],resolveFile:dt,ownPage:(e,t,n,r,i)=>n===`index.html`?Fp(e,t,r(`ryugi-report.js`),i?.sourceRunner.records(`report/${t}`)):void 0,isPage:e=>e===`index.html`,keepsLocal:e=>!Om.test(e)&&!zf.test(e)},Am=[`width`,`height`,`position`,`flex-grow`,`display`,`flex-direction`,`align-items`,`gap`,`padding`,`background-color`,`opacity`,`border-radius`,`border-style`,`font-size`,`color`,`box-shadow`],jm=`#0D99FF`,Mm=`M6.2 3.6C5 2.7 3.4 3.6 3.6 5.1L6 22.7C6.2 24.3 8.2 24.8 9.1 23.5L13 18.3C13.4 17.8 14 17.5 14.6 17.5L21.1 17.3C22.7 17.2 23.4 15.2 22.2 14.3Z`,Nm=`M13 3a9 9 0 0 1 0 18H4.5A1.5 1.5 0 0 1 3 19.5V13A10 10 0 0 1 13 3z`,Pm=(e,t,n)=>`url("data:image/svg+xml,${encodeURIComponent(e)}") ${t}, ${n}`,Fm=Pm(`<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 28 28'><path d='${Mm}' fill='none' stroke='white' stroke-width='4' stroke-linejoin='round'/><path d='${Mm}' fill='${jm}'/></svg>`,`3 3`,`default`),Im=Pm(`<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'><path d='${Nm}' fill='none' stroke='white' stroke-width='3' stroke-linejoin='round'/><path d='${Nm}' fill='${jm}'/><path d='M13 8.2v7.6M9.2 12h7.6' stroke='white' stroke-width='2.2' stroke-linecap='round'/></svg>`,`3 21`,`crosshair`);function Lm(e,t,n=`crosshair`,r=`default`){let i=e.document,a=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,o=/* @__PURE__ */ new WeakMap,s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set([`SCRIPT`,`STYLE`,`META`,`LINK`,`NOSCRIPT`,`HEAD`]),u=0,d=!1,f=`select`,p=``,m=null,h=0,g=0,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=!1,T=/* @__PURE__ */ new Map,E=/* @__PURE__ */ new Map,D=i.createElement(`style`);D.setAttribute(`data-ryugi-inspector`,``),D.textContent=`*{cursor:${r}!important}`;let O=(t,n)=>e.parent.postMessage({type:`ryugi:inspect:${t}`,session:a,connection:p,...n},`*`),k=e=>{let t=o.get(e);return t||(t=++u,o.set(e,t)),s.set(t,e),t},A=e=>(e.getAttribute(`data-layer-name`)||e.getAttribute(`aria-label`)||e.id||(e.childElementCount?``:e.textContent?.trim())||``).slice(0,100),j=e=>(e.id?`#${e.id}`:e.tagName.toLowerCase()+Array.from(e.classList).slice(0,2).map(e=>`.${e}`).join(``)).slice(0,200),ee=e=>{let t=[];for(let n=e;n&&n!==i.documentElement;n=n.parentElement){let e=n.tagName.toLowerCase(),r=n.parentElement,a=r&&n!==i.body?Array.from(r.children).filter(e=>e.tagName===n.tagName):[];if(t.unshift(n.id&&n.id.length<=64&&/^[A-Z][\w-]*$/i.test(n.id)?`${e}#${n.id}`:a.length>1?`${e}:nth-of-type(${a.indexOf(n)+1})`:e),n===i.body)break}return t.join(` > `).slice(0,4e3)},M=e=>{let t=o.get(e);return t!==void 0&&s.get(t)===e?t:null},N=(e,t)=>/^H[1-6]$/.test(e.tagName)?`Title`:[`IMG`,`SVG`,`CANVAS`,`VIDEO`].includes(e.tagName.toUpperCase())?`Image`:[`BUTTON`,`A`,`INPUT`,`SELECT`,`TEXTAREA`].includes(e.tagName)?`Button`:e.childElementCount?t.display.includes(`flex`)?t.flexDirection.startsWith(`row`)?`Row`:`Column`:t.display.includes(`grid`)?`Grid`:`Frame`:`Text`,P=e=>{let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}},F=(n,r=!1)=>{if(!m?.isConnected){m=null,O(`selection`,{selection:null,reason:n});return}let i=m,a=e.getComputedStyle(i),o=i.style,s={id:k(i),name:A(i),tag:i.tagName.toLowerCase(),selector:j(i),rect:v=P(i),css:Object.fromEntries(t.map(e=>[e,a.getPropertyValue(e)])),html:i.outerHTML.slice(0,2e4),widthMode:o?.width===`100%`?`fill`:o?.width===`max-content`?`hug`:`fixed`,heightMode:o?.height&&o.height!==`auto`?`fixed`:`hug`};O(`selection`,{selection:s,reason:n,toggle:r})},I=()=>{let e=[];for(let[t,n]of c)if(!t.isConnected)c.delete(t);else for(let[r,i]of n)e.push({id:k(t),name:A(t)||j(t),property:r,from:i.from,value:i.applied});let t=[];for(let e of T.keys())e.isConnected?t.push({id:k(e),name:A(e)||j(e)}):T.delete(e);O(`tweaks`,{tweaks:e,removed:t})},L=e=>{e.style&&!T.has(e)&&(T.set(e,{value:e.style.getPropertyValue(`display`),priority:e.style.getPropertyPriority(`display`)}),e.style.setProperty(`display`,`none`,`important`),m&&e.contains(m)&&(m=null))},te=e=>{let t=T.get(e);t&&(T.delete(e),e.style.getPropertyValue(`display`)===`none`&&e.style.getPropertyPriority(`display`)===`important`&&(t.value?e.style.setProperty(`display`,t.value,t.priority):e.style.removeProperty(`display`)))},R=()=>{if(!d||!i.body)return;s.clear();let t=[],n=!1,r=(i,a,o)=>{if(l.has(i.tagName)||i.hasAttribute(`data-ryugi-inspector`))return null;if(t.length>=2500||o>=50)return n=!0,null;let s=k(i),c={id:s,parentId:a,name:A(i),tag:i.tagName.toLowerCase(),selector:j(i),path:ee(i),kind:N(i,e.getComputedStyle(i)),children:[]};t.push(c);for(let e of i.children){if(t.length>=2500){n=!0;break}let i=r(e,s,o+1);i!==null&&c.children.push(i)}return s};r(i.body,null,0),O(`tree`,{nodes:t,truncated:n})},ne=()=>{h=0,d&&(R(),F(`update`),I())},z=new e.MutationObserver(()=>{d&&!h&&(h=e.setTimeout(ne,100))}),B=(e,t)=>e&&e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height,re=()=>{if(d){if(m?.isConnected){let e=P(m);B(v,e)||(v=e,O(`rect`,{id:k(m),rect:e}))}for(let[e,t]of E){let n=s.get(e);if(!n?.isConnected){E.delete(e);continue}let r=P(n);B(t,r)||(E.set(e,r),O(`rect`,{id:e,rect:r}))}if(_?.isConnected){let e=P(_),t=M(_);B(y,e)&&t===b||(y=e,b=t,O(`hover`,{rect:e,id:t}))}else y&&(y=null,b=null,O(`hover`,{rect:null,id:null}));g=e.requestAnimationFrame(re)}},ie=e=>!!e.closest(`[data-ryugi-inspector], script, style, link`),ae=t=>{d&&t.button===0&&t.target instanceof e.Element&&!ie(t.target)&&(t.preventDefault(),t.stopImmediatePropagation(),w?w=!1:f!==`comment`&&(m=t.target.closest(`svg`)||t.target,F(`user`,t.shiftKey||t.metaKey||t.ctrlKey)))},oe=t=>{d&&(t.button===2&&t.pointerType===`mouse`&&t.target instanceof e.Element?(t.preventDefault(),t.stopImmediatePropagation(),C={screenX:t.screenX,screenY:t.screenY,pointer:t.pointerId,panning:!1,target:t.target},i.documentElement.setPointerCapture?.(t.pointerId)):t.button===1?(t.preventDefault(),t.stopImmediatePropagation(),x={x:t.screenX,y:t.screenY,pointer:t.pointerId},i.documentElement.setPointerCapture?.(t.pointerId)):t.button===0&&t.target instanceof e.Element&&(t.preventDefault(),t.stopImmediatePropagation(),w=!1,S={x:t.clientX,y:t.clientY,screenX:t.screenX,screenY:t.screenY,pointer:t.pointerId,append:t.shiftKey||t.metaKey||t.ctrlKey,moved:!1},t.target.setPointerCapture?.(t.pointerId),O(`drag`,{phase:`start`,x:t.clientX,y:t.clientY,append:S.append,id:k(t.target.closest(`svg`)||t.target)})))},se=t=>{if(d){if(C&&t.pointerId===C.pointer){let e=t.screenX-C.screenX,n=t.screenY-C.screenY;if(!C.panning&&Math.hypot(e,n)<4)return;C.panning=!0,O(`pan`,{deltaX:e,deltaY:n}),C.screenX=t.screenX,C.screenY=t.screenY}else x?(O(`pan`,{deltaX:t.screenX-x.x,deltaY:t.screenY-x.y}),x.x=t.screenX,x.y=t.screenY):S&&t.pointerId===S.pointer?(Math.hypot(t.screenX-S.screenX,t.screenY-S.screenY)>=3&&(S.moved=!0),S.moved&&O(`drag`,{phase:`move`,x:t.clientX,y:t.clientY,append:S.append})):t.target instanceof e.Element&&(_=ie(t.target)?null:t.target.closest(`svg`)||t.target)}},ce=e=>{let t=C;if(C=null,t&&e.type===`pointerup`&&!t.panning&&!ie(t.target)){let n=e;O(`menu`,{x:n.clientX,y:n.clientY,id:k(t.target.closest(`svg`)||t.target)})}if(S){let t=e,n=e.type===`pointerup`;O(`drag`,{phase:n&&S.moved?`end`:`cancel`,x:t.clientX??S.x,y:t.clientY??S.y,append:S.append,...n&&!S.moved?{click:!0}:{}}),w=S.moved}x=null,S=null},le=()=>{_=null,y=null,b=null,d&&O(`hover`,{rect:null,id:null})},V=t=>{t.preventDefault();let n=t.deltaMode===1?16:t.deltaMode===2?e.innerHeight:1;O(`wheel`,{deltaX:t.deltaX*n,deltaY:t.deltaY*n,x:t.clientX,y:t.clientY,zoom:t.ctrlKey||t.metaKey})},ue=e=>{d&&(e.stopImmediatePropagation(),V(e))},de=e=>{e.ctrlKey&&!e.defaultPrevented&&V(e)},fe=[`Space`,`KeyH`,`KeyV`,`KeyC`,`KeyJ`,`KeyK`,`Escape`,`Equal`,`Minus`,`Digit0`,`Digit1`,`AltLeft`,`AltRight`],pe=[`KeyM`,`BracketLeft`,`BracketRight`,`Delete`,`Backspace`],me=[`KeyR`,`KeyA`,`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`],he=()=>{d&&O(`key`,{key:`Alt`,code:`AltLeft`,down:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1,altKey:!1})},ge=t=>{if(!d||t.composedPath().some(t=>t instanceof e.Element&&t.matches(`input,textarea,select,[contenteditable]`)))return;let n=t.metaKey||t.ctrlKey;(fe.includes(t.code)||pe.includes(t.code)&&!n||me.includes(t.code)&&!n&&f===`comment`||t.code===`KeyZ`&&n)&&(t.preventDefault(),t.stopImmediatePropagation(),O(`key`,{key:t.key,code:t.code,down:t.type===`keydown`,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey,altKey:t.altKey}))},_e=e=>{d&&(e.preventDefault(),e.stopImmediatePropagation())},ve=()=>{d&&m&&F(`update`)},ye=()=>{ce(new e.Event(`pointercancel`)),d=!1,z.disconnect(),D.remove(),e.clearTimeout(h),e.cancelAnimationFrame(g),h=0,g=0,_=null,y=null,b=null,O(`hover`,{rect:null,id:null})},be=l=>{if(l.source!==e.parent||l.data?.type!==`ryugi:inspect`)return;let u=l.data;if(u.action===`enable`){if(typeof u.connection!=`string`||!u.connection||u.connection.length>128)return;p=u.connection,d=!0,D.isConnected||(i.head||i.documentElement).append(D),z.observe(i.documentElement,{subtree:!0,childList:!0,characterData:!0,attributes:!0}),e.cancelAnimationFrame(g),g=e.requestAnimationFrame(re),R(),I(),m&&F(`update`)}else if(u.connection===p){if(u.action===`disable`)ye();else if(u.action===`mode`&&(u.mode===`select`||u.mode===`comment`))f=u.mode,D.textContent=`*{cursor:${f===`comment`?n:r}!important}`;else if((d||u.action===`reset`)&&u.session===a){if(u.action===`cancel-drag`)ce(new e.Event(`pointercancel`));else if(u.action===`select`&&Number.isSafeInteger(u.id)){let e=s.get(u.id);e?.isConnected&&(m=e,F(u.primary===!0?`primary`:`command`,u.toggle===!0))}else if(u.action===`track`&&Array.isArray(u.ids)&&u.ids.length<=2500&&u.ids.every(e=>Number.isSafeInteger(e)&&e>0)){E.clear();for(let e of u.ids){let t=s.get(e);t?.isConnected&&E.set(e,P(t))}}else if(u.action===`leaves`&&Number.isSafeInteger(u.request)&&u.request>0){let e=e=>M(e)!==null,t=t=>t.tagName.toLowerCase()===`svg`||Array.from(t.childNodes).some(e=>e.nodeType===3&&e.textContent.trim())||!Array.from(t.children).some(e),n=/* @__PURE__ */ new Set,r=[],a=/* @__PURE__ */ new Map,o=e=>{for(let t=e.parentElement;t&&t!==i.body;t=t.parentElement){let e=M(t);if(e!==null)return a.has(e)||a.set(e,{id:e,name:A(t)||j(t),parent:o(t),rect:P(t)}),e}return null};for(let[e,a]of s){if(a===i.body||!a.isConnected||a.parentElement?.closest(`svg`)||!t(a))continue;let s=a.parentElement;for(;s&&!n.has(s);)s=s.parentElement;if(s)continue;let c=P(a);c.width<=0||c.height<=0||(n.add(a),r.push({id:e,name:A(a)||j(a),parent:o(a),rect:c}))}O(`targets`,{request:u.request,targets:r,containers:[...a.values()]})}else if(u.action===`describe`&&Number.isSafeInteger(u.request)&&u.request>0&&Array.isArray(u.ids)&&u.ids.length<=2500){let e=[];for(let t of u.ids){let n=Number.isSafeInteger(t)?s.get(t):void 0;n?.isConnected&&e.push({id:t,text:(n.textContent??``).replaceAll(/\s+/g,` `).trim().slice(0,200),html:n.outerHTML.slice(0,2e3)})}O(`details`,{request:u.request,nodes:e})}else if(u.action===`hover`){let e=s.get(u.id);_=e?.isConnected?e:null,y=_?P(_):null,b=_?M(_):null,O(`hover`,{rect:y,id:b})}else if(u.action===`style`&&u.session===a&&m&&o.get(m)===u.id&&t.includes(u.property)&&typeof u.value==`string`&&u.value.length<=300){let t=m;if(!t.style||!t.isConnected)return;let n=u.property,r=i.createElement(`div`).style;r.setProperty(n,u.value);let a=r.getPropertyValue(n);if(!a)return;c.has(t)||c.set(t,/* @__PURE__ */ new Map);let o=c.get(t);if(!o.has(n)){let i=/* @__PURE__ */ new Set([...Array.from(r),...Array.from(t.style).filter(e=>r.getPropertyValue(e))]);o.set(n,{from:e.getComputedStyle(t).getPropertyValue(n).slice(0,2e3),applied:``,declarations:new Map(Array.from(i,e=>[e,{value:t.style.getPropertyValue(e),priority:t.style.getPropertyPriority(e),applied:``}]))})}t.style.setProperty(n,a);let s=o.get(n);s.applied=t.style.getPropertyValue(n);for(let[e,n]of s.declarations)n.applied=t.style.getPropertyValue(e);F(`update`),I()}else if((u.action===`remove`||u.action===`restore`)&&Array.isArray(u.ids)&&u.ids.length<=2500){for(let e of u.ids){let t=Number.isSafeInteger(e)?s.get(e):void 0;t?.isConnected&&t!==i.body&&t!==i.documentElement&&(u.action===`remove`?L(t):te(t))}F(`update`),I()}else if(u.action===`reset`){for(let[e,t]of c)for(let n of t.values()){let t=Array.from(n.declarations).filter(([t,n])=>e.style.getPropertyValue(t)===n.applied&&!e.style.getPropertyPriority(t));for(let[n,r]of t)r.value?e.style.setProperty(n,r.value,r.priority):e.style.removeProperty(n)}c.clear();for(let e of T.keys())te(e);F(`update`),I()}}}};return e.addEventListener(`message`,be),i.addEventListener(`click`,ae,!0),i.addEventListener(`pointerdown`,oe,!0),i.addEventListener(`pointermove`,se,!0),i.addEventListener(`pointerup`,ce,!0),i.addEventListener(`pointercancel`,ce,!0),i.addEventListener(`pointerleave`,le),i.addEventListener(`contextmenu`,_e,!0),i.addEventListener(`wheel`,ue,{passive:!1,capture:!0}),e.addEventListener(`wheel`,de,{passive:!1}),i.addEventListener(`keydown`,ge,!0),i.addEventListener(`keyup`,ge,!0),e.addEventListener(`scroll`,ve,!0),e.addEventListener(`blur`,ce),e.addEventListener(`blur`,he),()=>{ye(),e.removeEventListener(`message`,be),i.removeEventListener(`click`,ae,!0),i.removeEventListener(`pointerdown`,oe,!0),i.removeEventListener(`pointermove`,se,!0),i.removeEventListener(`pointerup`,ce,!0),i.removeEventListener(`pointercancel`,ce,!0),i.removeEventListener(`pointerleave`,le),i.removeEventListener(`contextmenu`,_e,!0),i.removeEventListener(`wheel`,ue,!0),e.removeEventListener(`wheel`,de),i.removeEventListener(`keydown`,ge,!0),i.removeEventListener(`keyup`,ge,!0),e.removeEventListener(`scroll`,ve,!0),e.removeEventListener(`blur`,ce),e.removeEventListener(`blur`,he)}}function Rm(e,t){let n=e.document,r=new URL(e.location.href).searchParams.get(`rv`),i=(t,n={})=>e.parent.postMessage({type:`ryugi:board:${t}`,...t===`ready`||t===`error`?{version:r}:{},...n},`*`),a=0,o=e=>{++a<=10&&i(`error`,{message:e.slice(0,500)})};e.addEventListener(`error`,t=>{let n=t.target;n instanceof e.Element?o(`failed to load ${n.getAttribute(`src`)||n.getAttribute(`href`)||n.tagName}`):o(String(t.message||`error`))},!0),e.addEventListener(`unhandledrejection`,e=>{o(`unhandled rejection: ${String(e.reason?.message??e.reason)}`)});let s=()=>new Promise(t=>e.requestAnimationFrame(()=>t())),c=async()=>{let t=n.fonts?.ready;t&&await Promise.race([t.catch(()=>void 0),new Promise(t=>{e.setTimeout(t,800)})]);for(let e=0;e<20;e++){let e=(n.getAnimations?.()??[]).filter(e=>e.playState===`running`&&e.effect?.getComputedTiming().endTime!==1/0);if(!e.length)break;await Promise.all(e.map(e=>e.finished.catch(()=>void 0)))}await Promise.race([Promise.all([s(),s()]),new Promise(t=>{e.setTimeout(t,100)})]),i(`ready`)};n.readyState===`complete`?c():e.addEventListener(`load`,()=>void c(),{once:!0});let l=()=>i(`interacted`);e.addEventListener(`pointerdown`,l,!0),e.addEventListener(`keydown`,l,!0);let u=e=>!!e&&(e.nodeType===1?e:e.parentElement)?.closest?.(`[data-ryugi-inspector]`)!=null,d=0;new e.MutationObserver(t=>{t.every(e=>u(e.target)||[...e.addedNodes,...e.removedNodes].some(u))||(e.clearTimeout(d),d=e.setTimeout(()=>i(`changed`),500))}).observe(n.documentElement,{subtree:!0,childList:!0,characterData:!0,attributes:!0});let f=async(t,n,r,i)=>{let a=new e.Image;a.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(t)}`,await a.decode();let o=new e.OffscreenCanvas(Math.max(1,Math.round(n*i)),Math.max(1,Math.round(r*i))),s=o.getContext(`2d`);return s.scale(i,i),s.drawImage(a,0,0,n,r),o.convertToBlob({type:`image/png`})};e.addEventListener(`message`,async n=>{let r=n.data;if(n.source===e.parent&&r?.type===`ryugi:board:capture`&&Number.isSafeInteger(r.request)&&r.scale>0&&r.scale<=4)try{let{svg:n,width:a,height:o}=await t(e),s=await f(n,a,o,r.scale);i(`snapshot`,{request:r.request,blob:s,width:a,height:o})}catch(e){i(`snapshot`,{request:r.request,error:String(e?.message??e).slice(0,200)})}})}async function zm(e){let t=e.document,n=e=>/* @__PURE__ */ Error(`unsupported: ${e}`),r=t.querySelector(`video, audio, iframe, object, embed`);if(r)throw n(r.tagName.toLowerCase());let i=t=>new Promise((n,r)=>{let i=new e.FileReader;i.onload=()=>n(String(i.result)),i.onerror=()=>r(i.error),i.readAsDataURL(t)}),a=/* @__PURE__ */ new Map,o=t=>(a.has(t)||a.set(t,e.fetch(t).then(e=>{if(!e.ok)throw n(`fetch ${t.slice(0,120)}`);return e})),a.get(t).then(e=>e.clone())),s=async e=>i(await(await o(e)).blob()),c=/url\(\s*(?:(['"])([^'")]+)\1|([^'")\s]+))\s*\)/g,l=/@import\s+(?:url\(\s*(?:(['"])([^'")\s;]+)\1|([^'")\s;]+))\s*\)|(['"])([^'")\s;]+)\4|(?=([^'")\s;]+))\6)[^;]*;/g,u=/@font-face\s*\{[^}]*\}/g,d=(e,t,n,r)=>[e.replaceAll(/["']/g,``).trim().toLowerCase(),{normal:`400`,bold:`700`}[t.trim()]??t.trim(),n.trim()||`normal`,r.replaceAll(/\s/g,``).toLowerCase()].join(`|`),f=/* @__PURE__ */ new Map;for(let e of t.fonts??[]){let t=d(e.family,e.weight,e.style,e.unicodeRange);f.set(t,f.get(t)===!0||e.status===`loaded`)}let p=(e,t,n)=>RegExp(`${t}\\s*:\\s*([^;}]+)`).exec(e)?.[1]??n,m=e=>f.get(d(p(e,`font-family`,``),p(e,`font-weight`,`400`),p(e,`font-style`,`normal`),p(e,`unicode-range`,`U+0-10FFFF`)))===!1,h=async(e,t,n=0)=>{let r=e;for(let e of r.matchAll(l)){let i=new URL(e[2]??e[3]??e[5]??e[6],t).href;r=r.replace(e[0],n<3?await h(await(await o(i)).text(),i,n+1):``)}r=r.replaceAll(u,e=>m(e)?``:e);let i=[...new Set([...r.matchAll(c)].map(e=>e[2]??e[3]).filter(e=>!/^(?:data:|#|about:)/.test(e)))],a=await Promise.all(i.map(e=>s(new URL(e,t).href)));return r.replaceAll(c,(e,t,n,r)=>{let o=n??r??``;return i.includes(o)?`url("${a[i.indexOf(o)]}")`:e}).replaceAll(/:root\b/g,`html`)},g=t.documentElement,_=g.cloneNode(!0),v=[g,...g.querySelectorAll(`*`)],y=[_,..._.querySelectorAll(`*`)],b=[];for(let r=0;r<v.length;r++){let i=v[r],a=y[r];if(i.hasAttribute(`data-ryugi-inspector`))continue;if(i.shadowRoot){let t=e.getComputedStyle(i);a.style.display=t.display,a.style.verticalAlign=t.verticalAlign,a.style.flex=t.flex,a.innerHTML=i.shadowRoot.innerHTML.replaceAll(/<style[\s\S]*?<\/style>/g,``);let n=a.querySelector(`svg`);n&&(n.style.display=`block`,n.style.width=`100%`,n.style.height=`100%`)}if(i instanceof e.HTMLImageElement){a.removeAttribute(`srcset`),a.removeAttribute(`sizes`);let e=i.currentSrc||i.src;e&&!e.startsWith(`data:`)&&b.push(s(new URL(e,t.baseURI).href).then(e=>a.setAttribute(`src`,e)))}else if(i instanceof e.HTMLCanvasElement){if(!i.getContext(`2d`))throw n(`webgl canvas`);let e;try{e=i.toDataURL()}catch{throw n(`tainted canvas`)}let r=t.createElement(`img`);r.src=e,r.setAttribute(`style`,i.getAttribute(`style`)??``),r.width=i.width,r.height=i.height,a.replaceWith(r)}else if(i instanceof e.HTMLInputElement)a.setAttribute(`value`,i.value),i.checked?a.setAttribute(`checked`,``):a.removeAttribute(`checked`);else if(i instanceof e.HTMLTextAreaElement)a.textContent=i.value;else if(i instanceof e.HTMLSelectElement)a.querySelectorAll(`option`).forEach((e,t)=>t===i.selectedIndex?e.setAttribute(`selected`,``):e.removeAttribute(`selected`));else if(i instanceof e.HTMLLinkElement&&/\bstylesheet\b/i.test(i.rel)&&i.href){let e=new URL(i.href,t.baseURI).href;b.push(o(e).then(e=>e.text()).then(t=>h(t,e)).then(e=>{let n=t.createElement(`style`);n.textContent=e,a.replaceWith(n)}))}else i instanceof e.HTMLStyleElement&&b.push(h(i.textContent??``,t.baseURI).then(e=>{a.textContent=e}));let c=i.getAttribute(`style`);c?.includes(`url(`)&&b.push(h(c,t.baseURI).then(e=>a.setAttribute(`style`,e)))}await Promise.all(b);for(let e of _.querySelectorAll(`script, noscript, link, [data-ryugi-inspector]`))e.remove();let x=t.createElement(`style`);x.textContent=`*, *::before, *::after { animation-delay: -99999s !important; animation-play-state: paused !important; transition: none !important }`,_.append(x);let S=e.innerWidth,C=e.innerHeight;return{svg:`<svg xmlns="http://www.w3.org/2000/svg" width="${S}" height="${C}"><foreignObject x="0" y="0" width="100%" height="100%">${new e.XMLSerializer().serializeToString(_)}</foreignObject></svg>`,width:S,height:C}}function Bm(e,t){if(Object.getOwnPropertyDescriptor(e,`ryugiTweaks`))return;let{readTweakSchema:n,readTweakValues:r,reconcileTweakValues:i}=t(),a=e.document,o=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,s=``,c,l=-1,u=null,d=null,f={};function p(t,n){for(let e of Object.keys(f))e in t||(a.documentElement.style.removeProperty(`--tweak-${e}`),a.documentElement.removeAttribute(`data-tweak-${e}`));f=t;for(let[e,n]of Object.entries(t))a.documentElement.style.setProperty(`--tweak-${e}`,String(n)),a.documentElement.setAttribute(`data-tweak-${e}`,String(n));n&&a.dispatchEvent(new e.CustomEvent(`ryugi-tweaks`,{detail:{...f}}))}function m(){let e=a.querySelectorAll(`script[type="application/json"][data-ryugi-tweaks]`),t=e.length?e[0].textContent:null;if(t!==c||e.length!==l){c=t,l=e.length;try{if(e.length>1)throw Error(`Use one data-ryugi-tweaks declaration per board.`);if(t&&t.length>65536)throw Error(`Parameter declaration is too large.`);let r=n(t===null?null:JSON.parse(t));u=r.schema,d=r.error}catch(e){u=null,d=e instanceof SyntaxError?`Invalid parameter JSON.`:String(e.message)}p(u?i(u):{},!1)}}let h=()=>e.parent.postMessage({type:`ryugi:tweaks:ready`,connection:s,session:o,schema:u,error:d,values:{...f}},`*`);Object.defineProperty(e,"ryugiTweaks",{get:()=>(m(),{...f})}),a.addEventListener(`DOMContentLoaded`,()=>{m(),s&&h()},{once:!0}),e.addEventListener(`message`,t=>{if(t.source!==e.parent)return;let n=t.data;if(n&&n.type===`ryugi:tweaks`){if(n.action===`connect`&&typeof n.connection==`string`&&n.connection.length>0&&n.connection.length<=128)s=n.connection,m(),h();else if(n.action===`set`&&n.connection===s&&n.session===o&&s&&u){let e=r(u,n.values);e&&Object.keys(e).some(t=>e[t]!==f[t])&&p(e,!0)}}})}function Vm(){let e=e=>!!e&&typeof e==`object`&&!Array.isArray(e),t=(e,t=512)=>typeof e==`string`&&e.length<=t,n=e=>typeof e==`number`&&Number.isFinite(e)&&Math.abs(e)<=1e9,r=e=>typeof e==`string`&&/^#[\da-f]{6}$/i.test(e);function i(e,i){if(e.type===`text`)return t(i);if(e.type===`color`)return r(i);if(e.type===`boolean`)return typeof i==`boolean`;if(e.type===`enum`)return typeof i==`string`&&!!e.options?.some(e=>e.value===i);if(!n(i)||e.min!==void 0&&i<e.min||e.max!==void 0&&i>e.max)return!1;let a=e.step===void 0?0:(i-(e.min??0))/e.step;return Math.abs(a-Math.round(a))<1e-7}function a(a){if(a===null)return{schema:null,error:null};let o=e=>({schema:null,error:e});if(!e(a)||a.version!==1||!e(a.controls))return o(`Expected version 1 and a controls object.`);let s=Object.entries(a.controls);if(s.length>32)return o(`Declare at most 32 parameters.`);let c=[],l=/* @__PURE__ */ new Set;for(let[a,u]of s){let s=e=>o(`Parameter ${a.slice(0,64)}: ${e}`);if(!/^[A-Z][\w-]{0,63}$/i.test(a)||[`constructor`,`prototype`].includes(a))return s(`invalid key.`);if(l.has(a.toLowerCase()))return s(`duplicate case-insensitive key.`);if(l.add(a.toLowerCase()),!e(u)||![`color`,`range`,`number`,`boolean`,`enum`,`text`].includes(String(u.type)))return s(`unsupported type.`);if(u.label!==void 0&&!t(u.label,128))return s(`label must be short text.`);if(u.section!==void 0&&!t(u.section,128))return s(`section must be short text.`);let d={type:u.type,label:u.label??a,default:u.default};if(u.section!==void 0&&(d.section=u.section),d.type===`number`||d.type===`range`){for(let e of[`min`,`max`,`step`])if(u[e]!==void 0){if(!n(u[e]))return s(`${e} must be a finite number.`);d[e]=u[e]}if(d.type===`range`){if(d.min===void 0||d.max===void 0)return s(`range needs min and max.`);d.step??=1}if(d.min!==void 0&&d.max!==void 0&&d.min>=d.max||d.step!==void 0&&d.step<1e-6)return s(`invalid bounds or step.`)}if(d.type===`enum`||d.type===`color`&&u.options!==void 0){if(!Array.isArray(u.options)||!u.options.length||u.options.length>32)return s(`options must contain 1–32 choices.`);let n=[];for(let i of u.options){let a=typeof i==`string`?i:e(i)?i.value:null,o=typeof i==`string`?i:e(i)?i.label??a:null;if(!t(a)||!t(o,128)||d.type===`color`&&!r(a)||n.some(e=>e.value===a))return s(`invalid or duplicate option.`);n.push({value:a,label:o})}d.options=n}if(!i(d,d.default))return s(`default does not match its type, options or bounds.`);c.push([a,d])}return{schema:{version:1,controls:Object.fromEntries(c)},error:null}}function o(t,n){if(!e(n)||Object.keys(n).length!==Object.keys(t.controls).length)return null;let r=[];for(let[e,a]of Object.entries(t.controls)){if(!Object.hasOwn(n,e)||!i(a,n[e]))return null;r.push([e,n[e]])}return Object.fromEntries(r)}function s(e,t={},n){return Object.fromEntries(Object.entries(e.controls).map(([e,r])=>{let a=t[e];return[e,(!n||a!==n.controls[e]?.default)&&i(r,a)?a:r.default]}))}return{readTweakSchema:a,readTweakValues:o,reconcileTweakValues:s}}const{readTweakSchema:Hm,readTweakValues:Um,reconcileTweakValues:Wm}=Vm(),Gm=/<head(\s[^>]*)?>/i,Km=/^\s*(<!doctype[^>]*>)?\s*(<html(\s[^>]*)?>)?/i,qm=/^<script>([\s\S]*?)<\/script>/,Jm=/^(?:<script (?:defer|type="module") src="[^"]*\/_ryugi\/runtime\/ryugi-(?:icons|ui|deck|storyboard)\.js"><\/script>|<style data-ryugi-deck>[^<]*<\/style>)+/;function Ym(e){let t=Gm.exec(e);return t?t.index+t[0].length:Km.exec(e)?.[0].length??0}function Xm(e){let t=Ym(e),n=e.slice(t);n.startsWith(`<style>:root{color-scheme:light dark;background:transparent}body{margin:0;font-family:var(--lobe-font-family,system-ui,-apple-system,sans-serif)}</style>`)&&(n=n.slice(153));let r=qm.exec(n);return!r||!r[1].includes(`ryugi:`)?e:e.slice(0,t)+n.slice(r[0].length).replace(Jm,``)}const Zm=`(() => {
271
- const post = (message) => parent.postMessage(message, '*');
272
- const readProps = () => {
273
- const match = /[#&]ryugi-props=([^&]*)/.exec(location.hash);
274
- try {
275
- const props = match ? JSON.parse(decodeURIComponent(match[1])) : {};
276
- return props && typeof props === 'object' && !Array.isArray(props) ? props : {};
277
- } catch {
278
- return {};
279
- }
280
- };
281
- window.ryugiProps = readProps();
282
- addEventListener('hashchange', () => {
283
- window.ryugiProps = readProps();
284
- document.dispatchEvent(new CustomEvent('ryugi-props', { detail: window.ryugiProps }));
285
- });
286
- let height = 0;
287
- new ResizeObserver(() => {
288
- const next = Math.ceil(document.documentElement.offsetHeight);
289
- if (next === height) return;
290
- height = next;
291
- post({ type: 'ryugi:height', height });
292
- }).observe(document.documentElement);
293
- addEventListener('error', (event) => {
294
- const el = event.target;
295
- if (el && el !== window && el.getAttribute) {
296
- post({ type: 'ryugi:error', message: 'failed to load ' + (el.getAttribute('src') || el.getAttribute('href') || el.tagName) });
297
- return;
298
- }
299
- const where = event.filename ? ' (' + event.filename.split('/').pop().split('?')[0] + ':' + event.lineno + ')' : '';
300
- post({ type: 'ryugi:error', message: String(event.message || 'error') + where });
301
- }, true);
302
- addEventListener('unhandledrejection', (event) => {
303
- const reason = event.reason;
304
- post({ type: 'ryugi:error', message: 'unhandled rejection: ' + String((reason && reason.message) || reason) });
305
- });
306
- const fields = () =>
307
- Array.from(document.querySelectorAll('input, select, textarea, details, [data-ryugi-control]')).filter(
308
- (el) => el.hasAttribute('data-ryugi-control') || !el.closest('[data-ryugi-control]'),
309
- );
310
- const keyOf = (el, index) => {
311
- if (el.id) return '#' + el.id;
312
- if (el.type === 'radio') return 'radio:' + el.name + ':' + el.value;
313
- if (el.name) return el.tagName + ':' + el.name;
314
- return el.tagName + ':' + index;
315
- };
316
- const fire = (el) => {
317
- el.dispatchEvent(new Event('input', { bubbles: true }));
318
- el.dispatchEvent(new Event('change', { bubbles: true }));
319
- };
320
- addEventListener('message', (event) => {
321
- if (event.source !== parent) return;
322
- const data = event.data || {};
323
- if (data.type === 'ryugi:snapshot') {
324
- const state = { scroll: [scrollX, scrollY], fields: {} };
325
- fields().forEach((el, index) => {
326
- const key = keyOf(el, index);
327
- if (el.hasAttribute('data-ryugi-control')) {
328
- const saved = {};
329
- if ('value' in el && el.value !== undefined) saved.value = el.value;
330
- if (typeof el.checked === 'boolean') saved.checked = el.checked;
331
- state.fields[key] = saved;
332
- } else if (el.tagName === 'DETAILS') state.fields[key] = { open: el.open };
333
- else if (el.type === 'checkbox' || el.type === 'radio') state.fields[key] = { checked: el.checked };
334
- else if (el.type !== 'file' && el.type !== 'password') state.fields[key] = { value: el.value };
335
- });
336
- post({ type: 'ryugi:state', state });
337
- }
338
- if (data.type === 'ryugi:restore' && data.state && data.state.fields) {
339
- fields().forEach((el, index) => {
340
- const saved = data.state.fields[keyOf(el, index)];
341
- if (!saved) return;
342
- if (el.hasAttribute('data-ryugi-control')) {
343
- let changed = false;
344
- if ('value' in saved && el.value !== saved.value) {
345
- el.value = saved.value;
346
- changed = true;
347
- }
348
- if ('checked' in saved && el.checked !== saved.checked) {
349
- el.checked = saved.checked;
350
- changed = true;
351
- }
352
- if (changed) {
353
- el.dispatchEvent(new CustomEvent('ryugi-change', { bubbles: true, detail: { value: el.value, checked: el.checked } }));
354
- }
355
- } else if ('open' in saved) el.open = saved.open;
356
- else if ('checked' in saved) {
357
- if (el.checked !== saved.checked) {
358
- el.checked = saved.checked;
359
- fire(el);
360
- }
361
- } else if ('value' in saved && el.value !== saved.value) {
362
- el.value = saved.value;
363
- fire(el);
364
- }
365
- });
366
- const scroll = data.state.scroll || [0, 0];
367
- scrollTo(scroll[0], scroll[1]);
368
- }
369
- });
370
- const toHex = (value) => {
371
- const m = /^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)(?:\\s*,\\s*([\\d.]+))?\\s*\\)$/i.exec(String(value || ''));
372
- if (!m) return null;
373
- if (m[4] !== undefined && Number(m[4]) < 0.08) return null;
374
- return '#' + [m[1], m[2], m[3]].map((n) => Math.max(0, Math.min(255, Number(n))).toString(16).padStart(2, '0')).join('');
375
- };
376
- const captureSkeleton = () => {
377
- if (window.innerWidth < 320 || window.innerHeight < 200 || !document.body) return;
378
- const vw = window.innerWidth;
379
- const vh = Math.max(200, vw * 0.6);
380
- const sx = 600 / vw;
381
- const sy = 360 / vh;
382
- const bodyCs = getComputedStyle(document.body);
383
- const htmlCs = getComputedStyle(document.documentElement);
384
- const bg = toHex(bodyCs.backgroundColor) || toHex(htmlCs.backgroundColor) || '#ffffff';
385
- const ink = toHex(bodyCs.color) || '#1f1e1b';
386
- const boxes = [];
387
- const mediaTags = { IMG: 1, SVG: 1, CANVAS: 1, VIDEO: 1 };
388
- const ctrlTags = { BUTTON: 1, INPUT: 1, SELECT: 1, TEXTAREA: 1 };
389
- const textTags = { H1: 1, H2: 1, H3: 1, H4: 1, H5: 1, H6: 1, P: 1, LI: 1, SPAN: 1, A: 1, TD: 1, TH: 1, LABEL: 1, CODE: 1, PRE: 1 };
390
- const round1 = (n) => Math.round(n * 10) / 10;
391
- const nodes = document.body.querySelectorAll('*');
392
- let visited = 0;
393
- for (let i = 0; i < nodes.length && visited < 400 && boxes.length < 56; i++) {
394
- const el = nodes[i];
395
- if (!el || el.tagName === 'SCRIPT' || el.tagName === 'STYLE' || el.tagName === 'NOSCRIPT') continue;
396
- visited++;
397
- const rect = el.getBoundingClientRect();
398
- if (rect.width < 6 || rect.height < 6 || rect.bottom <= 0 || rect.top >= vh || rect.right <= 0 || rect.left >= vw) continue;
399
- const cs = getComputedStyle(el);
400
- if (cs.display === 'none' || cs.visibility === 'hidden' || Number(cs.opacity) < 0.08) continue;
401
- const x = round1(rect.left * sx);
402
- const y = round1(rect.top * sy);
403
- const w = round1(Math.min(600 - x, rect.width * sx));
404
- const h = round1(Math.min(360 - y, rect.height * sy));
405
- if (w < 4 || h < 3) continue;
406
- const r = round1(Math.min(24, (parseFloat(cs.borderTopLeftRadius) || 0) * sx));
407
- const fill = toHex(cs.backgroundColor);
408
- const bw = parseFloat(cs.borderTopWidth) || 0;
409
- const border = bw >= 0.5 ? toHex(cs.borderTopColor) : null;
410
- if (mediaTags[el.tagName]) {
411
- if (el.tagName === 'SVG' && rect.width < 28 && rect.height < 28) continue;
412
- boxes.push({ x, y, w, h, r, bg: fill || '#e4e7ec', border: border || undefined, kind: 'media' });
413
- continue;
414
- }
415
- if (ctrlTags[el.tagName]) {
416
- boxes.push({ x, y, w, h, r: r || 4, bg: fill || bg, border: border || '#d0d4da', kind: 'control' });
417
- continue;
418
- }
419
- if ((fill && fill !== bg) || border) {
420
- if (!(w > 580 && h > 340)) {
421
- boxes.push({ x, y, w, h, r, bg: fill || undefined, border: border || undefined, kind: 'block' });
422
- }
423
- }
424
- if (textTags[el.tagName] && el.children.length === 0 && (el.textContent || '').trim().length > 1) {
425
- const fg = toHex(cs.color) || ink;
426
- boxes.push({ x, y, w, h: Math.min(h, 20), bg: fg, kind: 'text' });
427
- }
428
- }
429
- if (boxes.length > 0) post({ type: 'ryugi:html-skeleton', snapshot: { bg, ink, boxes } });
430
- };
431
- if (document.readyState === 'complete') setTimeout(captureSkeleton, 350);
432
- else addEventListener('load', () => { setTimeout(captureSkeleton, 350); }, { once: true });
433
- })();`.split(`
434
- `).map(e=>e.trim()).join(` `),Qm=/<ryugi-(?!icon(?:\s|>)|token-sheet(?:\s|>)|ios-)[a-z0-9-]+(?:\s|>)/i,$m=/<meta[^>]+name=["']ryugi-ui["'][^>]*>/i,eh=/<ryugi-(?:token-sheet|ios-[a-z0-9-]+)(?:\s|>)/i,th=/<meta[^>]+name=["']ryugi-mockup["'][^>]*>/i,nh=`/_ryugi/runtime/ryugi-ui.js`;function rh(e,t={}){let n=t.inspector?`;(${Bm.toString().replaceAll(`
435
- `,` `)})(window,${Vm.toString().replaceAll(`
436
- `,` `)});(${Lm.toString().replaceAll(`
437
- `,` `)})(window,${JSON.stringify(Am)},${JSON.stringify(Im)},${JSON.stringify(Fm)});;(${Rm.toString().replaceAll(`
438
- `,` `)})(window,${zm.toString().replaceAll(`
439
- `,` `)});`:``,r=t.capture&&!t.inspector?`;if(new URLSearchParams(location.search).has('ryugi-capture'))(${Rm.toString().replaceAll(`
440
- `,` `)})(window,${zm.toString().replaceAll(`
441
- `,` `)});`:``,i=`${t.embedded?`<style>:root{color-scheme:light dark;background:transparent}body{margin:0;font-family:var(--lobe-font-family,system-ui,-apple-system,sans-serif)}</style>`:``}<script>${n||Zm}${r}<\/script>`,a=t.uiRuntimeUrl&&!t.inspector&&(Qm.test(e)||$m.test(e))?`<script defer src="${t.uiRuntimeUrl.replaceAll(`"`,`&quot;`)}"><\/script>`:``,o=t.uiRuntimeUrl&&(eh.test(e)||th.test(e))?`<script defer src="${t.uiRuntimeUrl.replace(/ryugi-ui\.js$/,`ryugi-mockup.js`).replaceAll(`"`,`&quot;`)}"><\/script>`:``,s=t.uiRuntimeUrl&&(a||o||/<ryugi-icon(?:\s|>)|<meta[^>]+name=["']ryugi-icons["']/i.test(e))?`<script defer src="${t.uiRuntimeUrl.replace(/ryugi-ui\.js$/,`ryugi-icons.js`).replaceAll(`"`,`&quot;`)}"><\/script>`:``,c=t.deckRuntimeUrl?`<style data-ryugi-deck>aside.notes{display:none}</style><script type="module" src="${t.deckRuntimeUrl.replaceAll(`"`,`&quot;`)}"><\/script>`:``,l=t.storyboardRuntimeUrl?`<script defer src="${t.storyboardRuntimeUrl.replaceAll(`"`,`&quot;`)}"><\/script>`:``,u=Ym(e);return e.slice(0,u)+i+s+o+a+c+l+e.slice(u)}const ih=[{type:`document`,refAttribute:`document`,subTargets:[`block`],splitPane:!0},{type:`artboard`,refAttribute:`artboard`,subTargets:[`group`,`board`],splitPane:!0},{type:`whiteboard`,refAttribute:`whiteboard`,subTargets:[`page`,`frame`],splitPane:!0},{type:`html`,refAttribute:`html`,subTargets:[],splitPane:!0},{type:`slides`,refAttribute:`slides`,subTargets:[`slide`],splitPane:!0},{type:`report`,refAttribute:`report`,subTargets:[`block`],splitPane:!0},{type:`storyboard`,refAttribute:`storyboard`,subTargets:[`shot`],splitPane:!0}],ah=ih.map(e=>e.refAttribute),oh=[...new Set(ih.flatMap(e=>e.subTargets))];function sh(e){return ih.find(t=>t.type===e)??null}const ch=e=>ah.filter(t=>e[t]!==void 0),lh=e=>ch(e)[0]??`artboard`,uh=e=>e[lh(e)]??``,dh=e=>e.frame??(e.page?`page:${e.page}`:void 0)??e.group??e.board??e.slide??e.block??e.shot??``,fh={document:`a document`,artboard:`an artboard`,whiteboard:`a whiteboard`,html:`an html page`,slides:`a deck`,report:`a report`,storyboard:`a storyboard`},ph=[`artboard`,`whiteboard`,`document`,`html`,`slides`,`report`,`storyboard`],mh=e=>e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} or ${e.at(-1)}`;function hh(e,t=`ref`,n=ph){let r=t===`ref`?`reference`:t,i=ch(e);if(i.length>1)return`<${t}> names one target: either ${mh(i.map(e=>fh[e]))}, not both`;let a=i[0];if(!a)return`<${t}> needs ${mh(n.map(e=>fh[e]))}: the slug of one in this project`;let o=e[a]??``,s=`<${t} ${a}="${o}">`;if(!n.includes(a))return`${s} names ${fh[a]}: an <${t}> takes ${mh(n.map(e=>fh[e]))}`;if(e.embed!==void 0&&a!==`whiteboard`)return`<${t} ${a}="${o}" embed="${e.embed}">: only a whiteboard reference embeds; ${fh[a]} ${r} is a chip`;if(e.embed!==void 0&&e.embed!==`true`)return`<${t} ${a}="${o}" embed="${e.embed}">: write embed="true" to embed the whiteboard, or leave embed out for a chip`;if(!Jn(o))return`${s} is not ${fh[a].replace(/ page$/,``)} slug: lowercase letters, digits and hyphens`;let c=sh(a)?.subTargets??[],l=oh.filter(t=>e[t]!==void 0);for(let e of l){if(c.includes(e))continue;let t=ih.filter(t=>t.subTargets.includes(e)).map(e=>e.type),n=c.length?`${fh[a]} ${r} takes ${mh(c)}`:`${fh[a]} ${r} takes no sub-target`;return`${s} has no ${e}: ${e} belongs to ${mh(t)} ${r}s; ${n}`}return l.length>1?`${s} names either a ${l[0]} or a ${l[1]}, not both`:e.page!==void 0&&!Ge(e.page)?`<${t} ${a}="${o}" page="${e.page}"> is not a page id: lowercase letters, digits and hyphens`:null}const gh=new Map(Object.entries({lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`,nbsp:`\xA0`,mdash:`—`,ndash:`–`,hellip:`…`,rarr:`→`,larr:`←`,uarr:`↑`,darr:`↓`,harr:`↔`,copy:`©`,reg:`®`,trade:`™`,times:`×`,divide:`÷`,middot:`·`,bull:`•`,laquo:`«`,raquo:`»`,lsquo:`‘`,rsquo:`’`,ldquo:`“`,rdquo:`”`,deg:`°`,plusmn:`±`,le:`≤`,ge:`≥`,ne:`≠`,euro:`€`,pound:`£`,yen:`¥`})),_h=/[A-Za-z_][\w.-]*/y,vh=/\s*/y,q=e=>`name`in e;function yh(e,t){return e.replaceAll(/&(?:#(\d{1,7})|#x([0-9a-fA-F]{1,6})|([A-Za-z][A-Za-z0-9]*));/g,(e,n,r,i,a)=>{let o=n?Number(n):r?Number.parseInt(r,16):null;if(o!==null)return o>0&&o<=1114111?String.fromCodePoint(o):e;let s=gh.get(i);return s===void 0&&t?.(i,a),s??e})}function bh(e){return q(e)?e.children.map(bh).join(``):e.text}function xh(e){let t=[],n=null,r=t=>{if(!n){n=[];for(let t=e.indexOf(`
442
- `);t!==-1;t=e.indexOf(`
443
- `,t+1))n.push(t)}let r=0,i=n.length;for(;r<i;){let e=r+i>>1;n[e]<t?r=e+1:i=e}return r+1},i=(e,n)=>t.push({line:r(e),message:n}),a=[],o=[],s=()=>o.at(-1)?.children??a,c=/* @__PURE__ */ new Set,l=e=>(t,n)=>{c.has(t)||(c.add(t),i(e+n,`&${t}; is not an entity a deck knows: write the character itself, or &amp; for a plain &`))},u=(t,n,r)=>{if(n<=t)return;let a=e.slice(t,n),o=r?-1:a.indexOf(`]]>`);o!==-1&&i(t+o,`a ]]> outside CDATA: the section before it ended early. Split it as ]]]]><![CDATA[> or take the code from a file`),s().push({start:t,end:n,cdata:r,text:r?a:yh(a,l(t))})},d=0;for(;d<e.length;){let n=e.indexOf(`<`,d);if(n===-1){u(d,e.length,!1);break}if(u(d,n,!1),e.startsWith(`<!--`,n)){let t=e.indexOf(`-->`,n+4);if(t===-1){i(n,`a comment is never closed with -->`);break}d=t+3;continue}if(e.startsWith(`<![CDATA[`,n)){let t=e.indexOf(`]]>`,n+9);if(t===-1){i(n,`a CDATA section is never closed with ]]>`);break}u(n+9,t,!0),d=t+3;continue}if(e.startsWith(`<?`,n)||e.startsWith(`<!`,n)){let t=e.indexOf(`>`,n);d=t===-1?e.length:t+1;continue}if(e[n+1]===`/`){_h.lastIndex=n+2;let t=_h.exec(e)?.[0],r=e.indexOf(`>`,n);if(!t||r===-1){i(n,`a closing tag is not finished`);break}d=r+1;let a=o.length-1;for(;a>=0&&o[a].name!==t;)--a;if(a===-1&&o.length===0){i(n,`</${t}> closes nothing that is open`);continue}a!==o.length-1&&i(n,`</${t}> closes <${o.at(-1).name}>, which is still open`);for(let e of o.splice(a===-1?o.length-1:a))e.innerEnd=n,e.end=d;continue}_h.lastIndex=n+1;let a=_h.exec(e)?.[0];if(!a){i(n,`a "<" that starts no tag: write &lt; or use CDATA`),d=n+1;continue}let c=/* @__PURE__ */ new Map,f=n+1+a.length,p=!1,m=!1;for(;f<e.length;){if(vh.lastIndex=f,f+=vh.exec(e)[0].length,e[f]===`>`){f+=1,m=!0;break}if(e.startsWith(`/>`,f)){f+=2,p=!0,m=!0;break}_h.lastIndex=f;let t=_h.exec(e)?.[0],n=t?e[f+t.length+1]:void 0;if(!t||e[f+t.length]!==`=`||n!==`"`&&n!==`'`){i(f,`<${a}> has an attribute that is not name="value"`);break}let r=f+t.length+2,o=e.indexOf(n,r);if(o===-1){i(f,`<${a}> has an attribute value that is never closed`);break}c.has(t)||c.set(t,yh(e.slice(r,o),l(r))),f=o+1}if(!m){let r=e.indexOf(`>`,f);if((t.length===0||r===-1)&&i(n,`<${a}> is not finished`),r===-1)break;f=r+1}let h={name:a,attrs:c,children:[],start:n,end:f,innerStart:f,innerEnd:f,line:r(n),selfClosing:p};if(s().push(h),d=f,!p){if(o.length>=100){i(n,`elements are nested more than 100 deep`);break}o.push(h)}}let f=t.length>0&&d<e.length;for(let t of o)f||i(t.start,`<${t.name}> is never closed`),t.innerEnd=e.length,t.end=e.length;let p=a.filter(q),m=a.find(e=>!q(e)&&e.text.trim()!==``);return p.length>1?i(p[1].start,`only one root element is allowed`):m&&i(m.start,`text outside the root element`),{root:p[0]??null,errors:t}}const Sh=/* @__PURE__ */ `h1.h2.h3.p.blockquote.ul.ol.table.img.icon.alert.hr.codeblock.code.magic.mermaid.math.chart.embed.html.kicker.subtitle.label.quote.cite.big.fact`.split(`.`),Ch=[`h1`,`h2`,`h3`,`p`,`blockquote`,`ul`,`ol`,`kicker`,`subtitle`,`label`,`quote`,`cite`],wh=[`ink`,`muted`,`faint`,`accent`,`info`],Th=[`left`,`center`,`right`],Eh=[`x`,`y`,`w`,`h`],Dh=/^[A-Za-z0-9_-]{1,32}$/,Oh=e=>Sh.includes(e);function kh(e){let t=/* @__PURE__ */ new Map;return e.children.filter(q).forEach((e,n)=>{e.name===`col`?e.children.filter(q).forEach((e,r)=>{Oh(e.name)&&t.set(e,`${n}.${r}`)}):Oh(e.name)&&t.set(e,String(n))}),t}const Ah=[`pad`,`font`,`weight`,`size`,`leading`,`tracking`,`fit`,`fill`,`opacity`,`radius`,`border`,`shadow`],jh=[...Ah,`align`,`color`,`w`,`h`],Mh=wh,Nh=[`surface`,`paper`,`ink`,`muted`,`faint`,`accent`,`info`],Ph=[`solid`,`dashed`,`dotted`],Fh=[...Th,`justify`],Ih={ink:`ink`,muted:`ink-2`,faint:`ink-3`,accent:`accent`,info:`info`,surface:`surface`,paper:`paper`},Lh=e=>`var(--deck-${Ih[e]??e})`,Rh=[`img`,`embed`,`chart`,`mermaid`,`math`,`magic`],zh=[`table`,`codeblock`,`code`,`alert`,`big`,`fact`],Bh=[`hr`,`icon`],Vh=[`fill`,`opacity`,`radius`,`border`,`shadow`],Hh=[`font`,`weight`,`size`,`leading`,`tracking`,`fit`];function Uh(e){return Ch.includes(e)?[`pad`,...Hh,`align`,`color`,...Vh]:Rh.includes(e)?[...Vh]:zh.includes(e)?[`pad`,...Vh]:Bh.includes(e)?[`opacity`]:[]}const Wh=/^#(?:[0-9a-f]{6}|[0-9a-f]{8})$/i,Gh=/^[\p{L}\p{N}][\p{L}\p{N} ._-]{0,63}$/u,Kh=(e,t,n)=>/^-?\d+$/.test(e)&&Number(e)>=t&&Number(e)<=n,qh=(e,t,n,r)=>RegExp(`^-?\\d+(?:\\.\\d{1,${r}})?$`).test(e)&&Number(e)>=t&&Number(e)<=n,Jh=(e,t)=>t.includes(e)||Wh.test(e);function Yh(e){let t=e.split(` `);if(t.length!==4)return null;let[n,r,i,a]=t;return Kh(n,-200,200)&&Kh(r,-200,200)&&Kh(i,0,200)&&Jh(a,Nh)?[n,r,i,a]:null}const Xh={pad:[e=>Kh(e,0,200),`must be whole pixels from 0 to 200`],font:[e=>e===`mono`||Gh.test(e),`must be mono or a font name: letters, digits, spaces, - _ . (at most 64)`],weight:[e=>Kh(e,100,900)&&Number(e)%100==0,`must be 100, 200 … 900`],size:[e=>Kh(e,8,400),`must be whole pixels from 8 to 400`],leading:[e=>qh(e,.8,3,2),`must be 0.8 to 3, at most two decimals`],tracking:[e=>qh(e,-20,100,1),`must be -20 to 100 pixels, at most one decimal`],fit:[e=>e===`shrink`,`must be shrink`],fill:[e=>Jh(e,Nh),`must be #RRGGBB, #RRGGBBAA or ${Nh.join(`, `)}`],opacity:[e=>Kh(e,0,100),`must be 0 to 100`],radius:[e=>Kh(e,0,360),`must be whole pixels from 0 to 360`],border:[e=>Ph.includes(e),`must be ${Ph.join(`, `)}`],shadow:[e=>Yh(e)!==null,`must be "x y blur colour": x and y -200 to 200, blur 0 to 200`],align:[e=>Fh.includes(e),`must be ${Fh.join(`, `)}`],color:[e=>Jh(e,Mh),`must be #RRGGBB, #RRGGBBAA or a theme colour: ${Mh.join(`, `)}`]};function Zh(e,t,n){let r=Object.hasOwn(Xh,t)?Xh[t]:void 0;return r?Uh(e).includes(t)?r[0](n)?null:`${t}="${n}" ${r[1]}`:`<${e}> takes no ${t}`:`${t} is not a look attribute`}const Qh=e=>Wh.test(e)?e:Lh(e);function $h(e,t){switch(e){case`pad`:return[[`padding`,`${t}px`]];case`font`:return[[`font-family`,t===`mono`?`var(--deck-font-mono)`:`"${t}", var(--deck-font)`]];case`weight`:return[[`font-weight`,t]];case`size`:return[[`font-size`,`${t}px`]];case`leading`:return[[`line-height`,t]];case`tracking`:return[[`letter-spacing`,`${t}px`]];case`fill`:return[[`background-color`,Qh(t)]];case`opacity`:return[[`opacity`,String(Number(t)/100)]];case`radius`:return[[`border-radius`,`${t}px`]];case`border`:return[[`border`,`1px ${t} var(--deck-rule-strong)`]];case`shadow`:{let e=Yh(t);if(!e)return[];let[n,r,i,a]=e;return[[`box-shadow`,`${n}px ${r}px ${i}px ${Qh(a)}`]]}case`color`:return[[`color`,Qh(t)]];case`align`:return[[`text-align`,t]];default:return[]}}const eg={blocks:500,ref:64,tag:16,text:200,html:2e5},tg=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:null,ng=e=>typeof e==`number`&&Number.isFinite(e),rg=e=>typeof e==`string`&&e.length>0&&e.length<=eg.ref,ig=[`text`,`media`,`frozen`],ag=/^#[0-9a-f]{6}(?:[0-9a-f]{2})?$/i,og=[`border`,`color`,`fill`,`font`,`shadow`],sg=[`leading`,`opacity`,`pad`,`radius`,`size`,`tracking`,`weight`],cg=e=>jh.includes(e),lg=e=>typeof e==`string`&&e.length<=200;function ug(e){if(e===void 0)return;let t=tg(e);return!t||!og.every(e=>lg(t[e]))||!sg.every(e=>ng(t[e]))?null:Object.fromEntries([...og,...sg].map(e=>[e,t[e]]))}function dg(e){if(e===void 0)return;let t=tg(e);if(!t)return null;let n=Object.entries(t);return n.every(([e,t])=>cg(e)&&typeof t==`string`&&t.length<=80)?Object.fromEntries(n):null}function fg(e){if(e===void 0)return;let t=tg(e);if(!t)return null;let n=Object.entries(t);return n.every(([e,t])=>Nh.includes(e)&&typeof t==`string`&&ag.test(t))?Object.fromEntries(n):null}function pg(e){let t=tg(e);if(!t)return null;let{x:n,y:r,w:i,h:a}=t;return ng(n)&&ng(r)&&ng(i)&&ng(a)?{x:n,y:r,w:i,h:a}:null}function mg(e){return Array.isArray(e)?e.slice(0,16).flatMap(e=>{let t=tg(e);if(!t||t.kind!==`chip`&&t.kind!==`embed`)return[];let n=pg(t.rect),r=kg(t.target);return n&&r?[{kind:t.kind,rect:n,target:r}]:[]}):[]}function hg(e){let t=tg(e);if(!t)return null;let{ref:n,id:r,tag:i,kind:a,text:o}=t,s=pg(t.rect);if(!rg(n)||r!==null&&!rg(r)||typeof i!=`string`||!/^[a-z][a-z0-9]*$/.test(i)||i.length>eg.tag||typeof a!=`string`||!ig.includes(a)||typeof o!=`string`||!s)return null;let c=e=>typeof e==`string`&&/^[a-z]{1,16}$/.test(e);if(t.align!==void 0&&!c(t.align)||t.color!==void 0&&!c(t.color))return null;let l=dg(t.look),u=ug(t.values),d=ug(t.base);if(l===null||u===null||d===null)return null;let f=mg(t.opens);return{ref:n,id:r,tag:i,kind:a,text:o.slice(0,eg.text),rect:s,...t.align===void 0?{}:{align:t.align},...t.color===void 0?{}:{color:t.color},...l?{look:l}:{},...u?{values:u}:{},...d?{base:d}:{},...f.length?{opens:f}:{}}}function gg(e){let t=tg(e);if(!t||t.ns!==`ryugi-deck`)return null;let n=yg;if(t.type===`blocks`){let{slide:e,zoom:r,free:i}=t;if(typeof e!=`string`||e.length>bg.id||!ng(r)||r<=0||typeof i!=`boolean`||!Array.isArray(t.blocks))return null;let a=t.blocks.slice(0,eg.blocks).map(hg);if(a.includes(null))return null;let o=fg(t.palette),{ground:s}=t;return o===null||s!==void 0&&!(typeof s==`string`&&ag.test(s))?null:{ns:n,type:`blocks`,slide:e,zoom:r,free:i,blocks:a,...o?{palette:o}:{},...s===void 0?{}:{ground:s}}}if(t.type===`edit-link`)return{ns:n,type:`edit-link`};if(t.type===`text-commit`){let{ref:e,html:r,changed:i}=t;return rg(e)&&typeof r==`string`&&r.length<=eg.html&&typeof i==`boolean`?{ns:n,type:`text-commit`,ref:e,html:r,changed:i}:null}return null}const _g={w:1280,h:720};function vg(e){if(e===null)return null;if(typeof e!=`object`||Array.isArray(e))return;let{x:t,y:n}=e;if(typeof t==`number`&&typeof n==`number`&&t>=0&&t<=_g.w&&n>=0&&n<=_g.h)return{x:Math.round(t*10)/10,y:Math.round(n*10)/10}}const yg=`ryugi-deck`,bg={slides:500,errors:20,id:128,title:200,notes:4e3,text:200,path:500,message:500,sheets:50,sheetBytes:4194304,shotBytes:25165824},xg=[`normal`,`live`,`thumbs`,`print`],Sg=[`diagram`,`math`,`code`,`magic-move`,`embed`],Cg=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:null,wg=e=>typeof e==`number`&&Number.isInteger(e)&&e>=0,Tg=/^[\w-]{1,128}$/,Eg=/^[\w-]{1,64}$/,Dg=[...ah,...oh,`to`,`label`];function Og(e){let t=Cg(e);return!t||typeof t.to!=`string`||!Eg.test(t.to)||typeof t.kind!=`string`||!ah.includes(t.kind)?null:{to:t.to,kind:t.kind}}function kg(e){let t=Cg(e);if(!t)return null;let n={};for(let[e,r]of Object.entries(t)){if(!Dg.includes(e)||typeof r!=`string`)return null;n[e]=r}let r=ah.filter(e=>n[e]!==void 0),i=r.length===1?r[0]:null;if(!i||n[i]===``&&!n.to)return null;let{label:a,...o}=n;return hh({...o,[i]:n[i]||`published`})||a!==void 0&&a.length>bg.title||oh.some(e=>n[e]!==void 0&&!Tg.test(n[e]))||n.to!==void 0&&!Eg.test(n.to)?null:n}const Ag=e=>typeof e==`number`&&Number.isFinite(e);function jg(e){let t=Cg(e);return!t||typeof t.slide!=`string`||t.slide.length>bg.id||!wg(t.index)||!wg(t.step)||typeof t.overview!=`boolean`||typeof t.paused!=`boolean`?null:{slide:t.slide,index:t.index,step:t.step,overview:t.overview,paused:t.paused}}function Mg(e){let t=Cg(e);return!t||typeof t.id!=`string`||typeof t.title!=`string`||typeof t.notes!=`string`||!wg(t.steps)?null:{id:t.id.slice(0,bg.id),title:t.title.slice(0,bg.title),steps:t.steps,notes:t.notes.slice(0,bg.notes)}}function Ng(e){let t=Cg(e);return!t||typeof t.kind!=`string`||!Sg.includes(t.kind)||typeof t.message!=`string`||t.slide!==null&&typeof t.slide!=`string`?null:{kind:t.kind,slide:t.slide===null?null:t.slide.slice(0,bg.id),message:t.message.slice(0,bg.message)}}function Pg(e){let t=Cg(e);if(!t||t.ns!==`ryugi-deck`)return null;let n=yg;switch(t.type){case`ready`:{let e=jg(t.state);if(!e||typeof t.mode!=`string`||!xg.includes(t.mode)||!Array.isArray(t.outline))return null;let r=t.outline.slice(0,bg.slides).map(Mg);return r.includes(null)?null:{ns:n,type:`ready`,mode:t.mode,outline:r,state:e}}case`state`:{let e=jg(t.state);return!e||t.cause!==`user`&&t.cause!==`remote`?null:{ns:n,type:`state`,state:e,cause:t.cause}}case`geometry`:{let e=Cg(t.geometry);if(!e)return null;let{x:r,y:i,w:a,h:o,scale:s}=e;return!Ag(r)||!Ag(i)||!Ag(a)||!Ag(o)||!Ag(s)||s<=0?null:{ns:n,type:`geometry`,geometry:{x:r,y:i,w:a,h:o,scale:s}}}case`report`:return!Array.isArray(t.overflow)||!Array.isArray(t.errors)?null:{ns:n,type:`report`,overflow:t.overflow.filter(e=>typeof e==`string`).slice(0,bg.slides).map(e=>e.slice(0,bg.id)),errors:t.errors.map(Ng).filter(e=>e!==null).slice(0,bg.errors)};case`hit-result`:{let{id:e,slide:r,x:i,y:a,text:o,path:s}=t;return!wg(e)||typeof r!=`string`||!Ag(i)||!Ag(a)||typeof o!=`string`||typeof s!=`string`?null:{ns:n,type:`hit-result`,id:e,slide:r.slice(0,bg.id),x:i,y:a,text:o.slice(0,bg.text),path:s.slice(0,bg.path)}}case`print-ready`:return{ns:n,type:`print-ready`};case`pointer`:return{ns:n,type:`pointer`};case`cursor`:{let e=vg(t.at);return e===void 0?null:{ns:n,type:`cursor`,at:e}}case`sheet-result`:{let{request:e,sheets:r,error:i}=t;return wg(e)?typeof i==`string`?{ns:n,type:`sheet-result`,request:e,error:i.slice(0,bg.message)}:!Array.isArray(r)||r.length>bg.sheets||!r.every(e=>e instanceof Blob&&e.size<=bg.sheetBytes)?null:{ns:n,type:`sheet-result`,request:e,sheets:r}:null}case`shot`:{let{request:e,index:r,total:i,blob:a}=t;return!wg(e)||!wg(r)||!wg(i)||i>bg.slides||r>=i||!(a instanceof Blob)||a.size>bg.shotBytes?null:{ns:n,type:`shot`,request:e,index:r,total:i,blob:a}}case`open`:{let e=kg(t.target);return e?{ns:n,type:`open`,target:e}:null}case`targets`:{if(!Array.isArray(t.targets)||t.targets.length>200)return null;let e=t.targets.map(Og);return e.includes(null)?null:{ns:n,type:`targets`,targets:e}}case`shots-done`:{let{request:e,error:r}=t;return wg(e)?typeof r==`string`?{ns:n,type:`shots-done`,request:e,error:r.slice(0,bg.message)}:{ns:n,type:`shots-done`,request:e}:null}default:return gg(e)}}function Fg(e){let t=`slide ${e.slide+1}`,n=e.id??t;switch(e.code){case`missing_id`:return{code:`E_SLIDE_ID`,severity:`error`,location:t,message:`${t} has no id: give every <section> its own id, such as id="why-now".`};case`invalid_id`:return{code:`E_SLIDE_ID`,severity:`error`,location:t,message:`${t} has the id "${e.id}": use lowercase letters, digits and hyphens.`};case`duplicate_id`:return{code:`E_SLIDE_ID`,severity:`error`,location:t,message:`${t} repeats the id "${e.id}": every slide needs its own.`};case`nested_slide`:return{code:`E_SLIDE_NESTED`,severity:`error`,location:n,message:`${n} has a <section> inside it: a deck is one row of slides, with none nested.`};case`unknown_layout`:return{code:`W_SLIDE_LAYOUT`,severity:`warning`,location:n,message:`${n} uses l-${e.detail}, which is not a layout: it is shown with no layout rules.`};case`unknown_transition`:return{code:`W_SLIDE_MOTION`,severity:`warning`,location:n,message:`${n} has data-transition="${e.detail}", which is not a transition: the theme's is used.`};case`unknown_glow`:return{code:`W_SLIDE_MOTION`,severity:`warning`,location:n,message:`${n} has data-glow="${e.detail}", which is not a glow place: the theme's is used.`};case`duplicate_morph`:return{code:`W_SLIDE_MOTION`,severity:`warning`,location:n,message:`${n} has data-morph="${e.detail}" more than once: only the first element moves to the next slide.`};case`own_reveal`:return{code:`W_SLIDE_REVEAL`,severity:`warning`,message:`The deck loads or starts reveal.js itself: remove that, the page is given a runtime that does.`};case`two_entries`:return{code:`W_SLIDE_ENTRY`,severity:`warning`,message:`The directory holds both deck.xml and index.html: deck.xml is the deck, so delete index.html.`};case`missing_asset`:return{code:`W_SLIDE_ASSET`,severity:`warning`,location:e.detail,message:`${e.detail} is not in the artifact directory.`}}}function Ig(e){if(e.code===`xml`)return{code:`E_SLIDE_XML`,severity:`error`,message:`${e.detail.startsWith(`line `)?`deck.xml `:``}${e.detail}.`};let t=e.slide<0?null:e.id??`slide ${e.slide+1}`,n=e.code===`unknown_attr`?`<${e.tag}> does not take the attribute "${e.detail}"`:e.detail;return{code:e.code===`file`?`E_SLIDE_FILE`:`E_SLIDE_TAG`,severity:`error`,...t?{location:t}:{},message:`${t??`deck.xml`}: ${n}.`}}function Lg(e){let t=e.slide<0?null:e.id??`slide ${e.slide+1}`;return{code:`W_SLIDE_EMBED`,severity:`warning`,...t?{location:t}:{},message:`${t??`deck.xml`}: ${e.detail}.`}}function Rg(e,t,n=[],r=[]){return[...n.map(Ig),...r.map(Lg),...e.map(Fg),...(t?.overflow??[]).map(e=>({code:`W_SLIDE_OVERFLOW`,severity:`warning`,location:e,message:`${e}: the content does not fit the ${_g.w}×${_g.h} slide.`})),...(t?.errors??[]).map(e=>({code:`W_SLIDE_RENDER`,severity:`warning`,...e.slide?{location:e.slide}:{},message:`${e.slide??`the deck`}: ${e.kind} could not be drawn: ${e.message}`}))]}const zg=[`default`,`cover`,`section`,`statement`,`two-cols`,`image`,`quote`,`fact`,`code`,`end`,`none`],Bg=/^\s*(\d+)(?:\s*-\s*(\d+))?\s*$/,Vg=e=>{let t=e.trim();return t===`all`||t===`hide`?t:null};function Hg(e){let t=[];for(let n of e.split(`|`)){let e=Vg(n);if(e){t.push(e);continue}let r=/* @__PURE__ */ new Set;for(let e of n.split(`,`)){let t=Bg.exec(e);if(!t)continue;let n=Number(t[1]),i=t[2]===void 0?n:Number(t[2]),a=Math.max(n,i);for(let e=Math.max(1,Math.min(n,i));e<=a&&!(r.size>=2e3);e++)r.add(e)}r.size&&t.push([...r].sort((e,t)=>e-t))}return t}const Ug=e=>e.split(`|`).every(e=>Vg(e)!==null||e.split(`,`).every(e=>{let t=Bg.exec(e);return t!==null&&Number(t[1])>=1&&Number(t[2]??1)>=1})),Wg=[`view`,`fade-out`,`fade`,`slide-left`,`slide-up`,`none`],Gg=[`full`,`top`,`bottom`,`left`,`right`,`top-left`,`top-right`,`bottom-left`,`bottom-right`,`center`,`none`],Kg=e=>Wg.includes(e),qg=e=>Gg.includes(e),Jg=/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i;function Yg(e){let t=e?.trim();return!t||Jg.test(t)?null:t.split(/[?#]/)[0]||null}const Xg=/^[a-z0-9][a-z0-9-]*$/,Zg=`((?:"[^"]*"|'[^']*'|[^'">])*)`,Qg=RegExp(`<!--[\\s\\S]*?(?:-->|$)|<(script|style|textarea|template|title)\\b${Zg}>([\\s\\S]*?)(?:<\\/\\1\\s*>|$)|<(\\/?)([a-zA-Z][a-zA-Z0-9-]*)${Zg}>`,`gi`),$g=/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g,e_=/reveal(?:\.min)?(?:\.esm)?\.m?js(?:[?#]|$)/i,t_={lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `,amp:`&`};function n_(e){let t=/* @__PURE__ */ new Map;for(let n of e.matchAll($g)){let e=n[1].toLowerCase();t.has(e)||t.set(e,n[2]??n[3]??n[4]??``)}return t}function r_(e){return e.replaceAll(/<[^>]*>/g,``).replaceAll(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi,(e,t,n,r)=>t?String.fromCodePoint(Number(t)):n?String.fromCodePoint(Number.parseInt(n,16)):t_[String(r).toLowerCase()]??e).replaceAll(/\s+/g,` `).trim().slice(0,200)}function i_(e){let t=e.toLowerCase(),n=[],r=[],i=null,a=null,o=!1,s=!1,c=0,l=/* @__PURE__ */ new Set,u=e=>{let t=Yg(e);t&&l.add(t)},d=e=>{for(let t=n.length-1;t>=0;t--)if(n[t].tag===e){for(let e of n.splice(t))e.kind===`slide`&&(i=null),e.kind===`notes`&&--c;return}};Qg.lastIndex=0;for(let l=Qg.exec(e);l;l=Qg.exec(e)){let[,f,p=``,m=``,h,g,_=``]=l;if(f){let e=f.toLowerCase();e===`title`&&!i&&a===null&&(a=r_(m)||null);let t=e===`script`?n_(p).get(`src`):void 0;u(t),e===`script`&&(e_.test(t??``)||m.includes(`Reveal.initialize`))&&(s=!0);let r=n.at(-1);e===`template`&&i&&!c&&r?.kind===`magic`&&(r.templates=(r.templates??0)+1,r.templates>1&&(i.steps+=1));continue}if(!g)continue;let v=g.toLowerCase();if(h){(v===`div`||v===`section`||v===`aside`)&&d(v);continue}let y=n_(_);u(y.get(`src`)),v===`link`&&u(y.get(`href`));let b=(y.get(`class`)??``).split(/\s+/).filter(Boolean),x=n.at(-1)?.kind;if(i&&!c){let n=y.get(`data-morph`)?.trim();if(n&&(i.morphs.has(n)&&!i.morphRepeats.includes(n)&&i.morphRepeats.push(n),i.morphs.add(n)),b.includes(`fragment`)){let e=y.get(`data-fragment-index`);e!==void 0&&i.positions.has(e)||(i.steps+=1),e!==void 0&&i.positions.add(e)}if(v===`code`&&(i.steps+=Math.max(0,Hg(y.get(`data-lines`)??``).length-1)),!i.titled&&/^h[1-3]$/.test(v)){let n=t.indexOf(`</${v}`,Qg.lastIndex);i.title=r_(e.slice(Qg.lastIndex,n===-1?void 0:n)),i.titled=!0}}if(v===`div`){let e=`other`;!o&&x===`reveal`&&b.includes(`slides`)?(e=`slides`,o=!0):!o&&b.includes(`reveal`)?e=`reveal`:i&&b.includes(`magic-move`)&&(e=`magic`),n.push({tag:v,kind:e})}else if(v===`section`){if(x===`slides`){let e=b.find(e=>e.startsWith(`l-`)),t=e?e.slice(2):`default`;i={id:y.get(`id`)||null,layout:t,title:``,steps:0,notes:!1,nested:!1,titled:!1,unknownLayout:zg.includes(t)?null:t,transition:y.get(`data-transition`)?.trim()??null,glow:y.get(`data-glow`)?.trim()??null,morphs:/* @__PURE__ */ new Set,morphRepeats:[],positions:/* @__PURE__ */ new Set,...y.has(`data-deck-hidden`)?{hidden:!0}:{},...y.get(`data-deck-group`)?{group:y.get(`data-deck-group`)}:{}},r.push(i),n.push({tag:v,kind:`slide`})}else i&&(i.nested=!0),n.push({tag:v,kind:`other`})}else if(v===`aside`){let e=i!==null&&b.includes(`notes`);e&&(i.notes=!0,c+=1),n.push({tag:v,kind:e?`notes`:`other`})}}let f=[],p=/* @__PURE__ */ new Set,m=r.map(({nested:e,titled:t,unknownLayout:n,transition:r,glow:i,morphs:a,morphRepeats:o,positions:s,...c},l)=>{let u=c.id??void 0;c.id?Xg.test(c.id)?p.has(c.id)&&f.push({code:`duplicate_id`,slide:l,id:u}):f.push({code:`invalid_id`,slide:l,id:u}):f.push({code:`missing_id`,slide:l}),c.id&&p.add(c.id),e&&f.push({code:`nested_slide`,slide:l,...u?{id:u}:{}}),n&&f.push({code:`unknown_layout`,slide:l,...u?{id:u}:{},detail:n});let d={slide:l,...u?{id:u}:{}};r!==null&&!Kg(r)&&f.push({code:`unknown_transition`,...d,detail:r}),i!==null&&!qg(i)&&f.push({code:`unknown_glow`,...d,detail:i});for(let e of o)f.push({code:`duplicate_morph`,...d,detail:e});return c});return s&&f.push({code:`own_reveal`,slide:-1}),{complete:/<\/html\s*>\s*$/i.test(e),hasDeck:o,title:a,slides:m,issues:f,assets:[...l]}}const a_={explicit:!1,from:/* @__PURE__ */ new Map,index:/* @__PURE__ */ new Map},o_=/^[1-9]\d?$/,s_=(e,t)=>e.name===`col`||(e.name===`ul`||e.name===`ol`)&&t.name===`li`||e.name===`table`&&t.name===`tr`&&t.children.some(e=>q(e)&&e.name===`td`);function c_(e){return e.name===`codeblock`?Math.max(0,Hg(e.attrs.get(`lines`)??``).length-1):e.name===`magic`?Math.max(0,e.children.filter(e=>q(e)&&e.name===`step`).length-1):0}function l_(e){let t=/* @__PURE__ */ new Set,n=e=>{let r=e.attrs.get(`step`)??``;o_.test(r)&&t.add(Number(r)-1);for(let t of e.children)q(t)&&n(t)};return n(e),t}function u_(e,t){let n={explicit:!1,from:/* @__PURE__ */ new Map,index:/* @__PURE__ */ new Map},r=l_(e),i=0,a=null,o=()=>{for(;r.has(i);)i+=1;return i+=1,i-1},s=(e,r)=>{if(e.name===`notes`)return;let c=e.attrs.get(`step`)??(r?`true`:`false`),l=null;c===`true`?l=o():c===`with`?(n.explicit=!0,a===null?t.bad(e,`step`,`has no step before it to appear with`):l=a):o_.test(c)?(n.explicit=!0,l=Number(c)-1):c!==`false`&&t.bad(e,`step`,`must be true, with, or a step number from 1`),l!==null&&(n.index.set(e,l),a=l);let u=c_(e);if(u>0){n.from.set(e,o());for(let e=1;e<u;e+=1)o();a=i-1}if(e.name===`codeblock`||e.name===`magic`)return;let d=e.attrs.get(`steps`);d!==void 0&&d!==`true`&&d!==`false`&&t.bad(e,`steps`,`must be true or false`);for(let t of e.children)q(t)&&s(t,d===`true`&&s_(e,t))};for(let t of e.children)q(t)&&s(t,!1);return n}const d_=/^[a-z0-9-]{1,16}$/,f_=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,p_={readFile:(e,t)=>({error:`${t} cannot be read here`})},m_=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`);function h_(e){let t=e.filter(([e,t])=>e===`style`&&t!==!0);if(t.length<2)return e;let n=t.map(([,e])=>e).join(`;`),r=e.findIndex(([e])=>e===`style`);return e.flatMap((e,t)=>e[0]===`style`?t===r?[[`style`,n]]:[]:[e])}function g_(e,{classes:t,attrs:n},r){return`<${[e,...r===void 0?[]:[`id="${m_(r)}"`],...t.length?[`class="${t.join(` `)}"`]:[],...h_(n).map(([e,t])=>t===!0?e:`${e}="${m_(t)}"`)].join(` `)}>`}const __=/^[a-z0-9][a-z0-9-]*$/;var v_=class{env;audience;sources;deps=[];embeds=[];issues=[];refs=[];warnings=[];id;free=!1;placed=/* @__PURE__ */ new Map;blockIds=/* @__PURE__ */ new Set;slide=-1;steps=a_;constructor(e,t=!1,n=!1){this.env=e,this.audience=t,this.sources=n}issue(e,t,n){return{code:e,slide:this.slide,...this.id?{id:this.id}:{},...n?{tag:n}:{},detail:t}}report(e,t,n){this.issues.push(this.issue(e,t,n))}warn(e,t,n){this.warnings.push(this.issue(e,t,n))}read(e,t,n){let r=this.env.readFile(e,t);if(typeof r!=`string`)return this.report(`file`,r.error,n.name),null;let i=`${e}:${t}`;return this.deps.includes(i)||this.deps.push(i),r}bad(e,t,n){this.report(`bad_value`,`${t}="${e.attrs.get(t)??``}" ${n}`,e.name)}flag(e,t){let n=e.attrs.get(t);return n===void 0||n===`false`?!1:n===`true`||(this.bad(e,t,`must be true or false`),!1)}decor(e,t=[]){let n=this.attrs(e,[...t,`morph`,`step`,...this.blockAttrs(e)]),r=this.plain(e),i=this.steps.index.get(e);i!==void 0&&(r.classes.push(`fragment`),this.steps.explicit&&r.attrs.push([`data-fragment-index`,String(i)]));let a=e.attrs.get(`step`);this.sources&&a!==void 0&&d_.test(a)&&r.attrs.push([`data-deck-step`,a]);let o=n.get(`morph`);return o!==void 0&&(__.test(o)?r.attrs.push([`data-morph`,o]):this.bad(e,`morph`,`must be lowercase letters, digits and hyphens`)),r}blockAttrs(e){return this.placed.has(e)?[`id`,...Eh,...Uh(e.name)]:[]}plain(e){let t={classes:[],attrs:[]},n=this.placed.get(e);if(n===void 0)return t;this.id&&this.sources&&t.attrs.push([`data-deck-src`,`${this.id}:${n}`],[`data-deck-tag`,e.name]);let r=e.attrs.get(`id`);r!==void 0&&(Dh.test(r)?this.blockIds.has(r)?this.report(`bad_value`,`id="${r}" is used by another block on this slide`,e.name):(this.blockIds.add(r),this.sources&&t.attrs.push([`data-deck-id`,r])):this.bad(e,`id`,`must be letters, digits, _ and -, at most 32`));let i=this.place(e,t),a={},o=t.attrs.some(([e])=>e===`data-deck-placed`);for(let t of[`w`,`h`]){let n=e.attrs.get(t);o&&n!==void 0&&(t===`h`||n===`fill`)&&(a[t]=n)}o&&a.h!==void 0&&Ch.includes(e.name)&&i.push(`overflow:hidden`);for(let n of Uh(e.name)){let r=e.attrs.get(n);if(r===void 0)continue;let o=Zh(e.name,n,r);o?this.report(`bad_value`,o,e.name):n===`fit`&&!e.attrs.has(`h`)?this.report(`bad_value`,`fit="shrink" needs h on a free="true" slide`,e.name):(a[n]=r,n===`align`?t.attrs.push([`data-align`,r]):n===`color`&&wh.includes(r)?t.attrs.push([`data-color`,r]):n===`fit`?t.attrs.push([`data-deck-fit`,r]):i.push(...$h(n,r).map(([e,t])=>`${e}:${t}`)))}return i.length&&t.attrs.push([`style`,i.join(`;`)]),this.sources&&Object.keys(a).length&&t.attrs.push([`data-deck-look`,JSON.stringify(a)]),t}place(e,t){let n=Eh.filter(t=>e.attrs.has(t));if(!this.free)return n.length&&this.report(`bad_value`,`${n.join(`, `)} only work on a slide with free="true"`,e.name),[];if(![`x`,`y`,`w`].every(t=>e.attrs.has(t)))return this.report(`misplaced`,`<${e.name}> on a free="true" slide needs x, y and w`,e.name),[];let r={},i=!0;for(let t of n){let n=e.attrs.get(t);if(t===`w`&&n===`fill`)continue;let a=Number(n),o=t===`w`||t===`h`;!/^-?\d+$/.test(n)||Math.abs(a)>4e3||o&&a<=0?(this.bad(e,t,o?`must be a whole number of pixels above 0`:`must be a whole number of pixels`),i=!1):r[t]=a}if(!i)return[];let a=r.w??Math.max(1,1184-r.x),o=[`left:${r.x}px`,`top:${r.y}px`,`width:${a}px`];return r.h!==void 0&&o.push(`height:${r.h}px`),t.attrs.push([`data-deck-placed`,!0]),o}attrs(e,t){for(let n of e.attrs.keys())t.includes(n)||this.report(`unknown_attr`,n,e.name);return e.attrs}};const y_=/^([^#]+?)(?:#L(\d+)(?:-(\d+))?)?$/,b_=/<\/?(?:section|html|body|head)\b|<!doctype/i,x_=/<(\/?)div\b/gi;function S_(e,t){let n=e.attrs.get(`src`).trim(),r=y_.exec(n);if(!r)return t.bad(e,`src`,`must be a path, optionally followed by #L10 or #L10-24`),null;let[,i,a,o]=r,s=t.read(`project`,i,e);if(s===null)return null;let c=s.replaceAll(`\r
444
- `,`
445
- `).replace(/\n$/,``).split(`
446
- `);if(a===void 0)return c.join(`
447
- `);let l=Number(a),u=o===void 0?l:Number(o);return l<1||u<l||u>c.length?(t.report(`file`,`${i} has ${c.length} lines: ${n.slice(i.length)} is not among them`,e.name),null):c.slice(l-1,u).join(`
448
- `)}function C_(e){let t=0;for(let n of e.matchAll(x_))if(t+=n[1]?-1:1,t<0)return!0;return t!==0}function w_(e,t){let n=e.attrs.get(`src`)?.trim();if(!n)return t.bad(e,`src`,`must name an HTML file in the artifact directory`),null;let r=t.read(`artifact`,n,e);return r===null?null:b_.test(r)||C_(r)?(t.report(`file`,`${n} must be a fragment: no <html>, <body>, <head> or <section>, and every <div> closed`,e.name),null):r.trim()}const T_=/^[A-Za-z0-9+#.-]{1,32}$/;function E_(e){let t=e.replace(/^[ \t]*\n/,``).replace(/\s+$/,``).split(`
449
- `),n=Math.min(...t.filter(e=>e.trim()).map(e=>/^[ \t]*/.exec(e)[0].length));return Number.isFinite(n)?t.map(e=>e.slice(n)).join(`
450
- `):``}const D_=(e,t)=>{let n=e.attrs.get(`lang`)?.trim()??`text`;return T_.test(n)?n:(t.bad(e,`lang`,`is not a language name`),`text`)},O_=(e,t)=>{let n=t.decor(e,[`lang`,`lines`,`numbers`,`title`,`max-height`,`diff`,`src`]),r=[],i=D_(e,t),a=e.attrs.get(`lines`)?.trim();if(a!==void 0){if(Ug(a)){r.push([`data-lines`,a]);let n=t.steps.explicit?t.steps.from.get(e):void 0;n!==void 0&&r.push([`data-step-from`,String(n)])}else t.bad(e,`lines`,`must be steps split by |, each line numbers such as 1,3-5, all or hide`)}let o=e.attrs.get(`max-height`)?.trim(),s=o!==void 0&&/^\d{2,4}$/.test(o);o!==void 0&&!s&&t.bad(e,`max-height`,`must be a number of pixels`),t.flag(e,`numbers`)&&r.push([`data-numbers`,!0]);let c=e.attrs.get(`title`)?.trim();c&&r.push([`data-title`,c]),s&&r.push([`data-max-height`,o]),t.flag(e,`diff`)&&r.push([`data-diff`,!0]);let l=E_(bh(e)),u=e.attrs.has(`src`);u&&l&&t.report(`misplaced`,`a <codeblock> with src takes its code from the file: remove the code written in it`,`codeblock`);let d=u?S_(e,t):l;if(d===null)return``;if(!d)return t.report(`misplaced`,`a <codeblock> has no code: write it in CDATA or name a file with src`,`codeblock`),``;let f=g_(`code`,{classes:[`language-${i}`],attrs:r});return`${g_(`pre`,n)}${f}${m_(d)}</code></pre>`},k_=(e,t)=>(t.report(`misplaced`,`a code block is written <codeblock>; <code> is inline code inside text`,`code`),``),A_=(e,t)=>{let n=t.decor(e,[`lang`]),r=e.children.filter(e=>q(e)&&e.name===`step`?!0:(q(e)&&t.report(`unknown_tag`,`<${e.name}> cannot sit in <magic>`,e.name),!1));if(r.length<2)return t.report(`misplaced`,`a <magic> needs two or more <step>; this one has ${r.length}`,`magic`),``;n.classes.unshift(`magic-move`);let i=t.steps.explicit?t.steps.from.get(e):void 0;i!==void 0&&n.attrs.unshift([`data-step-from`,String(i)]),n.attrs.unshift([`data-lang`,D_(e,t)]);let a=r.map(e=>(t.attrs(e,[]),`<template>${m_(E_(bh(e)))}</template>`));return`${g_(`div`,n)}${a.join(``)}</div>`},j_=(e,t)=>{let n=t.decor(e);return n.classes.unshift(`mermaid`),`${g_(`pre`,n)}${m_(E_(bh(e)))}</pre>`},M_=(e,t)=>{let n=t.decor(e);return n.classes.unshift(`math`),`${g_(`div`,n)}${m_(E_(bh(e)))}</div>`},N_=(e,t,n,r=[])=>(e.classes.unshift(`deck-placeholder`),e.attrs.unshift([`data-kind`,t],...r),`${g_(`div`,e)}${m_(n)}</div>`),P_=(e,t)=>{let n=bh(e).trim(),r=t.env.checkChart?.(n)??null;r&&t.report(`bad_value`,r,`chart`);let i=`Chart`;try{let e=JSON.parse(n);typeof e==`object`&&e&&typeof e.title==`string`&&(i=e.title)}catch{r||t.report(`bad_value`,`a <chart> holds a ChartSpec as JSON, in CDATA`,`chart`)}return N_(t.decor(e),`chart`,i)},F_=(e,t)=>{let n=t.decor(e,[`src`]),r=w_(e,t);return r===null?``:(n.classes.unshift(`deck-html`),`${g_(`div`,n)}${r}</div>`)},I_=[`artboard`,`whiteboard`,`html`,`report`,`slides`],L_={artboard:[`board`],whiteboard:[`frame`,`page`],report:[`block`],slides:[`slide`]},R_=/^[\w-]+$/,z_=[...ah,...oh];function B_(e){let t=hh(e,`embed`,I_);if(t)return t;let n=lh(e);if(n===`html`)return null;let r=`<embed ${n}="${uh(e)}"`,i=L_[n],a=`an <embed> shows ${i.map(e=>`one ${e}`).join(` or `)}, named with ${i.map(e=>`${e}="…"`).join(` or `)}`;if(e.group!==void 0)return`${r} group="${e.group}"> names a group: ${a}`;let o=i.find(t=>e[t]!==void 0);if(o===void 0)return`${r}> names no ${i.join(` or `)}: ${a}`;let s=e[o];return R_.test(s)?null:`${r} ${o}="${s}">: ${o}="${s}" is not an id`}function V_(e){let t=oh.find(t=>e[t]!==void 0);return[[`data-embed-slug`,uh(e)],...t?[[`data-embed-sub`,t],[`data-embed-part`,e[t]]]:[]]}const H_=e=>{let t=dh(e);return`${lh(e)}/${uh(e)}${t?`#${t}`:``}`};function U_(e,t,n){return e.classes.unshift(`deck-embed`),e.attrs.unshift([`data-kind`,lh(t)],[`data-target`,H_(t)],...V_(t),[`data-embed-to`,n.to],...n.kind===`flow`?[[`data-flow`,!0]]:[[`style`,`--embed-w:${n.w};--embed-h:${n.h}`]]),`${g_(`div`,e)}<iframe src="${m_(n.src)}" sandbox="allow-scripts" tabindex="-1" loading="eager" title="${m_(n.title)}"></iframe></div>`}const W_=(e,t)=>{let n=t.decor(e,z_),r={};for(let t of z_){let n=e.attrs.get(t);n!==void 0&&(r[t]=n.trim())}let i=B_(r);if(i)return t.report(`bad_value`,i,`embed`),``;let a=H_(r),o=t.env.embed?.(r),s=o&&`kind`in o?o:null;t.embeds.push({slide:t.id??``,target:r,...s?{frame:s.src.split(`?`)[0]}:{}});let c=()=>t.audience?N_(n,`embed`,``):N_(n,`embed`,a,[[`data-target`,a]]);if(!o)return c();if(`missing`in o)return t.warn(`embed`,o.missing,`embed`),c();if(t.audience){let e=oh.find(e=>r[e]!==void 0);return N_(n,`embed`,``,[[`data-embed-to`,o.to],[`data-embed-kind`,lh(r)],...e?[[`data-embed-sub`,e],[`data-embed-part`,r[e]]]:[],o.kind===`flow`?[`data-flow`,``]:[`style`,`--embed-w:${o.w};--embed-h:${o.h}`]])}return U_(n,r,o)},G_=[...ah,...oh],K_={document:`file-text`,artboard:`layout-dashboard`,whiteboard:`pen-tool`,html:`code`,slides:`presentation`,report:`chart-column`,storyboard:`clapperboard`};function q_(e,t,n){return`${g_(`span`,{classes:[`deck-ref`],attrs:[[`role`,`link`],[`tabindex`,`0`],...e]})}<ryugi-icon name="${K_[t]}"></ryugi-icon><span class="deck-ref-label">${m_(n)}</span></span>`}function J_(e,t){let n=t.attrs(e,G_),r={};for(let e of G_){let t=n.get(e);t!==void 0&&(r[e]=t.trim())}let i=bh(e).trim();i&&(r.label=i);let a=hh(r);if(a)return t.report(`bad_value`,a,`ref`),m_(i);t.refs.push({slide:t.id??``,target:r});let o=lh(r),s=uh(r),c=oh.find(e=>r[e]!==void 0),l=[[`data-ref-kind`,o],...t.audience?[]:[[`data-ref-slug`,s]],...c?[[`data-ref-sub`,c],[`data-ref-part`,r[c]]]:[]],u=t.env.ref?.(r),d=t.audience?i:i||s;if(!u)return q_(l,o,d);if(`missing`in u)return t.warn(`embed`,u.missing,`ref`),q_([...l,[`data-ref-missing`,!0]],o,t.audience?i:s);let f=t.audience?i:i||u.title;return q_([...l,[`data-ref-to`,u.to]],o,f)}const Y_={b:`b`,strong:`strong`,i:`i`,em:`em`,u:`u`,s:`s`,del:`del`,strike:`s`,sub:`sub`,sup:`sup`,code:`code`},X_=[`h4`,`h5`,`h6`,`details`,`steps`,`excalidraw`,`footnote-section`,`footnote`,`def`,`dynamic`,`pending`,`ask`,`option`],Z_=e=>`<${e}> is a document block with no place on a slide`,Q_=[`highlight`,`underline`,`circle`,`strike`],$_=/^(?:https?:|mailto:|#|[^:]*$|[^/?#:]*[/?#])/i;function ev(e,t){if(e.name===`br`)return t.attrs(e,[]),`<br>`;let n=f_(Y_,e.name);if(n)return t.attrs(e,[]),`<${n}>${nv(e.children,t)}</${n}>`;if(e.name===`mark`){let n=t.decor(e,[`type`]),r=e.attrs.get(`type`)?.trim();return r!==void 0&&(Q_.includes(r)?n.classes.unshift(`deck-mark`,`deck-mark-${r}`):t.bad(e,`type`,`must be ${Q_.join(`, `)}`)),`${g_(`mark`,n)}${nv(e.children,t)}</mark>`}if(e.name===`a`){let n=t.attrs(e,[`href`]).get(`href`)?.trim()??``,r=nv(e.children,t);return!n||!$_.test(n)?(t.report(`bad_value`,`href="${n}" is not a link a slide may hold`,`a`),r):`<a href="${m_(n)}">${r}</a>`}return e.name===`icon`?tv(e,t):e.name===`ref`?J_(e,t):e.name===`math`?(t.attrs(e,[]),`<span class="math">${m_(bh(e).trim())}</span>`):(t.report(`unknown_tag`,X_.includes(e.name)?Z_(e.name):`<${e.name}> is not something text may hold`,e.name),``)}function tv(e,t){let n=t.attrs(e,[`name`,`size`,...t.blockAttrs(e)]),r=n.get(`name`)?.trim()??``,i=n.get(`size`)?.trim();if(!/^[a-z0-9-]+$/.test(r))return t.report(`bad_value`,`name="${r}" is not an icon name`,`icon`),``;if(i!==void 0&&!/^\d{1,3}$/.test(i))return t.report(`bad_value`,`size="${i}" is not a number of pixels`,`icon`),`<ryugi-icon name="${r}"></ryugi-icon>`;let a=t.plain(e);return a.attrs.unshift([`name`,r],...i?[[`size`,i]]:[]),`${g_(`ryugi-icon`,a)}</ryugi-icon>`}function nv(e,t,n){return e.map(e=>q(e)?n?.(e)??ev(e,t):m_(e.text)).join(``)}const rv=(e,t,n)=>nv(e.children,t,n).trim(),iv=(e,t,n)=>e.children.filter(r=>q(r)?n.includes(r.name)?!0:(t.report(`unknown_tag`,`<${r.name}> cannot sit in <${e.name}>`,r.name),!1):(r.text.trim()&&t.report(`misplaced`,`text straight inside <${e.name}>`,e.name),!1)),av=e=>(t,n)=>`${g_(e,n.decor(t))}${rv(t,n)}</${e}>`,ov=(e,t)=>`${g_(e.name,t.decor(e,[`steps`]))}${iv(e,t,[`li`]).map(e=>`${g_(`li`,t.decor(e))}${rv(e,t,e=>e.name===`ul`||e.name===`ol`?ov(e,t):null)}</li>`).join(``)}</${e.name}>`,sv=(e,t)=>`${g_(`table`,t.decor(e,[`steps`]))}${iv(e,t,[`tr`]).map(e=>`${g_(`tr`,t.decor(e))}${iv(e,t,[`th`,`td`]).map(e=>av(e.name)(e,t)).join(``)}</tr>`).join(``)}</table>`,cv=(e,t)=>{let n=t.decor(e,[`src`,`alt`,`frame`]),r=e.attrs.get(`src`)?.trim()??``;return t.flag(e,`frame`)&&n.classes.push(`deck-frame`),!r||/^[a-z][a-z0-9+.-]*:/i.test(r)||r.startsWith(`/`)?(t.bad(e,`src`,`must be a file inside the artifact directory`),``):(n.attrs.unshift([`src`,r],[`alt`,e.attrs.get(`alt`)??``]),g_(`img`,n))},lv=[`note`,`tip`,`important`,`warning`,`caution`],uv={h1:av(`h1`),h2:av(`h2`),h3:av(`h3`),p:av(`p`),blockquote:av(`blockquote`),ul:ov,ol:ov,table:sv,img:cv,icon:tv,alert:(e,t)=>{let n=t.decor(e,[`type`]),r=e.attrs.get(`type`)?.trim()??`note`;lv.includes(r)||(t.bad(e,`type`,`must be ${lv.join(`, `)}`),r=`note`),n.classes.unshift(`deck-alert`),n.attrs.unshift([`data-type`,r]);let i=dv(e,t,{},[]).map(e=>e.html);return`${g_(`div`,n)}${i.join(``)}</div>`},hr:(e,t)=>g_(`hr`,t.decor(e)),notes:(e,t)=>(t.attrs(e,[]),`<aside class="notes">${rv(e,t)}</aside>`),codeblock:O_,code:k_,magic:A_,mermaid:j_,math:M_,chart:P_,embed:W_,html:F_};function dv(e,t,n,r){let i=[];for(let a of e.children){if(!q(a)){a.text.trim()&&t.report(`misplaced`,`text straight inside <${e.name}>: put it in a block such as <p>`,e.name);continue}let o=f_(n,a.name)??f_(uv,a.name);if(!o){r.includes(a.name)?t.report(`misplaced`,`<${a.name}> has no place in this layout`,a.name):t.report(`unknown_tag`,X_.includes(a.name)?Z_(a.name):a.name===`ref`?`<ref> sits in text, such as a <p>: to show the artifact itself, use <embed>`:`<${a.name}> is not a block a slide may hold`,a.name);continue}let s=o(a,t);s&&i.push({name:a.name,html:s})}return i}const fv=[`top`,`right`,`bottom`,`left`,`top-right`,`bottom-left`,`top-left`,`bottom-right`],pv={cover:`full`,end:`full`,quote:`center`,fact:`center`,none:`none`};function mv(e,t,n){let r=f_(pv,e);if(r===`none`||r&&r!==n)return r;let i=fv[t%fv.length];return i===n?fv[(t+1)%fv.length]:i}const hv=[`default`,`section`,`statement`,`two-cols`,`image`,`code`],gv=(e,t)=>(n,r)=>{let i=r.decor(n);return t&&i.classes.unshift(t),`${g_(e,i)}${rv(n,r)}</${e}>`},_v=gv(`p`,`label`),vv={kicker:gv(`p`,`kicker`),subtitle:gv(`p`,`sub`),label:_v,col:(e,t)=>(t.attrs(e,[`steps`]),`<div${t.free?` data-deck-col`:``}>${dv(e,t,{label:_v},[]).map(e=>e.html).join(``)}</div>`),quote:gv(`blockquote`),cite:gv(`cite`),big:(e,t)=>{let n=t.attrs(e,[`value`,`unit`,...t.blockAttrs(e)]),r=n.get(`unit`),i=t.plain(e);return i.classes.push(`big`),`${g_(`p`,i)}<b>${m_(n.get(`value`)??``)}</b>${r===void 0?``:`<span>${m_(r)}</span>`}</p>`},fact:(e,t)=>{let n=t.attrs(e,[`value`,`label`,...t.blockAttrs(e)]);return`${g_(`li`,t.plain(e))}<b>${m_(n.get(`value`)??``)}</b><span>${m_(n.get(`label`)??``)}</span></li>`}},yv={cover:[`kicker`,`subtitle`],statement:[`subtitle`],"two-cols":[`col`],image:[`col`],quote:[`quote`,`cite`],fact:[`big`,`fact`]},bv=Object.keys(vv);function xv(e,t,n){let r=[],i=null;for(let a of e)if(a.name!==t)i=null,r.push(a);else{if(!i){let e=[];i=e,r.push({name:t,get html(){return n(e.join(``))}})}i.push(a.html)}return r}function Sv(e,t,n){let r=[...f_(yv,t)??[],...hv.includes(t)?[`label`]:[]],i=dv(e,n,Object.fromEntries(r.map(e=>[e,vv[e]])),bv),a=e=>i.filter(t=>t.name===e).length,o=(e,t)=>n.report(`misplaced`,t,e);return t===`two-cols`&&(a(`col`)!==2&&o(`col`,`a two-cols slide takes exactly two <col>`),i=xv(i,`col`,e=>`<div class="cols">${e}</div>`)),t===`image`&&a(`col`)!==1&&o(`col`,`an image slide takes one <col> for its text, beside the <img>`),t===`fact`&&(a(`fact`)>3&&o(`fact`,`a fact slide takes at most three <fact>`),i=xv(i,`fact`,e=>`<ul class="facts">${e}</ul>`)),i.map(e=>e.html)}const Cv=[`paper`,`mono`],wv=[`light`,`dark`,`auto`],Tv=/* @__PURE__ */ `paper.ink.ink-2.ink-3.accent.on-accent.info.rule.rule-strong.surface.font.font-mono.transition.transition-duration.transition-blur.fragment.fragment-duration.fragment-blur.glow.glow-1.glow-2.glow-3.glow-fade.glow-opacity.glow-blur.glow-drift.glow-hue.glow-at`.split(`.`),Ev=/[;{}<>\\]|\/\*|url\(|@import|expression\(/i,Dv=[`paper`,`surface`,`ink`,`ink-2`,`ink-3`],Ov={name:`paper`,appearance:`auto`,style:``};function kv(e,t){let n={...Ov},r=[];!e.attrs.has(`appearance`)&&Dv.some(t=>e.attrs.has(t))&&(n.appearance=`light`);for(let[i,a]of e.attrs){let o=a.trim();i===`name`?Cv.includes(o)?n.name=o:t.bad(e,i,`is not a theme: use ${Cv.join(` or `)}`):i===`appearance`?wv.includes(o)?n.appearance=o:t.bad(e,i,`must be ${wv.join(`, `)}`):Tv.includes(i)?!o||Ev.test(o)?t.bad(e,i,`is not a value a theme variable may hold`):r.push(`--deck-${i}:${o}`):t.report(`unknown_attr`,i,`theme`)}return r.length&&(n.style=`:root{${r.join(`;`)}}`),n}const Av=[`id`,`layout`,`transition`,`glow`,`glow-seed`,`glow-opacity`,`glow-hue`,`zoom`,`hidden`,`src`,`free`],jv=[`glow-seed`,`glow-opacity`,`glow-hue`],Mv=/^[a-z0-9][a-z0-9-]*$/,Nv=/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/;function Pv(e,t){let n=[];for(let r of e.children)q(r)?r.name===`notes`?n.push(uv.notes(r,t)):t.report(`misplaced`,`<${r.name}> beside src: a slide is either a file or blocks`,r.name):r.text.trim()&&t.report(`misplaced`,`text straight inside <slide>`,`slide`);let r=w_(e,t);return[...r===null?[]:[r],...n]}function Fv(e,t,n,r,i=null){let a=r.attrs(e,Av),o={classes:[],attrs:[]},s=`default`,c=a.get(`layout`)?.trim();c!==void 0&&(Mv.test(c)?(s=c,o.classes.push(`l-${c}`)):r.bad(e,`layout`,`is not a layout name`));let l=a.get(`transition`);l!==void 0&&o.attrs.push([`data-transition`,l.trim()]);let u=a.get(`glow`)?.trim(),d=u===void 0?mv(s,t,n):qg(u)?u:null;o.attrs.push([`data-glow`,u??d]);for(let e of jv){let t=a.get(e);t!==void 0&&o.attrs.push([`data-${e}`,t.trim()])}let f=a.get(`zoom`)?.trim();if(f!==void 0){let t=Number(f);/^\d*\.?\d+$/.test(f)&&t>=.3&&t<=1?o.attrs.push([`data-zoom`,f],[`style`,`--deck-zoom:${f}`]):r.bad(e,`zoom`,`must be a number from 0.3 to 1`)}r.flag(e,`hidden`)&&o.attrs.push([`data-deck-hidden`,!0]);let p=r.flag(e,`free`);p&&a.has(`src`)?r.bad(e,`free`,`cannot be on a slide of your own HTML`):p&&o.attrs.push([`data-deck-free`,!0]),i&&o.attrs.push([`data-deck-group`,i]);let m;return a.has(`src`)&&s!==`none`?(r.bad(e,`src`,`belongs to a slide with layout="none"`),m=[]):a.has(`src`)?m=Pv(e,r):(r.steps=u_(e,r),r.free=p,r.placed=kh(e),r.blockIds=/* @__PURE__ */ new Set,m=Sv(e,s,r),r.steps=a_,r.free=!1,r.placed=/* @__PURE__ */ new Map),{glow:d,html:`${g_(`section`,o,a.get(`id`))}\n${m.join(`
451
- `)}\n</section>`}}function Iv(e,t=p_,n={}){let r=new v_(t,n.audience===!0||n.published===!0,n.sources===!0),{root:i,errors:a}=xh(e);for(let e of a)r.report(`xml`,`line ${e.line}: ${e.message}`);i&&i.name!==`deck`&&r.report(`xml`,`the root element is <${i.name}>: a deck starts with <deck title="…">`);let o=i?.name===`deck`?i:null,s=o?r.attrs(o,[`title`,`lang`,`cover`]):/* @__PURE__ */ new Map,c=s.get(`title`)?.trim()||null,l=s.get(`lang`)?.trim();o&&l!==void 0&&!Nv.test(l)&&(r.bad(o,`lang`,`is not a language tag`),l=void 0);let u=[],d=/* @__PURE__ */ new Map,f=Ov,p=!1,m=null,h=[],g=/* @__PURE__ */ new Map,_=null,v=(e,t)=>{let i=e.attrs.get(`id`),a=e.attrs.get(`hidden`)?.trim()===`true`;if(i&&!g.has(i)&&g.set(i,a),n.audience&&a)return;r.slide=u.length,r.id=i||void 0;let o=Fv(e,u.length,m,r,_);m=o.glow,u.push(o.html),t&&r.id&&d.set(r.id,t),r.slide=-1,r.id=void 0},y=e=>{let t=r.attrs(e,[`src`]).get(`src`)?.trim();if(!t){r.bad(e,`src`,`must name an XML file in the artifact directory`);return}let n=r.read(`artifact`,t,e);if(n===null)return;let i=xh(n);for(let e of i.errors)r.report(`xml`,`${t} line ${e.line}: ${e.message}`);if(i.root?.name!==`slides`)r.report(`file`,`${t} must start with <slides> and hold only <slide>`,`include`);else{r.attrs(i.root,[]);for(let e of i.root.children)q(e)&&(e.name===`slide`?v(e,t):e.name===`include`?r.report(`misplaced`,`${t} includes another file: only the deck may include`,`include`):r.report(`unknown_tag`,`<${e.name}> cannot sit in <slides>`,e.name))}},b=e=>{let t=r.attrs(e,[`id`,`title`]),n=t.get(`id`)?.trim(),i=t.get(`title`)?.trim();n||r.report(`bad_value`,`a <group> needs an id`,`group`),i||r.report(`bad_value`,`a <group> needs a title`,`group`),n&&i&&h.push({id:n,title:i,at:u.length}),_=n||null;for(let t of e.children)q(t)?t.name===`slide`?v(t,null):t.name===`include`?y(t):t.name===`group`?r.report(`misplaced`,`<group> cannot sit in <group>: groups do not nest`,`group`):r.report(`misplaced`,`<${t.name}> cannot sit in <group>`,t.name):t.text.trim()&&r.report(`misplaced`,`text straight inside <group>`,`group`);_=null};for(let e of o?.children??[])q(e)?e.name===`theme`?(p||u.length?r.report(`misplaced`,`a deck takes one <theme>, before its slides`,`theme`):f=kv(e,r),p=!0):e.name===`slide`?v(e,null):e.name===`include`?y(e):e.name===`group`?b(e):r.report(`unknown_tag`,`<${e.name}> cannot sit in <deck>`,e.name):e.text.trim()&&r.report(`misplaced`,`text straight inside <deck>`);let x=/* @__PURE__ */ new Set;for(let{id:e}of h)(g.has(e)||x.has(e))&&r.report(`bad_value`,`id="${e}" is already used in this deck`,`group`),x.add(e);let S=s.get(`cover`)?.trim()||null;return S!==null&&!g.has(S)?r.warn(`bad_value`,`cover="${S}" names no slide`):S!==null&&g.get(S)&&r.warn(`bad_value`,`cover="${S}" names a hidden slide`),{html:`<!doctype html>
452
- <html${l?` lang="${m_(l)}"`:``} data-deck-source="xml" data-deck-theme="${f.name}" data-deck-appearance="${f.appearance}">
453
- <head>
454
- <meta charset="utf-8">
455
- <title>${m_(c??``)}</title>${f.style?`\n<style>${f.style}</style>`:``}
456
- </head>
457
- <body>
458
- <div class="reveal"><div class="slides">
459
- ${u.join(`
460
- `)}
461
- </div></div>
462
- </body>
463
- </html>
464
- `,issues:r.issues,warnings:r.warnings,deps:r.deps,embeds:r.embeds,origins:d,refs:r.refs,title:c,groups:h,cover:S}}function Lv(e,t){let n=W(e,`artboard`,t),r=n?ht(n).canvas:null;if(!r)return null;let i=r.groups??{};return{boards:Object.keys(r.boards??{}),groups:Object.keys(i),choices:Object.keys(i).filter(e=>i[e]?.choose)}}function Rv(e,t,n){let r=e.artboard,i=t.canvasOf(r);return i?e.group&&!i.groups.includes(e.group)?`<${n} artboard="${r}" group="${e.group}">: the artboard has no group ${e.group}`:e.board&&!i.boards.includes(e.board)?`<${n} artboard="${r}" board="${e.board}">: the artboard has no board ${e.board}`:null:null}function zv(e,t){let n=W(e,`document`,t);return n?Qc(n,t).blocks??{}:null}function Bv(e,t,n){if(!e.block)return null;let r=uh(e),i=t.documentBlocksOf(r);return i&&!Object.hasOwn(i,e.block)?`<${n} document="${r}" block="${e.block}">: the document has no block ${e.block}`:null}function Vv(e,t){let n=W(e,`report`,t);if(!n)return null;try{return $f(d.default.readFileSync(p.default.join(n,H.report),`utf8`)).map(e=>e.id)}catch{return null}}function Hv(e,t,n){if(!e.block)return null;let r=uh(e),i=t.blocksOf(r);return i&&!i.includes(e.block)?`<${n} report="${r}" block="${e.block}">: the report has no block ${e.block}; its blocks are: ${i.join(`, `)}`:null}function Uv(e,t,n){if(!e.slide)return null;let r=uh(e),i=t.slidesOf(r);return i&&!i.includes(e.slide)?`<${n} slides="${r}" slide="${e.slide}">: the deck has no slide ${e.slide}; its slides are: ${i.join(`, `)}`:null}const Wv=({refs:e,title:t})=>JSON.stringify([t??``,...e.map(e=>[e.blockId,lh(e),uh(e),dh(e)])]);function Gv(e){let t=/* @__PURE__ */ new Map;return{sources:()=>[...t].filter(([t])=>e(t)).map(([e,t])=>({slides:e,...t})),update(e,n,r){let i={refs:n.map(({slide:e,target:t})=>({blockId:e,...t})),...r?{title:r}:{}},a=t.get(e)??{refs:[]};return t.set(e,i),Wv(a)===Wv(i)?[]:[...new Set([...a.refs,...i.refs].map(e=>`${lh(e)}/${uh(e)}`))].map(e=>{let[t,n]=e.split(`/`);return{type:t,id:n}})}}}const Kv=e=>{try{return d.default.readFileSync(e,`utf8`)}catch{return null}},qv=e=>({readFile:(t,n)=>{let r=t===`artifact`?tt(e,n):null;return(r&&Kv(r))??{error:`${n} cannot be read here`}}});function Jv(e){let t=Kv(p.default.join(e,Ib));if(t===null)return[];let n=[],r=e=>(n.push(`${lh(e)}/${uh(e)}`),{missing:``});return Iv(t,{...qv(e),embed:r,ref:r}),n}function Yv(e){let t=Kv(p.default.join(e,Ib)),n=t===null?Kv(p.default.join(e,Lb)):Iv(t,qv(e)).html;if(n===null)return null;let r=i_(n);return{title:r.title||null,slides:r.slides.flatMap(({id:e})=>e?[e]:[])}}const Xv=/^(\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*)<report(?=[\s/>])/;function Zv(e){let t=p.default.join(e,H.verify),n=p.default.join(e,`report.xml`);if(d.default.existsSync(t)||!d.default.existsSync(n))return;let r;try{r=d.default.readFileSync(n,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw e}let i=r.lastIndexOf(`</report>`),a=Xv.test(r)&&i!==-1?`${r.slice(0,i).replace(Xv,`$1<verify`)}</verify>${r.slice(i+9)}`:r,o=`${t}.${process.pid}.tmp`;d.default.writeFileSync(o,a),d.default.renameSync(o,t),d.default.rmSync(n,{force:!0})}const Qv=/* @__PURE__ */ new Set([`version`,`versionNonce`,`updated`,`seed`,`customData`]),$v=/* @__PURE__ */ new Set([`width`,`height`,`baseline`]);function ey(e){let t=t=>Qv.has(t)||e.type===`text`&&$v.has(t),n=Object.keys(e).filter(e=>!t(e)).sort();return JSON.stringify(n.map(t=>[t,e[t]]))}const ty=/* @__PURE__ */ new Set([`boundElements`,`index`]),ny=/* @__PURE__ */ new Set([`x`,`y`]),ry=/* @__PURE__ */ new Set([`x`,`y`,`width`,`height`,`points`,`startBinding`,`endBinding`]);function iy(e){let t=!!(e.startBinding&&e.endBinding),n=n=>ty.has(n)||!!e.containerId&&ny.has(n)||t&&ry.has(n),r=Object.fromEntries(Object.entries(e).filter(([e])=>!n(e))),i=t?{ends:[e.startBinding.elementId,e.endBinding.elementId]}:{};return ey({...r,...i})}const ay=e=>typeof e.version!=`number`||typeof e.seed!=`number`||e.type===`richtext`&&typeof e.xml==`string`,oy=`A${`0`.repeat(26)}`;function sy(e){return e>=`a`&&e<=`z`?e.charCodeAt(0)-97+2:e>=`A`&&e<=`Z`?90-e.charCodeAt(0)+2:1/0}function cy(e){if(typeof e!=`string`||e.length===0||e===oy)return!1;let t=sy(e[0]);return t>e.length||![...e].every(e=>`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.includes(e))?!1:e.slice(t).slice(-1)!==`0`}function ly(e){let t=[{head:null,followers:[]}];for(let n of e)cy(n.index)?t.push({head:n,followers:[]}):t.at(-1).followers.push(n);let[n,...r]=t;return r.sort((e,t)=>{let n=e.head.index,r=t.head.index;return n===r?e.head.id<t.head.id?-1:1:n<r?-1:1}),[...n.followers,...r.flatMap(e=>[e.head,...e.followers])]}const uy=e=>e===`human`||e===`agent`;function dy(e){let t=e.customData??{},n={};return uy(t.ryugiAuthor)&&(n.author=t.ryugiAuthor),typeof t.ryugiRev==`number`&&(n.rev=t.ryugiRev),uy(t.ryugiLastBy)&&(n.lastBy=t.ryugiLastBy),n}function fy(e,t){let n={...e.customData};return t.author&&(n.ryugiAuthor=t.author),t.rev!==void 0&&(n.ryugiRev=t.rev),t.lastBy&&(n.ryugiLastBy=t.lastBy),{...e,customData:n}}const py=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{};function my(e,t=`scene.excalidraw`){let n;try{n=JSON.parse(e)}catch{return{error:`${t} is not valid JSON`}}let r=py(n),i=r.elements??[];if(!Array.isArray(i))return{error:`${t}: elements must be an array`};for(let[e,n]of i.entries()){let r=py(n);if(typeof r.id!=`string`||typeof r.type!=`string`)return{error:`${t}: element ${e} needs a string id and type`}}return{scene:{type:`excalidraw`,version:2,source:typeof r.source==`string`?r.source:`ryugi`,elements:i,appState:py(r.appState),files:py(r.files)}}}const hy=e=>`${JSON.stringify(e,null,2)}\n`,gy=e=>{try{return d.default.readFileSync(e,`utf8`)}catch{return null}};function _y(e){try{return d.default.readdirSync(p.default.join(e,Ue)).filter(e=>e.endsWith(`.excalidraw`)).map(e=>e.slice(0,-11)).sort()}catch{return[]}}function vy(e){let{pages:t}=Ze(Xe(gy(p.default.join(e,He))).pages,_y(e)),n={},r={};for(let i of t){let t=gy(p.default.join(e,Ke(i.id))),a=t===null?null:my(t);if(!(!a||`error`in a)){r[i.id]=a.scene;for(let e of a.scene.elements)e.type===`frame`&&!e.isDeleted&&!(e.id in n)&&(n[e.id]=i.id)}}return{pages:t,frames:n,scenes:r}}function yy(e,t){let n=W(e,`whiteboard`,t);return n?vy(n):null}function by(e,t,n){let r=e.whiteboard,i=t.framesOf(r);if(!i)return null;if(e.page){let t=i.pages.find(t=>t.id===e.page);if(!t)return`<${n} whiteboard="${r}" page="${e.page}">: the whiteboard has no page ${e.page}`;if(t.deleted)return`<${n} whiteboard="${r}" page="${e.page}">: page ${e.page} is deleted; restore it or point the reference elsewhere`}if(!e.frame)return null;let a=i.frames[e.frame];return a===void 0?`<${n} whiteboard="${r}" frame="${e.frame}">: the whiteboard has no frame ${e.frame}`:i.pages.find(e=>e.id===a)?.deleted?`<${n} whiteboard="${r}" frame="${e.frame}">: frame ${e.frame} is on deleted page ${a}`:null}function xy(e,t,n,r=`artboard`,i=dh){let a={};for(let o of n){let{refs:n,title:s}=o,[c,l]=`slides`in o?[`slides`,o.slides]:[`document`,o.document];if(c!==r||l!==e)for(let o of n){if(lh(o)!==r||uh(o)!==e||o.to&&o.to!==t)continue;let n=i(o);(a[n]??=[]).push({from:l,fromType:c,blockId:o.blockId,...s?{title:s}:{}})}}return a}function Sy(e,t){return t?Object.entries(e).flatMap(([e,n])=>e&&!t.groups.includes(e)&&!t.boards.includes(e)?n.map(({from:t,fromType:n,blockId:r})=>`${n} ${t} block ${r} references ${e}, which this artboard no longer has`):[]):[]}function Cy(e,t,n,r){return!n||!r?[]:n.choices.filter(e=>!t[e]?.length).map(t=>`choice group ${t} is not referenced by any document; if a document section discusses it, put <ref artboard="${e}" group="${t}" /> on its own line under that section's heading`)}const wy={document:Bv,artboard:Rv,whiteboard:by,html:null,slides:Uv,report:Hv,storyboard:null},Ty={document:()=>``};function Ey(e){return{idOf:(t,n=`artboard`)=>W(e,n,t)?xi(e,n,t).slice(`/${n}/`.length):null,blocksOf:t=>Vv(e,t),documentBlocksOf:t=>zv(e,t),framesOf:t=>yy(e,t),canvasOf:t=>Lv(e,t)}}function Dy(e){return{...Ey(e),slidesOf:t=>{let n=W(e,`slides`,t);return n?Gb(n,t).outline.flatMap(({id:e})=>e?[e]:[]):null}}}const Oy=RegExp(`<ref\\b[^>]*?\\b(${ih.map(e=>e.refAttribute).join(`|`)})="([^"]+)"`,`g`),ky=new Map(ih.map(e=>[e.refAttribute,e.type])),Ay=e=>[...(d.default.existsSync(e)?d.default.readFileSync(e,`utf8`):``).matchAll(Oy)].map(e=>`${ky.get(e[1])}/${e[2]}`),jy={document:e=>Ay(p.default.join(e,`doc.xml`)),artboard:null,html:null,whiteboard:null,verify:e=>(Zv(e),Ay(p.default.join(e,H.verify))),slides:e=>Jv(e),report:null,storyboard:null};function My({documents:e,refLookup:t,root:n}){let r=e=>{let t=W(n,`document`,e),r=t?Qc(t,e).title:e;return r===e?void 0:r},i=Gv(e=>W(n,`slides`,e)!==null),a=(n,a=`artboard`,o=!1)=>xy(n,t.idOf(n,a),[...e().ids().map(t=>({document:t,refs:e().refs(t),title:r(t)})),...o?i.sources():[]],a,Ty[a]);return{artboardHints:n=>{let r=Cy(n,a(n),t.canvasOf(n),e().ids().length>0);return r.length?{hints:r}:{}},artboardRefWarnings:e=>Sy(a(e),t.canvasOf(e)),backlinksOf:(e,t=`artboard`)=>a(e,t,!0),deckBacklinks:i}}function Ny(e,t,n=`ref`){let r=lh(e),i=uh(e),a=t.idOf(i,r);return a?e.to&&e.to!==a?`<${n} ${r}="${i}"> points at ${e.to}, but ${i} is now ${a}; delete to= to point the reference at it`:wy[r]?.(e,t,n)??null:`<${n} ${r}="${i}"> names ${fh[r]} that is not in this project`}function Py(e,t){return e.flatMap(e=>{let n=Ny(e,t);return n?[`block ${e.blockId}: ${n}`]:[]})}const Fy=/* @__PURE__ */ new Set([`paragraph`,`heading`,`quote`,`list`,`listitem`]),Iy=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null,Ly=e=>Array.isArray(e.children)?e.children.map(Iy).filter(e=>e!==null):[],Ry=e=>typeof e.type==`string`&&Fy.has(e.type);function zy(e){return typeof e.text==`string`?e.text:e.type===`linebreak`?` `:Ly(e).map(zy).join(``)}function By(e,t){let n=Ly(e),r=n.filter(Ry);if(r.length===0)t.push(zy(e));else{t.push(n.filter(e=>!Ry(e)).map(zy).join(``));for(let e of r)By(e,t)}}function Vy(e){let t=Iy(Iy(e)?.root);return t!==null&&Array.isArray(t.children)}function Hy(e){if(!Vy(e))return``;let t=[];for(let n of Ly(Iy(Iy(e).root)))By(n,t);return t.map(e=>e.trim()).filter(Boolean).join(`
465
- `)}const Uy={"&amp;":`&`,"&lt;":`<`,"&gt;":`>`,"&quot;":`"`,"&#39;":`'`,"&apos;":`'`},Wy=e=>e.replaceAll(/&(?:amp|lt|gt|quot|#39|apos);/g,e=>Uy[e]).trim();function Gy(e){if(typeof e!=`string`)return null;let t=/<title[^>]*>([^<]*)<\/title>/i.exec(e)?.[1];if(t?.trim())return Wy(t);let n=/^\s*<svg\b[^>]*\saria-label=(?:"([^"]*)"|'([^']*)')/i.exec(e),r=n?.[1]??n?.[2];return r?.trim()?Wy(r):null}const Ky=e=>typeof e==`string`&&/^\s*<svg[\s>]/i.test(e),qy=/* @__PURE__ */ new Set([`arrow`,`line`]),Jy=/* @__PURE__ */ new Set([`text`,`frame`,`magicframe`,`freedraw`,`arrow`,`line`]),Yy=(e,t)=>{let n=Math.ceil(e)+10;return t===`ellipse`?Math.round(n/Math.SQRT2*2):t===`diamond`?2*n:n},Xy=(e,t)=>e.x<t.x+t.w&&t.x<e.x+e.w&&e.y<t.y+t.h&&t.y<e.y+e.h,Zy=(e,[t,n])=>t>e.x&&t<e.x+e.w&&n>e.y&&n<e.y+e.h,Qy=(e,t)=>({x:e.x+t,y:e.y+t,w:e.w-2*t,h:e.h-2*t}),$y=(e,t,n)=>{if(n.w<=0||n.h<=0)return!1;let r=t[0]-e[0],i=t[1]-e[1],a=0,o=1;for(let[t,s]of[[-r,e[0]-n.x],[r,n.x+n.w-e[0]],[-i,e[1]-n.y],[i,n.y+n.h-e[1]]]){if(t===0){if(s<0)return!1;continue}let e=s/t;if(t<0?a=Math.max(a,e):o=Math.min(o,e),a>o)return!1}return!0},eb=(e,t,n)=>Math.sign((t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])),tb=(e,t,n,r)=>eb(e,t,n)*eb(e,t,r)<0&&eb(n,r,e)*eb(n,r,t)<0,nb=e=>{let{points:t}=e;if(!Array.isArray(t)||t.length<2)return null;let n=[];for(let r of t){if(!Array.isArray(r)||typeof r[0]!=`number`||typeof r[1]!=`number`)return null;n.push([(e.x??0)+r[0],(e.y??0)+r[1]])}return n},rb=e=>e.slice(1).map((t,n)=>[e[n],t]),ib=e=>rb(e).reduce((e,[t,n])=>e+Math.hypot(n[0]-t[0],n[1]-t[1]),0),ab=e=>[e.startBinding?.elementId,e.endBinding?.elementId].filter(e=>typeof e==`string`);function ob(e){let t=[];for(let n of e)n.type===`svg`&&(typeof n.svg!=`string`||!n.svg.trim()?t.push(`svg ${n.id} has no markup — put the whole <svg …>…</svg> source in its "svg" field`):Ky(n.svg)||t.push(`svg ${n.id} does not start with <svg — its "svg" field must hold one whole <svg …>…</svg> document`)),n.type===`richtext`&&!ay(n)&&!Vy(n.content)&&t.push(`card ${n.id} has no readable content — write it as "xml": "<p>…</p>" and the browser fills in the rest`);return t}function sb(e,t){let n=new Map(e.map(e=>[e.id,e])),r=[];for(let i of e){let e=t[i.id];if(i.type!==`text`||!e?.overflow)continue;let a=i.containerId?n.get(i.containerId):void 0,o=a?t[a.id]:void 0;if(!a||!o){r.push(`text ${i.id} overflows its container`);continue}let s=Yy(e.w,a.type),c=Yy(e.h,a.type),l=[s>o.w&&`${s} wide`,c>o.h&&`${c} tall`].filter(Boolean),u=l.length===2?`${Math.round(o.w)}×${Math.round(o.h)}`:s>o.w?Math.round(o.w):Math.round(o.h);r.push(l.length?`label of ${a.id} does not fit — make ${a.id} at least ${l.join(` and `)} (now ${u})`:`label of ${a.id} sticks out of it — re-center the label or enlarge ${a.id}`)}return r}function cb(e,t){let n=e.filter(e=>!Jy.has(e.type)&&!e.containerId&&t[e.id]),r=new Map(e.filter(e=>e.type===`text`&&e.containerId&&t[e.id]).map(e=>[e.containerId,t[e.id]])),i=e.flatMap(e=>{if(!qy.has(e.type)||dy(e).author!==`agent`)return[];let t=nb(e);return t?[{element:e,path:t,bound:ab(e)}]:[]}),a=[];for(let{element:e,path:o}of i){let i=[o[0],o.at(-1)],s=n.filter(e=>!i.some(n=>Zy(t[e.id],n)));for(let n of s){let r=Qy(t[n.id],2);rb(o).some(([e,t])=>$y(e,t,r))&&a.push(`arrow ${e.id} crosses ${n.id} — move ${n.id} or bend the arrow around it`)}let c=r.get(e.id);if(!c)continue;for(let n of s)Xy(c,Qy(t[n.id],2))&&a.push(`label of arrow ${e.id} covers ${n.id} — move ${n.id} or shorten the label`);let[l,u]=[i[1][0]-i[0][0],i[1][1]-i[0][1]],d=Math.hypot(l,u);if(d===0)continue;let f=Math.ceil((Math.abs(l)*c.w+Math.abs(u)*c.h)/d+40),p=ib(o);p<f&&a.push(`label of arrow ${e.id} needs the arrow to be at least ${f} px long (now ${Math.round(p)}) — move its ends apart or shorten the label`)}let o=[];for(let[e,t]of i.entries())for(let n of i.slice(e+1))t.bound.some(e=>n.bound.includes(e))||rb(t.path).some(([e,t])=>rb(n.path).some(([n,r])=>tb(e,t,n,r)))&&o.push(`${t.element.id} × ${n.element.id}`);if(o.length){let e=o.slice(0,5).join(`, `),t=o.length>5?`, and ${o.length-5} more`:``,n=o.length===1?`1 place`:`${o.length} places`;a.push(`arrows cross in ${n}: ${e}${t} — reorder the shapes so fewer arrows cross`)}return a}const lb=e=>e.elements.reduce((e,t)=>e+(t.version??0),0);function ub(e,t){let n=ir(e),r;try{r=d.default.readFileSync(p.default.join(e,H.whiteboard),`utf8`)}catch{return{title:t,warnings:[`${H.whiteboard} not found`],version:n,sceneVersion:0}}let i=my(r);if(`error`in i)return{title:t,warnings:[i.error],version:n,sceneVersion:0};let a=typeof i.scene.appState.name==`string`?i.scene.appState.name.trim():``,o=a?Re(`appState.name`,a,t):`"appState.name" is missing; give the whiteboard a title`;return{title:a||t,warnings:o?[o]:[],version:n,sceneVersion:lb(i.scene)}}const db=/* @__PURE__ */ new Set([`arrow`,`line`]),fb=(e,t)=>e.x<t.x+t.w&&t.x<e.x+e.w&&e.y<t.y+t.h&&t.y<e.y+e.h,pb=(e,t)=>t.x>=e.x&&t.y>=e.y&&t.x+t.w<=e.x+e.w&&t.y+t.h<=e.y+e.h;function mb(e,t){let n=t.file??`scene.excalidraw`,r=e.elements.filter(e=>!e.isDeleted),i=new Set(r.map(e=>e.id)),a=[];for(let e of r){if(db.has(e.type)){for(let n of[e.startBinding,e.endBinding])if(n&&!i.has(n.elementId)){let r=t.elsewhere?.(n.elementId);a.push(r?`arrow ${e.id} points to ${n.elementId} on page ${r}; arrows can't cross pages`:`arrow ${e.id} points to missing element ${n.elementId}`)}}e.containerId&&!i.has(e.containerId)&&a.push(`text ${e.id} belongs to missing container ${e.containerId}`),e.frameId&&!i.has(e.frameId)&&a.push(`element ${e.id} is in missing frame ${e.frameId}`)}a.push(...ob(r));for(let e of t.duplicates??[])a.push(`element id ${e} appears more than once in ${n}; only one copy is kept — give each element its own id`);for(let e of t.conflicts)a.push(`conflict: ${e} was changed in the browser after you read the scene; their version was kept — re-read ${n}`);t.bytes>5242880&&a.push(`${n} is ${(t.bytes/1024/1024).toFixed(1)} MB; keep it under 5 MB (images are stored inline)`);let o=t.geometry?.sceneVersion===lb(e)?t.geometry.elements:null;if(o){a.push(...sb(r,o));for(let e of r){let t=o[e.id],n=e.frameId?o[e.frameId]:void 0;t&&n&&!e.containerId&&!db.has(e.type)&&(dy(e).lastBy!==`agent`||pb(n,t)||a.push(`element ${e.id} sticks out of frame ${e.frameId}, which hides the part outside — move it in or resize the frame`))}let e=r.filter(e=>dy(e).author===`agent`&&e.type!==`frame`&&e.type!==`text`&&!db.has(e.type)&&o[e.id]);for(let[t,n]of e.entries())for(let r of e.slice(t+1)){let e=o[n.id],t=o[r.id];fb(e,t)&&!pb(e,t)&&!pb(t,e)&&a.push(`elements ${n.id} and ${r.id} overlap`)}a.push(...cb(r,o))}return{warnings:a,pending:r.some(ay)?[`skeleton_not_completed`]:[]}}function hb(e){let t=e.pages.length>1,n=/* @__PURE__ */ new Map;for(let t of e.pages)for(let e of t.scene.elements)e.isDeleted||n.set(e.id,[...n.get(e.id)??[],t.id]);let r=[...e.pagesWarnings],i=[];for(let a of e.pages){let e=mb(a.scene,{bytes:a.bytes,conflicts:a.conflicts,duplicates:a.duplicates,geometry:a.geometry,file:Ke(a.id),elsewhere:e=>n.get(e)?.find(e=>e!==a.id)??null}),o=[...a.problem?[a.problem]:[],...e.warnings];r.push(...o.map(e=>t?`[${a.id}] ${e}`:e)),i.push(...e.pending.map(e=>t?`${e}:${a.id}`:e))}for(let[e,t]of n){let n=[...new Set(t)];n.length>1&&r.push(`element id ${e} is on pages ${n.join(` and `)}; give each element its own id`)}return{warnings:r,pending:i}}function gb(e,t,n){let r=e=>/^\[([a-z0-9-]+)\] /.exec(e)?.[1],i=e=>{let t=e.lastIndexOf(`:`);return t===-1?void 0:e.slice(t+1)},a=e=>e===void 0||e===t||!n.includes(e);return{warnings:e.warnings.filter(e=>a(r(e))),pending:e.pending.filter(e=>a(i(e)))}}function _b(e){return{...Ey(e),slidesOf:t=>{let n=W(e,`slides`,t);return n?Yv(n)?.slides??null:null}}}function vb(e,t,n){if(e===`document`)return Qc(t,n).title;if(e===`artboard`)return ht(t).canvas?.title;if(e===`whiteboard`)return ub(t,n).title;if(e===`html`)return $l(t,n).title;if(e===`slides`)return Yv(t)?.title;try{return Op(d.default.readFileSync(p.default.join(t,H.report),`utf8`))}catch{return null}}function yb(e){let t=_b(e);return n=>{let r=lh(n),i=uh(n),a=W(e,r,i),o=Ny(n,t);if(o)return{missing:o};let s=t.idOf(i,r);return!a||!s?{missing:`<ref ${r}="${i}"> cannot be read`}:{title:vb(r,a,i)||i,to:s}}}const bb={w:1280,h:720},xb=e=>{try{return d.default.statSync(e).mtimeMs}catch{return 0}};function Sb(e){let t=e.x??0,n=e.y??0,r=e.width??0,i=e.height??0,a=Array.isArray(e.points)?e.points:null,o=a?.length?a.map(([e,r])=>[t+e,n+r]):[[t,n],[t+r,n],[t,n+i],[t+r,n+i]],s=typeof e.angle==`number`?e.angle:0;if(!s)return o;let c=t+r/2,l=n+i/2,u=Math.cos(s),d=Math.sin(s);return o.map(([e,t])=>[c+(e-c)*u-(t-l)*d,l+(e-c)*d+(t-l)*u])}function Cb(e,t,n,r,i,a,o){let s=n.frame?r.frames[n.frame]:n.page,c=p.default.join(e,Ke(s));o(c);let l=(r.scenes[s]?.elements??[]).filter(e=>!e.isDeleted),u=n.frame?l.find(e=>e.id===n.frame):void 0,d=u?{w:u.width??0,h:u.height??0}:wb(l);return!d||!(d.w>0&&d.h>0)?{missing:`${i}: ${n.frame?`frame ${n.frame}`:`page ${s}`} has nothing drawn on it yet`}:{kind:`frame`,src:`../../whiteboard/${t}/embed.html?${new URLSearchParams({...n.frame?{frame:n.frame}:{},page:s,v:String(Math.round(xb(c)))})}`,w:Math.round(d.w),h:Math.round(d.h),title:u?.name||ub(e,t).title,to:a}}function wb(e){let t=e.flatMap(Sb);if(!t.length)return null;let n=t.map(([e])=>e),r=t.map(([,e])=>e);return{w:Math.max(...n)-Math.min(...n),h:Math.max(...r)-Math.min(...r)}}function Tb(e,t,n,r,i,a){a(p.default.join(e,`canvas.json`));let o=ht(e),s=o.canvas?.boards[n];if(!s)return{missing:`${r}: the artboard has no board ${n}`};if(Oe(s))return{missing:`${r}: board ${n} is ${s.type===`image`?`an image`:`a video`}, not a page`};let c=it(e,s.file);a(c??p.default.join(e,s.file));let l=o.versions[s.file];return!c||!l?{missing:`${r}: board ${n} is still being written`}:{kind:`frame`,src:`../../artboard/${t}/${encodeURI(s.file)}?v=${Math.round(l)}`,w:s.w,h:s.h,title:s.title||n,to:i}}function Eb(e,t,n,r,i){let a=p.default.join(e,H.html);return i(a),d.default.existsSync(a)?{kind:`frame`,src:`../../html/${t}/${H.html}?v=${Math.round(ir(e))}`,...bb,title:$l(e,t).title,to:r}:{missing:`${n}: the page has no ${H.html} yet`}}function Db(e,t,n,r,i){let a=p.default.join(e,H.report);i(a);for(let t of d.default.existsSync(p.default.join(e,`data`))?d.default.readdirSync(p.default.join(e,up)):[])i(p.default.join(e,up,t));let o=``;try{o=d.default.readFileSync(a,`utf8`)}catch{o=``}return{kind:`flow`,src:`../../report/${t}/index.html?block=${encodeURIComponent(n)}&embed&v=${Math.round(ir(e))}`,title:Op(o)||t,to:r}}function Ob(e,t,n,r,i){return i(p.default.join(e,Ib)),{kind:`frame`,src:`../../slides/${t}/index.html?embed=${encodeURIComponent(n)}&v=${Math.round(ir(e))}`,...bb,title:Yv(e)?.title||t,to:r}}function kb(e,t,n,r){if(!Jn(n))return;let i=p.default.join(e,t,n);if(t===`html`&&r(p.default.join(i,H.html)),t===`artboard`&&r(p.default.join(i,H.artboard)),t===`report`&&r(p.default.join(i,H.report)),t===`slides`&&r(p.default.join(i,Ib)),t===`whiteboard`){r(p.default.join(i,He)),r(p.default.join(i,Ue));for(let e of[Ve,..._y(i)])r(p.default.join(i,Ke(e)))}}function Ab(e,t){let n=_b(e);return r=>{let i=lh(r),a=uh(r),o=Ny(r,n,`embed`);if(o)return kb(e,i,a,t),{missing:o};let s=W(e,i,a),c=n.idOf(a,i),l=r.board??r.frame,u=`<embed ${i}="${a}"${l?` ${r.board?`board`:`frame`}="${l}"`:``}>`;if(!s||!c)return{missing:`${u} cannot be read`};if(i===`report`&&r.block)return Db(s,a,r.block,c,t);if(i===`slides`&&r.slide)return Ob(s,a,r.slide,c,t);if(i===`html`)return Eb(s,a,u,c,t);if(i===`artboard`&&r.board)return Tb(s,a,r.board,u,c,t);let d=i===`whiteboard`?n.framesOf(a):null;return d&&(r.frame||r.page)?Cb(s,a,r,d,u,c,t):{missing:`${u} cannot be read`}}}const jb=/^(?:id_(?:rsa|dsa|ecdsa|ed25519)\b.*|(?:secrets?|credentials?)(?:\..*)?|.*\.(?:pem|key|p12|pfx|jks|keystore|tfstate|tfvars)(?:\..*)?)$/i,Mb=(e,t)=>e.toLowerCase().startsWith(`${t.toLowerCase()}${p.default.sep}`);function Nb(e,t){let n={error:`${t} is outside what a deck may read`};if(p.default.isAbsolute(t))return n;let r=tt(e,t);if(!r)return n;let i;try{if(i=d.default.realpathSync(r),!Mb(i,d.default.realpathSync(e)))return n;let a=d.default.statSync(i);if(!a.isFile())return{error:`${t} is not a file`};if(a.size>524288)return{error:`${t} is too large to put on a slide`}}catch{return{error:`${t} was not found`}}return i}function Pb(e,t){try{return(0,l.execFileSync)(`git`,[`check-ignore`,`-q`,`--`,t],{cwd:e,stdio:`ignore`,timeout:2e3}),!0}catch{return!1}}function Fb(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map;return{deps:()=>[...n],embed:Ab(p.default.resolve(e,`../..`),e=>n.add(e)),ref:yb(p.default.resolve(e,`../..`)),checkChart:t=>cl.chart(t,e)??null,readFile(i,a){let o=Nb(i===`project`?t:e,a);if(typeof o!=`string`)return o;if(jb.test(p.default.basename(o))||jb.test(p.default.basename(a)))return{error:`${a} is named like a secret, and a deck does not show those`};if(i===`project`&&(r.has(o)||r.set(o,Pb(t,o)),r.get(o)))return{error:`git ignores ${a}, and a deck does not show ignored files`};if(i===`artifact`&&p.default.basename(o).toLowerCase()===`comments.json`)return{error:`${a} is not part of the deck`};try{let e=d.default.readFileSync(o,`utf8`);return n.add(o),e}catch{return{error:`${a} could not be read`}}}}}const Ib=`deck.xml`,Lb=`index.html`,Rb=e=>p.default.resolve(e,`../../../..`);function zb(e){try{return d.default.readFileSync(e,`utf8`)}catch{return null}}function Bb(e,t=!1,n=!1){let r=Vb(e,void 0,{sources:t,published:n});return r?.source===`xml`?r.html:null}function Vb(e,t=Rb(e),n={}){let r=zb(p.default.join(e,Ib));if(r===null){let t=zb(p.default.join(e,Lb));return t===null?null:{html:t,source:`html`,issues:[],warnings:[],deps:[],embeds:[],refs:[],both:!1,complete:null,origins:/* @__PURE__ */ new Map,title:null,groups:[],cover:null}}let i=Fb(e,t),a;try{a=Iv(r,i,n)}catch(e){a={html:``,title:null,deps:[],embeds:[],refs:[],warnings:[],origins:/* @__PURE__ */ new Map,groups:[],cover:null,issues:[{code:`xml`,slide:-1,detail:`the deck could not be read: ${e instanceof Error?e.message:String(e)}`}]}}return{html:a.html,source:`xml`,issues:a.issues,warnings:a.warnings,deps:i.deps(),embeds:a.embeds,refs:a.refs,both:d.default.existsSync(p.default.join(e,Lb)),complete:/<\/deck\s*>\s*$/.test(r),origins:a.origins,title:a.title,groups:a.groups,cover:a.cover}}function Hb(e){let t=Vb(e),n={files:[],embeds:[],refs:[],title:null};if(!t)return n;let r;try{r=d.default.realpathSync(e)+p.default.sep}catch{return n}return{files:t.deps.filter(e=>!e.startsWith(r)),embeds:t.embeds,refs:t.refs,title:t.title}}function Ub(e,t){let n=p.default.resolve(e,t);return n.startsWith(`${e}${p.default.sep}`)&&d.default.existsSync(n)}function Wb(e){try{return d.default.statSync(e).mtimeMs}catch{return 0}}function Gb(e,t,n=Rb(e)){let r=Vb(e,n),i=Math.max(ir(e,`comments.json`),...(r?.deps??[]).map(Wb));if(!r)return{title:t,version:i,complete:!1,outline:[],issues:[],warnings:[`${Ib} not found`]};let a=i_(r.html),o=r.source===`xml`,s=new Set(r.embeds.flatMap(({frame:e})=>e?[e]:[]));return{title:r.title||a.title||t,version:i,complete:r.complete??a.complete,outline:a.slides,issues:[...r.both?[{code:`two_entries`,slide:-1}]:[],...a.issues,...a.assets.filter(t=>!s.has(t)&&!Ub(e,t)).map(e=>({code:`missing_asset`,slide:-1,detail:e}))],...o?{sourceIssues:r.issues,sourceWarnings:r.warnings}:{},...o?{groups:r.groups,origins:Object.fromEntries(r.origins),...r.cover?{cover:r.cover}:{}}:{},warnings:o||a.hasDeck?[]:[`index.html has no <div class="reveal"><div class="slides">`]}}function Kb(e,t,n){let r=t?.version===e.version?t:null,i=n?.version===e.version?n:null;return{ran:r!==null,sheet:i,pending:r?.draws&&!i?[`sheet_not_drawn`]:[],diagnostics:Rg(e.issues,r,e.sourceIssues,e.sourceWarnings),outline:{version:e.version,title:e.title,slides:e.outline.map(e=>({...e,overflow:r&&e.id?r.overflow.includes(e.id):null}))}}}function qb(e,{artifact:t,version:n,overflow:r,errors:i,sheet:a}){if(typeof t!=`string`||typeof n!=`number`)return;let o=G(t);if(o?.type!==`slides`||t!==`slides/${o.id}`)return;let s=W(e.root,`slides`,o.id);if(!s||n!==Gb(s,o.id).version)return;let c=Pg({ns:yg,type:`report`,overflow:r,errors:i});c?.type===`report`&&(e.slidesReports.set(t,{version:n,overflow:c.overflow,errors:c.errors,draws:a===!0}),e.writeState(o,s))}const Jb=(e,t)=>e.lastIndexOf(`
466
- `,t-1)+1,Yb=(e,t)=>{let n=e.indexOf(`
467
- `,t);return n===-1?e.length:n+1},Xb=/^[ \t]*$/,Zb=e=>e.includes(`\r
468
- `)?`\r
469
- `:`
470
- `;function Qb(e,t){let n=Jb(e,t.start),r=e.slice(n,t.start),i=Yb(e,t.end);if(!Xb.test(r)||!/^[ \t]*\r?\n?$/.test(e.slice(t.end,i)))return{start:t.start,end:t.end,indent:``,own:!1};let a=n;for(;a>0;){let t=Jb(e,a-1);if(!e.slice(t,a).trimEnd().endsWith(`-->`))break;let n=e.lastIndexOf(`<!--`,a);if(n===-1)break;let r=Jb(e,n);if(!Xb.test(e.slice(r,n)))break;a=r}return{start:a,end:i,indent:r,own:!0}}const $b=/<!\[CDATA\[[\s\S]*?\]\]>|<(codeblock|pre|mermaid|math)\b(?:[^>"']|"[^"]*"|'[^']*')*(?<!\/)>[\s\S]*?<\/\1\s*>/g,ex=e=>[...e.matchAll($b)].map(e=>({start:e.index,end:e.index+e[0].length}));function tx(e,t,n){let r=ex(e),i=0;return e.split(/(?<=\n)/).map(e=>{let a=i;return i+=e.length,r.some(e=>e.start<a&&a<e.end)?e:e.trim()&&e.startsWith(t)?n+e.slice(t.length):e}).join(``)}function nx(e,t){let n=[...t].sort((e,t)=>e.start-t.start||Number(e.end>e.start)-Number(t.end>t.start)),r=``,i=0;for(let t of n){if(t.start<i)throw Error(`overlapping edits`);r+=e.slice(i,t.start)+t.text,i=t.end}return r+e.slice(i)}const rx=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`);function ix(e,t,n){let r=RegExp(`\\s+${t}\\s*=\\s*(?:"[^"]*"|'[^']*')`),i=r.exec(e);if(n===null)return i?e.replace(r,``):e;let a=` ${t}="${rx(n)}"`;return i?e.replace(r,()=>a):e.replace(/(\s*\/?>)$/,e=>`${a}${e}`)}var ax=class extends Error{};const ox=`deck`,J=e=>{throw new ax(e)};function sx(e,t,n){let{root:r,errors:i}=xh(e);return(!r||i.length||r.name!==t)&&J(`${n===`deck`?`deck.xml`:n} cannot be read as XML; fix it first`),r}const cx=e=>e.children.filter(q);function lx(e){let t=sx(e.deck,`deck`,ox),n={deck:t,groups:/* @__PURE__ */ new Map,ids:/* @__PURE__ */ new Set,roots:/* @__PURE__ */ new Map([[ox,t]]),slides:/* @__PURE__ */ new Map,files:/* @__PURE__ */ new Map},r=(t,r,i)=>{if(t.name===`slide`){let e=t.attrs.get(`id`);e&&!n.slides.has(e)&&n.slides.set(e,{el:t,container:r,group:i,file:ox}),e&&n.ids.add(e)}else if(t.name===`include`){let r=t.attrs.get(`src`)?.trim(),a=r===void 0?void 0:e.includes[r];if(!r||a===void 0||n.files.has(r))return;let o=sx(a,`slides`,r);n.roots.set(r,o);let s=[];for(let e of cx(o)){let a=e.attrs.get(`id`);e.name===`slide`&&a&&(s.push(a),n.ids.add(a),n.slides.has(a)||n.slides.set(a,{el:e,container:o,group:i,file:r,include:t}))}n.files.set(r,s)}};for(let e of cx(t))if(e.name===`group`){let t=e.attrs.get(`id`);t&&(n.groups.set(t,e),n.ids.add(t));for(let n of cx(e))r(n,e,t??null)}else r(e,t,null);return n}const ux=(e,t)=>e.slides.get(t)??J(`no slide ${t}`),dx=(e,t)=>e.groups.get(t)??J(`no group "${t}"`),fx=(e,t)=>t===`deck`?e.deck:e.includes[t];function px(e,t){for(let n of cx(t)){let t=Qb(e,n);if(t.own&&t.indent)return t.indent}return` `}function mx(e,t){let n=Qb(e,t);return{block:n,el:e.slice(t.start,t.end),indent:n.indent,lead:n.own?e.slice(n.start,Jb(e,t.start)):``}}function hx(e,t,n,r){return t?e.map(e=>tx(`${e.lead}${e.indent}${e.el}${r}`,e.indent,n)).join(``):e.map(e=>e.el).join(``)}function gx(e,t){let n=Qb(e,t),r=n.own?n.start:t.start;return{edit:e=>({start:r,end:r,text:e(n.own,n.indent)})}}function _x(e,t){let n=Qb(e,t),r=n.own?n.end:t.end;return{edit:e=>({start:r,end:r,text:e(n.own,n.indent)})}}function vx(e,t,n){let r=Zb(e);if(t.selfClosing){let i=Qb(e,t),a=e.slice(t.start,t.end).replace(/\s*\/>$/,`>`);return{edit:e=>({start:t.start,end:t.end,text:i.own?`${a}${r}${e(!0,i.indent+n)}${i.indent}</${t.name}>`:`${a}${e(!1,``)}</${t.name}>`})}}let i=t.innerEnd,a=Jb(e,i),o=e.slice(a,i);return/^[ \t]*$/.test(o)&&a>t.innerStart?{edit:e=>({start:a,end:a,text:e(!0,o+n)})}:{edit:e=>({start:i,end:i,text:e(!1,``)})}}function yx(e){return e.map(({block:e})=>({start:e.start,end:e.end,text:``}))}const bx=(e,t)=>{let n=[...new Set(t)];return n.length||J(`no slides named`),n.map(t=>ux(e,t)).sort((e,t)=>e.file===t.file?e.el.start-t.el.start:e.file===`deck`?-1:1)};function xx(e,t,n){let r=t=>e.ids.has(t)||n.has(t);if(!r(t))return t;for(let e=2;;e++)if(!r(`${t}-${e}`))return`${t}-${e}`}function Sx(e,t){let n=e.indexOf(`>`);return ix(e.slice(0,n+1),`id`,t)+e.slice(n+1)}const Cx=e=>e.join(`, `),wx=(e,t)=>/* @__PURE__ */ new Map([[e,t]]),Tx=e=>[...kh(e)].map(([e,t])=>({el:e,path:t}));function Ex(e,t){let n=Tx(e);return t.startsWith(`#`)?n.find(e=>e.el.attrs.get(`id`)===t.slice(1))??null:n.find(e=>e.path===t)??null}const Dx=(e,t)=>e.slice(t.start,t.selfClosing?t.end:t.innerStart),Ox=e=>bh(e).replaceAll(/\s+/g,` `).trim();function kx(e){let t=Ox(e)||e.attrs.get(`value`)||e.attrs.get(`alt`)||``,n=t.length>40?`${t.slice(0,39)}…`:t;return n?`${e.name} "${n}"`:e.name}const Ax=e=>e===void 0?null:Number(e);function jx(e){return{tag:e.name,text:Ox(e),x:Ax(e.attrs.get(`x`)),y:Ax(e.attrs.get(`y`)),w:e.attrs.get(`w`)===`fill`?`fill`:Ax(e.attrs.get(`w`)),h:Ax(e.attrs.get(`h`)),align:e.attrs.get(`align`)??null,color:e.attrs.get(`color`)??null,look:Object.fromEntries(Ah.flatMap(t=>{let n=e.attrs.get(t);return n===void 0?[]:[[t,n]]}))}}function Mx(e,t,n){let r;try{r=lx(e).slides.get(t)}catch(e){if(e instanceof ax)return null;throw e}if(!r||fx(e,r.file)===void 0)return null;let i=Ex(r.el,n);return i?{path:i.path,state:jx(i.el)}:null}function Nx(e,t){let n;try{n=lx(e).slides.get(t)}catch(e){if(e instanceof ax)return[];throw e}return!n||fx(e,n.file)===void 0?[]:Tx(n.el).map(({el:e,path:t})=>({id:e.attrs.get(`id`)??null,path:t,state:jx(e)}))}function Px(e){try{return[...lx(e).slides.keys()]}catch(e){if(e instanceof ax)return[];throw e}}const Fx=[`b`,`i`,`u`,`a`],Ix=[`ul`,`ol`],Lx=/^(https?:|mailto:|#)/;function Rx(e){return e.selfClosing?[]:Ix.includes(e.name)?e.children.filter(q).filter(e=>e.name===`li`&&!e.selfClosing).flatMap(e=>{let t=e.children.filter(q).filter(e=>Ix.includes(e.name)),n=t[0]?.start??e.innerEnd;return[...n>e.innerStart?[{start:e.innerStart,end:n}]:[],...t.flatMap(Rx)]}):[{start:e.innerStart,end:e.innerEnd}]}function zx(e,t){let{root:n,errors:r}=xh(`<x>${e}</x>`);if(!n||r.length)return null;let i=n.children.filter(e=>q(e)||e.text.trim()),a=i.length===1?i[0]:null;return!a||!q(a)||a.name!==t||a.selfClosing?null:`<x>${e}</x>`.slice(a.innerStart,a.innerEnd)}const Bx=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`);function Vx(e,t,n,r){n===`a`&&!(r&&Lx.test(r)&&r.length<=2e3)&&J(`a link needs an http, https, mailto or # address`);let i=[...new Set(t.map(t=>eS(e,t).el))];for(let e of i)Ch.includes(e.name)||J(`<${e.name}> holds no text`);let a=i.flatMap(e=>Rx(e).map(t=>({el:e,unit:t}))),o=a.map(({unit:t})=>e.text.slice(t.start,t.end)),s=o.length>0&&o.every(e=>zx(e.trim(),n)!==null),c=n===`a`?`<a href="${Bx(r)}">`:`<${n}>`,l=[],u=/* @__PURE__ */ new Map;a.forEach(({el:t,unit:r},i)=>{let a=o[i],d=a.length-a.trimStart().length,f=a.length-a.trimEnd().length,p=a.trim();if(!s&&zx(p,n)!==null)return;let m=s?zx(p,n):`${c}${p}</${n}>`;l.push({start:r.start+d,end:r.end-f,text:m}),u.has(t)||u.set(t,nS(e,t))});for(let[t,n]of u)t.attrs.get(`id`)!==n&&l.push(rS(e,t,[[`id`,n]]));return{changes:`${s?`removed`:`applied`} <${n}> on ${oS([...u.keys()])} on slide ${e.slide}`,edits:wx(e.file,l),touched:[...u.values()].map(t=>aS(e,t))}}const Hx=[`misplaced`,`unknown_tag`,`unknown_attr`,`bad_value`];function Ux(e,t){let n=ux(lx(e),t),r=fx(e,n.file)??J(`no file for slide ${t}`),i=r.slice(n.el.start,n.el.end),a=Dx(r,n.el),o=e=>{let{issues:t}=Iv(`<deck title="x">${ix(a,`layout`,e==="default"?null:e)}${i.slice(a.length)}</deck>`);return t.filter(e=>Hx.includes(e.code)).length},s=o(n.el.attrs.get(`layout`)??`default`);return zg.filter(e=>e!==`none`&&o(e)<=s)}function Wx(e,t,n){return t.el.attrs.get(`free`)===`true`&&J(`slide ${t.slide} is free: restore its layout before changing it`),Ux(e,t.slide).includes(n)||J(`the blocks on slide ${t.slide} do not fit the ${n} layout`),{changes:`changed the layout of slide ${t.slide} to ${n}`,edits:wx(t.file,[rS(t,t.el,[[`layout`,n==="default"?null:n]])])}}function Gx(e,t){return cx(e).includes(t)?e:cx(e).find(e=>cx(e).includes(t))??e}function Kx(e,t,n){e.el.attrs.get(`free`)!==`true`&&J(`slide ${e.slide} is not free: its blocks keep their reading order`);let{el:r}=eS(e,t),i=cx(Gx(e.el,r)).filter(e=>Oh(e.name)),a=i.filter(e=>e!==r),o=Math.max(0,Math.min(Math.floor(n),a.length)),s=nS(e,r);if(i.indexOf(r)===o)return{changes:`kept ${oS([r])} in place`,edits:wx(e.file,[]),touched:[]};let c=mx(e.text,r),l=Dx(e.text,r),u={...c,el:ix(l,`id`,s)+c.el.slice(l.length)},d=Zb(e.text),f=o<a.length?gx(e.text,a[o]):_x(e.text,a.at(-1));return{changes:`moved ${oS([r])} to place ${o+1} on slide ${e.slide}`,edits:wx(e.file,[...yx([c]),f.edit((e,t)=>hx([u],e,t,d))]),touched:[aS(e,s)]}}const qx=()=>`b${Math.random().toString(36).slice(2,8)}`,Jx=[`h1`,`h2`,`h3`,`p`,`kicker`,`subtitle`,`label`,`ul`,`ol`],Yx=[`ul`,`ol`],Xx={b:[],strong:[],i:[],em:[],u:[],s:[],del:[],strike:[],sub:[],sup:[],code:[],br:[],math:[],mark:[`type`,`step`],a:[`href`],icon:[`name`,`size`]},Zx={li:[`step`],ul:[],ol:[]};function Qx(e,t,n,r){let i=ux(t,n);i.el.attrs.has(`src`)&&J(`slide ${n} is your own HTML: its blocks cannot be edited`);let a=new Set(Tx(i.el).map(e=>e.el.attrs.get(`id`)).filter(e=>!!e));return{el:i.el,file:i.file,ids:a,newId:r,slide:n,text:fx(e,i.file)}}function $x(e){for(;;){let t=e.newId();if(!e.ids.has(t))return e.ids.add(t),t}}function eS(e,t){return Ex(e.el,t)??J(`no block ${t} on slide ${e.slide}`)}const tS=e=>e.el.attrs.get(`free`)===`true`;function nS(e,t){return t.attrs.get(`id`)??$x(e)}function rS(e,t,n,r){let i=Dx(e.text,t);for(let[e,t]of n)i=ix(i,e,t);return r&&(i=`<${r}${i.slice(t.name.length+1)}`),{start:t.start,end:t.start+Dx(e.text,t).length,text:i}}const iS=e=>[[`x`,String(e.x)],[`y`,String(e.y)],[`w`,String(e.w)],[`h`,e.h===void 0?null:String(e.h)]],aS=(e,t,n=!1)=>({slide:e.slide,id:t,removed:n}),oS=e=>e.map(kx).join(`, `);function sS(e,t){let n=Tx(e.el),r=[],i=[rS(e,e.el,[[`free`,`true`]])];for(let{el:a,path:o}of n){let n=nS(e,a),s=t[o]??t[`#${n}`]??{x:0,y:0,w:1280};i.push(rS(e,a,[[`id`,n],...iS(s)])),r.push(aS(e,n))}return{changes:`pinned slide ${e.slide} to free placement`,edits:wx(e.file,i),touched:r}}function cS(e,t){tS(e)||J(`slide ${e.slide} is not free: pin it first`);let n=/* @__PURE__ */ new Map;for(let{block:r,box:i}of t)n.set(eS(e,r).el,i);let r=[],i=[...n].map(([t,n])=>{let i=nS(e,t);return r.push(aS(e,i)),rS(e,t,[[`id`,i],...iS(n)])});return{changes:`moved ${oS([...n.keys()])} on slide ${e.slide}`,edits:wx(e.file,i),touched:r}}function lS(e){let t=[[`x`,null],[`y`,null],[`w`,null],[`h`,null],[`fit`,null]];return{changes:`restored the layout of slide ${e.slide}`,edits:wx(e.file,[rS(e,e.el,[[`free`,null]]),...Tx(e.el).map(({el:n})=>rS(e,n,t))])}}function uS(e,t){let{root:n,errors:r}=xh(`<x>${e}</x>`);(!n||r.length)&&J(`the text is not well-formed`);let i=e=>{for(let n of e.children){if(!q(n))continue;let e=Xx[n.name]??(t?Zx[n.name]:void 0);!Object.hasOwn(Xx,n.name)&&!(t&&Object.hasOwn(Zx,n.name))&&J(`<${n.name}> cannot be written in this text`);for(let t of n.attrs.keys())e.includes(t)||J(`<${n.name} ${t}> cannot be written in this text`);i(n)}};i(n)}function dS(e,t,n){let{el:r}=eS(e,t);Ch.includes(r.name)||J(`<${r.name}> holds no text to edit`),n.length>2e5&&J(`the text is too long`),uS(n,Yx.includes(r.name));let i=nS(e,r),a=rS(e,r,[[`id`,i]]),o=r.selfClosing?[{start:r.start,end:r.end,text:`${a.text.replace(/\s*\/>$/,`>`)}${n}</${r.name}>`}]:[a,{start:r.innerStart,end:r.innerEnd,text:n}];return{changes:`edited the text of ${kx(r)} on slide ${e.slide}`,edits:wx(e.file,o),touched:[aS(e,i)]}}function fS(e,t,n){let{el:r}=eS(e,t);Jx.includes(n)&&Jx.includes(r.name)||J(`<${r.name}> cannot become <${n}>`);let i=nS(e,r),a=Yx.includes(r.name),o=Yx.includes(n),s=r.selfClosing?``:e.text.slice(r.innerStart,r.innerEnd),c=s;o&&!a&&(c=`<li>${s.trim()}</li>`),a&&!o&&(c=cx(r).filter(e=>e.name===`li`).map(t=>e.text.slice(t.innerStart,t.innerEnd).trim()).join(`<br/>`));let l=`${rS(e,r,[[`id`,i],...o?[]:[[`steps`,null]]],n).text.replace(/\s*\/>$/,`>`)}${c}</${n}>`;return{changes:`turned ${kx(r)} into ${n} on slide ${e.slide}`,edits:wx(e.file,[{start:r.start,end:r.end,text:l}]),touched:[aS(e,i)]}}function pS(e,t,n){tS(e)||J(`${t} only changes on a free slide: pin slide ${e.slide} first`),n===null?t===`w`&&J(`a block on a free slide needs w`):(t!==`w`||n!==`fill`)&&(!/^\d+$/.test(n)||Number(n)<1||Number(n)>4e3)&&J(`${t} must be a whole number of pixels above 0`)}function mS(e,t,n,r){if(n===`w`||n===`h`)return pS(e,n,r);if(r===null){Uh(t.name).includes(n)||J(`<${t.name}> takes no ${n}`);return}let i=Zh(t.name,n,r);i&&J(i),n===`fit`&&!t.attrs.has(`h`)&&J(`fit="shrink" needs a fixed height`)}function hS(e,t,n,r){let i=[...new Set(t.map(t=>eS(e,t).el))];for(let t of i)mS(e,t,n,r);let a=[],o=i.map(t=>{let i=nS(e,t);return a.push(aS(e,i)),rS(e,t,[[`id`,i],[n,r],...n===`h`&&r===null?[[`fit`,null]]:[]])});return{changes:`${r===null?`cleared ${n} on`:`set ${n} ${r} on`} ${oS(i)} on slide ${e.slide}`,edits:wx(e.file,o),touched:a}}function gS(e,t){let n=[...new Set(t.map(t=>eS(e,t).el))];return{changes:`deleted ${oS(n)} from slide ${e.slide}`,edits:wx(e.file,yx(n.map(t=>mx(e.text,t)))),touched:n.map(t=>({...aS(e,t.attrs.get(`id`)??null,!0),gone:jx(t)}))}}function _S(e,t){return e.roots.get(t.file)??e.deck}function vS(e,t,n){n.length>2e5&&J(`the pasted blocks are too long`);let r=`<x>${n}</x>`,{root:i,errors:a}=xh(r);(!i||a.length)&&J(`the pasted text is not block XML`);let o=[],s=[],c=[];for(let e of i.children){if(!q(e)){e.text.trim()&&J(`the pasted text is not block XML`);continue}Oh(e.name)||J(`<${e.name}> cannot be pasted onto a slide`),tS(t)&&![`x`,`y`,`w`].every(t=>e.attrs.has(t))&&J(`<${e.name}> needs x, y and w on the free slide ${t.slide}`);let n=$x(t),i=r.slice(e.start,e.end),a=Dx(r,e);o.push(ix(a,`id`,n)+i.slice(a.length)),s.push(aS(t,n)),c.push(e)}o.length||J(`the pasted text holds no block`);let l=Zb(t.text),u=vx(t.text,t.el,px(t.text,_S(e,t)));return{changes:`added ${oS(c)} to slide ${t.slide}`,created:s.map(e=>e.id),edits:wx(t.file,[u.edit((e,t)=>e?o.map(e=>`${t}${e}${l}`).join(``):o.join(``))]),touched:s}}function yS(e,t,n,r){let i=[...new Set(n.map(e=>eS(t,e).el))].sort((e,t)=>e.start-t.start),a=i.map(e=>nS(t,e)),o=i.map((e,n)=>{let r=mx(t.text,e),i=Dx(t.text,e);return{...r,el:ix(i,`id`,a[n])+r.el.slice(i.length)}}),s=Zb(t.text),c=cx(t.el)[0],l=r===`front`?vx(t.text,t.el,px(t.text,_S(e,t))):gx(t.text,c);return{changes:`${r===`front`?`brought`:`sent`} ${oS(i)} to the ${r} on slide ${t.slide}`,created:a,touched:a.map(e=>aS(t,e)),edits:wx(t.file,[...yx(o),l.edit((e,t)=>hx(o,e,t,s))])}}function bS(e,t){let n=t.map(t=>eS(e,t).el),r=/* @__PURE__ */ new Map,i=[];for(let t of n){if(r.has(t))continue;let n=nS(e,t);r.set(t,n),t.attrs.get(`id`)!==n&&i.push(rS(e,t,[[`id`,n]]))}return{changes:`named ${oS([...r.keys()])} on slide ${e.slide}`,created:n.map(e=>r.get(e)),edits:wx(e.file,i),touched:[]}}function xS(e,t,n){let r=ux(lx(e),t),i=fx(e,r.file);return n.map(e=>{let n=Ex(r.el,e)??J(`no block ${e} on slide ${t}`),a=mx(i,n.el);return tx(a.el,a.indent,``)})}function SS(e,t,n,r){let i=Qx(e,t,n.slide,r);switch(n.op){case`pin`:return sS(i,n.boxes);case`place`:return cS(i,n.boxes);case`unpin`:return lS(i);case`text`:return dS(i,n.block,n.xml);case`retag`:return fS(i,n.block,n.tag);case`attr`:return hS(i,n.blocks,n.name,n.value);case`remove`:return gS(i,n.blocks);case`add`:return vS(t,i,n.xml);case`order`:return yS(t,i,n.blocks,n.to);case`name`:return bS(i,n.blocks);case`wrap`:return Vx(i,n.blocks,n.tag,n.href);case`restack`:return Kx(i,n.block,n.index);case`relayout`:return Wx(e,i,n.layout)}}const CS=e=>typeof e==`string`&&e.length>0&&e.length<=200,wS=e=>e===null||CS(e),TS=e=>Array.isArray(e)&&e.length>0&&e.length<=500&&e.every(CS),ES=e=>typeof e==`string`&&e.trim().length>0&&e.length<=200,DS=e=>typeof e==`string`&&e.length>0&&e.length<=64,OS=e=>Array.isArray(e)&&e.length>0&&e.length<=500&&e.every(DS),kS=(e,t)=>typeof e==`number`&&Number.isInteger(e)&&Math.abs(e)<=4e3&&(!t||e>0);function AS(e){if(typeof e!=`object`||!e)return null;let{x:t,y:n,w:r,h:i}=e;return!kS(t,!1)||!kS(n,!1)||!kS(r,!0)?null:i===void 0?{x:t,y:n,w:r}:kS(i,!0)?{x:t,y:n,w:r,h:i}:null}function jS(e){if(!CS(e.slide))return null;let t=e.slide;switch(e.op){case`pin`:{let n=e.boxes;if(typeof n!=`object`||!n||Array.isArray(n))return null;let r=Object.entries(n);if(r.length>500)return null;let i={};for(let[e,t]of r){let n=AS(t);if(!DS(e)||!n)return null;i[e]=n}return{op:`pin`,slide:t,boxes:i}}case`place`:{if(!Array.isArray(e.boxes)||!e.boxes.length||e.boxes.length>500)return null;let n=e.boxes.map(e=>{let{block:t,box:n}=e??{},r=AS(n);return DS(t)&&r?{block:t,box:r}:null});return n.every(e=>e!==null)?{op:`place`,slide:t,boxes:n}:null}case`unpin`:return{op:`unpin`,slide:t};case`text`:return DS(e.block)&&typeof e.xml==`string`&&e.xml.length<=2e5?{op:`text`,slide:t,block:e.block,xml:e.xml}:null;case`retag`:return DS(e.block)&&typeof e.tag==`string`&&e.tag.length<=20?{op:`retag`,slide:t,block:e.block,tag:e.tag}:null;case`attr`:return OS(e.blocks)&&jh.includes(e.name)&&(e.value===null||typeof e.value==`string`&&e.value.length<=80)?{op:`attr`,slide:t,blocks:e.blocks,name:e.name,value:e.value}:null;case`restack`:return DS(e.block)&&typeof e.index==`number`&&Number.isInteger(e.index)&&e.index>=0&&e.index<=500?{op:`restack`,slide:t,block:e.block,index:e.index}:null;case`relayout`:return typeof e.layout==`string`&&zg.includes(e.layout)?{op:`relayout`,slide:t,layout:e.layout}:null;case`wrap`:{if(!OS(e.blocks)||!Fx.includes(e.tag))return null;let n=e.tag;return e.href===void 0?{op:`wrap`,slide:t,blocks:e.blocks,tag:n}:typeof e.href==`string`&&e.href.length<=2e3?{op:`wrap`,slide:t,blocks:e.blocks,tag:n,href:e.href}:null}case`remove`:return OS(e.blocks)?{op:`remove`,slide:t,blocks:e.blocks}:null;case`add`:return typeof e.xml==`string`&&e.xml.length<=2e5?{op:`add`,slide:t,xml:e.xml}:null;case`order`:return OS(e.blocks)&&(e.to===`front`||e.to===`back`)?{op:`order`,slide:t,blocks:e.blocks,to:e.to}:null;case`name`:return OS(e.blocks)?{op:`name`,slide:t,blocks:e.blocks}:null;default:return null}}function MS(e){if(typeof e!=`object`||!e)return null;let t=e;switch(t.op){case`move`:{let e=t.to;return TS(t.slides)&&e&&typeof e==`object`&&wS(e.group)&&wS(e.before)?{op:`move`,slides:t.slides,to:{group:e.group,before:e.before}}:null}case`moveGroup`:return CS(t.group)&&wS(t.before)?{op:`moveGroup`,group:t.group,before:t.before}:null;case`newGroup`:return TS(t.slides)&&ES(t.title)?{op:`newGroup`,slides:t.slides,title:t.title.trim()}:null;case`renameGroup`:return CS(t.group)&&ES(t.title)?{op:`renameGroup`,group:t.group,title:t.title.trim()}:null;case`ungroup`:case`deleteGroup`:return CS(t.group)?{op:t.op,group:t.group}:null;case`hide`:return TS(t.slides)&&typeof t.hidden==`boolean`?{op:`hide`,slides:t.slides,hidden:t.hidden}:null;case`duplicate`:case`delete`:return TS(t.slides)?{op:t.op,slides:t.slides}:null;case`insert`:return CS(t.after)?{op:`insert`,after:t.after}:null;case`paste`:return CS(t.after)&&typeof t.xml==`string`&&t.xml.length<=2e5?{op:`paste`,after:t.after,xml:t.xml}:null;case`cover`:return wS(t.slide)?{op:`cover`,slide:t.slide}:null;default:return jS(t)}}function NS(e){if(!Array.isArray(e)||e.length===0||e.length>50)return null;let t=e.map(MS);return t.every(e=>e!==null)?t:null}const PS=(e,t)=>e.slice(t.start,t.selfClosing?t.end:t.innerStart);function FS(e,t,n,r){let i=bx(t,n),a=i[0].file;i.some(e=>e.file!==a)&&J(`slides from different files move separately`),r.before&&n.includes(r.before)&&J(`cannot move ${r.before} before itself`),r.group!==null&&dx(t,r.group);let o=fx(e,a),s,c;if(a!==`deck`){if(r.before)ux(t,r.before).file!==a&&J(`${Cx(n)} can only move inside ${a}`),s=gx(o,ux(t,r.before).el),c=`before ${r.before}`;else{r.group!==i[0].group&&J(`${Cx(n)} can only move inside ${a}`);let e=t.roots.get(a);s=vx(o,e,px(o,e)),c=`to the end of ${a}`}}else if(r.before&&r.group===null&&t.groups.has(r.before))s=gx(o,t.groups.get(r.before)),c=`to the top level before group "${r.before}"`;else if(r.before){let e=ux(t,r.before);e.group!==r.group&&J(`${r.before} is not in ${r.group?`group "${r.group}"`:`the top level`}`),e.include?(t.files.get(e.file)[0]!==r.before&&J(`slides cannot go between the slides of ${e.file}`),s=gx(o,e.include)):s=gx(o,e.el),c=r.group?`into group "${r.group}" before ${r.before}`:`to the top level before ${r.before}`}else s=vx(o,r.group?dx(t,r.group):t.deck,px(o,t.deck)),c=r.group?`into group "${r.group}" at its end`:`to the end of the deck`;let l=i.map(e=>mx(o,e.el)),u=Zb(o);return{changes:`moved ${Cx(i.map(e=>e.el.attrs.get(`id`)))} ${c}`,edits:wx(a,[...yx(l),s.edit((e,t)=>hx(l,e,t,u))])}}function IS(e,t,n,r){let i=dx(t,n),a=e.deck,o;if(r===n&&J(`cannot move group "${n}" before itself`),r===null)o=vx(a,t.deck,px(a,t.deck));else if(t.groups.has(r))o=gx(a,t.groups.get(r));else{let e=ux(t,r);e.group!==null&&J(`${r} is inside a group`),e.include&&t.files.get(e.file)[0]!==r&&J(`a group cannot go between the slides of ${e.file}`),o=gx(a,e.include??e.el)}let s=[mx(a,i)],c=Zb(a);return{changes:`moved group "${n}" ${r===null?`to the end of the deck`:`before ${r}`}`,edits:wx(ox,[...yx(s),o.edit((e,t)=>hx(s,e,t,c))])}}const LS=e=>e.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`).replaceAll(/^-+|-+$/g,``).slice(0,48)||`group`;function RS(e,t,n,r){let i=bx(t,n);i.some(e=>e.file!==`deck`)&&J(`slides from an include file cannot move to a new group`);let a=e.deck,o=i[0],s=xx(t,LS(r),/* @__PURE__ */ new Set),c=ix(`<group id="${s}">`,`title`,r),l=o.group?_x(a,dx(t,o.group)):gx(a,o.el),u=i.map(e=>mx(a,e.el)),d=px(a,t.deck),f=Zb(a);return{changes:`put ${Cx(i.map(e=>e.el.attrs.get(`id`)))} in a new group "${s}"`,created:[s],edits:wx(ox,[...yx(u),l.edit((e,t)=>e?`${t}${c}${f}${hx(u,!0,t+d,f)}${t}</group>${f}`:`${c}${hx(u,!1,``,f)}</group>`)])}}function zS(e,t,n,r){let i=dx(t,n),a=PS(e.deck,i);return{changes:`renamed group "${n}" to "${r}"`,edits:wx(ox,[{start:i.start,end:i.start+a.length,text:ix(a,`title`,r)}])}}function BS(e,t,n){let r=dx(t,n),i=e.deck,a=Qb(i,r),o=cx(r),s=`ungrouped "${n}"`;if(r.selfClosing||!o.length)return{changes:s,edits:wx(ox,[{start:a.start,end:a.end,text:``}])};if(!a.own)return{changes:s,edits:wx(ox,[{start:r.start,end:r.end,text:i.slice(r.innerStart,r.innerEnd)}])};let c=Zb(i),l=i.slice(a.start,Jb(i,r.start)),u=Jb(i,r.innerEnd),d=u>r.innerStart&&/^[ \t]*$/.test(i.slice(u,r.innerEnd)),f=i.slice(r.innerStart,d?u:r.innerEnd),p=Qb(i,o[0]);return f=p.own&&f.startsWith(c)?f.slice(c.length):`${a.indent}${f.trim()}${c}`,{changes:s,edits:wx(ox,[{start:a.start,end:a.end,text:l+(p.own?tx(f,p.indent,a.indent):f)}])}}function VS(e,t,n){let r=Qb(e.deck,dx(t,n)),i=[...t.slides].filter(([,e])=>e.group===n).map(([e])=>e);return{changes:i.length?`deleted group "${n}" and slides ${Cx(i)}`:`deleted empty group "${n}"`,edits:wx(ox,[{start:r.start,end:r.end,text:``}])}}function HS(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of e)t.set(n,[...t.get(n)??[],r]);return t}function US(e,t,n,r){let i=bx(t,n);return{changes:`${r?`skipped`:`stopped skipping`} ${Cx(i.map(e=>e.el.attrs.get(`id`)))}`,edits:HS(i.map(({el:t,file:n})=>{let i=PS(fx(e,n),t);return[n,{start:t.start,end:t.start+i.length,text:ix(i,`hidden`,r?`true`:null)}]}))}}function WS(e,t){for(let n=1;;n++)if(!e.ids.has(`new-${n}`)&&!t.has(`new-${n}`))return`new-${n}`}function GS(e,t,n,r){let i=ux(t,n),a=fx(e,i.file),o=Zb(a),s=_x(a,i.el).edit((e,t)=>e?r.map(e=>tx(`${e}${o}`,``,t)).join(``):r.join(``));return[i.file,s]}function KS(e,t){let n=mx(e,t);return tx(n.el,n.indent,``)}function qS(e,t,n){let r=/* @__PURE__ */ new Set,i=[],a=[],o=bx(t,n).map(n=>{let o=n.el.attrs.get(`id`),s=xx(t,`${o}-copy`,r);return r.add(s),a.push(s),i.push(`${o} as ${s}`),GS(e,t,o,[Sx(KS(fx(e,n.file),n.el),s)])});return{changes:`duplicated ${i.join(`, `)}`,created:a,edits:HS(o)}}function JS(e,t,n){let r=WS(t,/* @__PURE__ */ new Set);return{changes:`added ${r} after ${n}`,created:[r],edits:HS([GS(e,t,n,[`<slide id="${r}"><h2>新的一页</h2></slide>`])])}}function YS(e,t,n,r){r.length>2e5&&J(`the pasted text is too long`);let i=`<slides>${r}</slides>`,{root:a,errors:o}=xh(i);(!a||o.length)&&J(`the pasted text is not slide XML`);let s=/* @__PURE__ */ new Set,c=[];for(let e of a.children){if(!q(e)){e.text.trim()&&J(`the pasted text is not slide XML`);continue}e.name!==`slide`&&J(`<${e.name}> cannot be pasted: only slides`);let n=e.attrs.get(`id`),r=n&&!t.ids.has(n)&&!s.has(n)?n:n?xx(t,`${n}-copy`,s):WS(t,s);s.add(r);let a=i.slice(e.start,e.end);c.push(r===n?a:Sx(a,r))}return c.length||J(`the pasted text holds no slide`),{changes:`pasted ${Cx([...s])} after ${n}`,created:[...s],edits:HS([GS(e,t,n,c)])}}function XS(e,t,n){let r=bx(t,n);return{changes:`deleted slides ${Cx(r.map(e=>e.el.attrs.get(`id`)))}`,edits:HS(r.map(({el:t,file:n})=>{let r=Qb(fx(e,n),t);return[n,{start:r.start,end:r.end,text:``}]}))}}function ZS(e,t,n){n!==null&&ux(t,n);let r=PS(e.deck,t.deck);return{changes:n===null?`cleared the cover`:`set the cover to ${n}`,edits:wx(ox,[{start:t.deck.start,end:t.deck.start+r.length,text:ix(r,`cover`,n)}])}}function QS(e,t,n,r){switch(n.op){case`move`:return FS(e,t,n.slides,n.to);case`moveGroup`:return IS(e,t,n.group,n.before);case`newGroup`:return RS(e,t,n.slides,n.title);case`renameGroup`:return zS(e,t,n.group,n.title);case`ungroup`:return BS(e,t,n.group);case`deleteGroup`:return VS(e,t,n.group);case`hide`:return US(e,t,n.slides,n.hidden);case`duplicate`:return qS(e,t,n.slides);case`insert`:return JS(e,t,n.after);case`paste`:return YS(e,t,n.after,n.xml);case`delete`:return XS(e,t,n.slides);case`cover`:return ZS(e,t,n.slide);default:return SS(e,t,n,r)}}function $S(e,t,n={}){let r={deck:e.deck,includes:{...e.includes}},i=[],a=[],o=/* @__PURE__ */ new Map;for(let e of t){let t=QS(r,lx(r),e,n.newId??qx);for(let e of t.touched??[])o.set(e.id===null?`${e.slide}:${o.size}`:`${e.slide}#${e.id}`,e);for(let[e,n]of t.edits){let t=nx(fx(r,e),n);r=e===`deck`?{...r,deck:t}:{...r,includes:{...r.includes,[e]:t}}}i.push(t.changes),a.push(...t.created??[])}let s=[...r.deck===e.deck?[]:[ox],...Object.keys(r.includes).filter(t=>r.includes[t]!==e.includes[t])];return{files:r,changed:s,changes:i,created:a,touched:[...o.values()]}}function eC(e,t){let n=lx(e);return bx(n,t).map(t=>KS(fx(e,t.file),t.el)).join(`
471
- `)}function tC(e,t,n,r){let i=p.default.join(e,t,n,`${r}-changes.json`),a=p.default.join(e,t,n,`${r}-seen.json`),o=()=>{try{let e=JSON.parse(d.default.readFileSync(i,`utf8`));return Array.isArray(e)?e:[]}catch{return[]}},s=()=>{try{let e=JSON.parse(d.default.readFileSync(a,`utf8`));return typeof e.seq==`number`?e.seq:0}catch{return 0}};return{read:o,seen:s,append(e){let t=o(),n=(t.at(-1)?.seq??0)+1;return U(i,[...t,{seq:n,at:Date.now(),changes:e}].slice(-500)),n},unread:()=>{let e=s();return o().filter(t=>t.seq>e).length},markSeen(e){let t=e.find(e=>e.peer===`0`)?.counter??0;U(a,{seq:Math.max(s(),t)})},since(e){let t=e?.find(e=>e.peer===`0`)?.counter??0,n=o().filter(e=>e.seq>t),i=[{peer:`0`,counter:n.at(-1)?.seq??t}];return n.length?{diff:[`--- ${r} (seen)`,`+++ ${r}`,...n.flatMap(e=>[`@@ ${new Date(e.at).toISOString()} @@`,...e.changes.map(e=>`+${e}`)])].join(`
472
- `),empty:!1,to:i}:{diff:``,empty:!0,to:i}}}}const nC=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`),rC=(e,t)=>e.lastIndexOf(`
473
- `,t-1)+1;function iC(e,t){let n=e.slice(rC(e,t),t);return/^[ \t]*$/.test(n)?n:null}function aC(e,t){let n=[],r=!1,i=null,a=!1;Qg.lastIndex=0;for(let o=Qg.exec(e);o;o=Qg.exec(e)){let[,e,,,s,c,l=``]=o;if(e||!c)continue;let u=c.toLowerCase();if(u!==`div`&&u!==`section`&&u!==`aside`)continue;if(s){let e=n.length-1;for(;e>=0&&n[e].tag!==u;)--e;if(e===-1)continue;for(let t of n.splice(e))if(t.kind===`notes`&&i?.innerEnd===void 0&&i&&(i.innerEnd=o.index,i.end=Qg.lastIndex),t.kind===`target`)return{closeStart:o.index,notes:i?.end===void 0?null:i};continue}let d=(n_(l).get(`class`)??``).split(/\s+/),f=n.at(-1)?.kind,p=`other`;u===`div`?!r&&f===`reveal`&&d.includes(`slides`)?(p=`slides`,r=!0):!r&&d.includes(`reveal`)&&(p=`reveal`):u===`section`&&f===`slides`?(a=n_(l).get(`id`)===t,p=a?`target`:`slide`):u===`aside`&&a&&i===null&&d.includes(`notes`)&&(p=`notes`,i={start:o.index,innerStart:Qg.lastIndex}),n.push({tag:u,kind:p})}return null}function oC(e,t,n){let r=aC(e,t);if(!r)return null;let i=n.trim().split(/\r?\n/).map(e=>nC(e.trim())),{notes:a,closeStart:o}=r;if(!n.trim()){if(!a)return e;let t=iC(e,a.start)!==null&&/^[ \t]*(?:\n|$)/.test(e.slice(a.end))?rC(e,a.start)-1:a.start;return e.slice(0,Math.max(t,0))+e.slice(a.end)}if(a){let t=iC(e,a.start),n=t===null?i.join(`<br>`):`\n${i.map(e=>`${t} ${e}`).join(`<br>
474
- `)}\n${t}`;return e.slice(0,a.innerStart)+n+e.slice(a.innerEnd)}let s=iC(e,o);if(s===null)return`${e.slice(0,o)}<aside class="notes">${i.join(`<br>`)}</aside>${e.slice(o)}`;let c=rC(e,o)-1,l=`\n${s} <aside class="notes">\n${i.map(e=>`${s} ${e}`).join(`<br>
475
- `)}\n${s} </aside>`;return e.slice(0,c)+l+e.slice(c)}function sC(e,t){let n=`${e}.${process.pid}.tmp`;d.default.writeFileSync(n,t),d.default.renameSync(n,e)}const cC=[`text`,`tag`,`x`,`y`,`w`,`h`,`align`,`color`],lC=(e,t)=>p.default.join(e,`slides`,t,`edit-watches.json`);function uC(e,t){try{let n=JSON.parse(d.default.readFileSync(lC(e,t),`utf8`));return Array.isArray(n)?n:[]}catch{return[]}}const dC=(e,t,n)=>U(lC(e,t),n.slice(-500)),fC=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function pC(e,t){return(t.id===null?null:Mx(e,t.slide,`#${t.id}`))??(t.path===null?null:Mx(e,t.slide,t.path))}const mC=(e,t,n)=>e.slide===t.slide&&(t.id!==null&&e.id===t.id||t.replaces!=null&&e.id===t.replaces||n!==null&&e.id===null&&e.path===n||t.gone!==void 0&&e.gone?.tag===t.gone.tag&&e.gone.text===t.gone.text);function hC(e,t,n,r,i){let a=uC(e,t);for(let e of i){if(e.id===null&&e.path===void 0&&e.gone===void 0)continue;let t=e.removed?null:e.id===null?Mx(r,e.slide,e.path):Mx(r,e.slide,`#${e.id}`),i=t?.path??e.path??null;a=a.filter(t=>!mC(t,e,e.id===null?i:null)),a.push({seq:n,slide:e.slide,id:e.id,path:e.removed?null:i,state:t?.state??null,...e.removed&&e.gone?{gone:e.gone}:{}})}dC(e,t,a)}function gC(e,t){let n=[];for(let r of/* @__PURE__ */ new Set([...Px(e),...Px(t)])){let i=Nx(e,r),a=/* @__PURE__ */ new Set;for(let e of Nx(t,r)){let t=(e.id===null?void 0:i.find(t=>t.id===e.id))??i.find(t=>t.path===e.path&&!a.has(t));t&&a.add(t),t&&fC(t.state,e.state)&&t.id===e.id||n.push({slide:r,id:e.id,path:e.path,removed:!1,replaces:t?.id??null})}for(let e of i.filter(e=>!a.has(e)))n.push({slide:r,id:e.id,removed:!0,gone:e.state})}return n}function _C(e,t){if(t.id!==null)return pC(e,t)?.state??null;let n=t.gone;return n?Nx(e,t.slide).find(e=>e.state.tag===n.tag&&e.state.text===n.text)?.state??null:null}function vC(e,t){let n={slide:e.slide,id:e.id??e.path??``};if(e.state===null){let r=_C(t,e);return r?[{...n,tag:r.tag,field:`deleted`,human:``,now:r.text}]:[]}let r=pC(t,e)?.state??null,i=e.state.tag;if(!r)return[{...n,tag:i,field:`block`,human:e.state.text,now:``}];let a=cC.filter(t=>e.state[t]!==r[t]).map(t=>({...n,tag:i,field:t,human:String(e.state[t]??``),now:String(r[t]??``)})),o=e.state.look;if(!o)return a;let s=[.../* @__PURE__ */ new Set([...Object.keys(o),...Object.keys(r.look)])];return[...a,...s.filter(e=>o[e]!==r.look[e]).map(e=>({...n,tag:i,field:e,human:o[e]??``,now:r.look[e]??``}))]}function yC(e,t,n){let r=uC(e,t).filter(n=>n.seq>wC(e,t));if(!r.length)return[];let i=NC(n);return i?r.flatMap(e=>vC(e,i)):[]}function bC({field:e,human:t,now:n,tag:r}){return e===`deleted`?`deleted a <${r}>, and the file has it again`:e===`block`?`edited <${r}> "${t}", and that block is no longer in the file`:e===`text`?`wrote "${t}" in a <${r}>; the file now says "${n}"`:`set ${e} of a <${r}> to ${t||`(none)`}; the file now has ${n||`(none)`}`}function xC(e,t,n){return yC(e,t,n).map(e=>({code:`W_HUMAN_EDIT_OVERWRITTEN`,severity:`warning`,location:e.slide,message:`Your human partner ${bC(e)}. Re-read slide ${e.slide} and keep their edit unless you mean to change it.`}))}const SC=(e,t)=>tC(e,`slides`,t,`structure`),CC=(e,t,n)=>SC(e,t).append(n),wC=(e,t)=>SC(e,t).seen(),TC=(e,t)=>SC(e,t).unread(),EC=(e,t,n)=>SC(e,t).markSeen(n),DC=(e,t,n)=>SC(e,t).since(n),OC=e=>(0,u.createHash)(`sha256`).update(e).digest(`hex`),kC=e=>{try{return d.default.readFileSync(e,`utf8`)}catch{return null}};function AC(e){let{root:t}=xh(e);if(!t)return[];let n=[],r=e=>{for(let t of e){if(!q(t))continue;t.name===`group`&&r(t.children);let e=t.name===`include`?t.attrs.get(`src`)?.trim():void 0;e&&!n.includes(e)&&n.push(e)}};return r(t.children),n}const jC=e=>e===`deck`?Ib:e;function MC(e,t){return t===`deck.xml`?p.default.join(e,Ib):ct(e,t)}function NC(e){let t=kC(p.default.join(e,Ib));return t===null?null:FC(e,t)}const PC=(e,t)=>({deck:t[`deck.xml`]??e.deck,includes:{...e.includes,...Object.fromEntries(Object.entries(t).filter(([e])=>e!==Ib))}});function FC(e,t){let n={};for(let r of AC(t)){let t=ct(e,r),i=t&&kC(t);typeof i==`string`&&(n[r]=i)}return{deck:t,includes:n}}const IC=(e,t)=>({status:e,body:{error:t}});function LC(e,{before:t,after:n},r,i,a,o=[]){for(let[t,r]of Object.entries(n))sC(MC(e,t),r);let s=CC(i,r,a),c=NC(e);return c&&o.length&&hC(i,r,s,c,o),{version:Gb(e,r).version,changes:a,undo:{files:Object.fromEntries(Object.keys(n).map(e=>[e,{before:t[e],afterHash:OC(n[e])}]))}}}const RC=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`string`);function zC(e,t,n,r,i){let a=r.restore,o=typeof r.label==`string`?r.label.slice(0,500):``;if(!a||!RC(a.files)||!RC(a.expect)||!o)return IC(400,`send {restore: {files, expect}, label}`);let s=a.files,c=a.expect,l=/* @__PURE__ */ new Set([Ib,...AC(i)]),u=Object.keys(s);if(!u.length||u.some(t=>!l.has(t)||!MC(e,t)||c[t]===void 0))return IC(400,`restore names a file that is not part of this deck`);let d={};for(let t of u){let n=kC(MC(e,t))??``;if(OC(n)!==c[t])return IC(409,`the deck changed since; it cannot be undone`);d[t]=n}let f=NC(e),p=f&&PC(f,s),m=f&&p?gC(f,p):[];return{status:200,body:LC(e,{before:d,after:s},t,n,[o],m)}}function BC(e,t,n,r){let i=Vb(e),a=kC(p.default.join(e,Ib));if(!i||i.source!==`xml`||a===null)return IC(400,`only a deck.xml deck can be restructured`);let o=typeof r==`object`&&r?r:{},s=FC(e,a);try{if(Array.isArray(o.copy))return{status:200,body:{xml:eC(s,o.copy.filter(e=>typeof e==`string`))}};if(o.restore!==void 0)return zC(e,t,n,o,a);let r=o.copyBlocks;if(r&&typeof r.slide==`string`&&Array.isArray(r.blocks)){let e=r.blocks.filter(e=>typeof e==`string`);return{status:200,body:{xml:xS(s,r.slide,e.slice(0,500))}}}let i=o.layouts;if(i&&typeof i.slide==`string`)return{status:200,body:{layouts:Ux(s,i.slide)}};let c=NS(o.ops);if(!c||typeof o.version!=`number`)return IC(400,`send {version, ops}`);let l=Gb(e,t).version;if(o.version!==l)return{status:409,body:{error:`slides/${t} has changed since you last saw it`,version:l}};let u=$S(s,c),d={},f={};for(let e of u.changed){let t=jC(e);d[t]=e===`deck`?s.deck:s.includes[e],f[t]=e===`deck`?u.files.deck:u.files.includes[e]}return{status:200,body:{...LC(e,{before:d,after:f},t,n,u.changes,u.touched),created:u.created}}}catch(e){if(e instanceof ax)return IC(400,e.message);throw e}}const VC={threads:(e,t,n)=>{let r=new Map(e.slidesComments.list(t,n,!0).map(e=>[e.id,e]));return e.slidesComments.comments(t).threads.map(e=>{let t=r.get(e.id);return{...e,...t,anchor:t&&t.number!==null?{...e.anchor,number:t.number,title:t.title}:e.anchor,messages:e.messages.map(({avatar:e,...t})=>t)}})},changes:{load:async(e,t)=>async n=>DC(p.default.join(e.root,`.state`),t,n),seen:(e,t,n)=>{EC(p.default.join(e.root,`.state`),t,n),e.writeState({type:`slides`,id:t},W(e.root,`slides`,t))}}},HC=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`),UC=(e,t)=>e.lastIndexOf(`
476
- `,t-1)+1;function WC(e,t){let n=e.slice(UC(e,t),t);return/^[ \t]*$/.test(n)?n:null}const GC=(e,t)=>`${t}<notes>\n${e.map(e=>`${t} ${e}`).join(`<br/>
477
- `)}\n${t}</notes>`;function KC(e,t,n){let{root:r,errors:i}=xh(e);if(!r||i.length>0)return null;let a=r.children.flatMap(e=>q(e)&&e.name===`group`?e.children:[e]).find(e=>q(e)&&e.name===`slide`&&e.attrs.get(`id`)===t);if(!a)return null;let o=a.children.find(e=>q(e)&&e.name===`notes`),s=n.trim().split(/\r?\n/).map(e=>HC(e.trim()));if(!n.trim()){if(!o)return e;let t=WC(e,o.start)!==null&&/^[ \t]*(?:\n|$)/.test(e.slice(o.end))?UC(e,o.start)-1:o.start;return e.slice(0,Math.max(t,0))+e.slice(o.end)}if(o){let t=WC(e,o.start),n=t===null?`<notes>${s.join(`<br/>`)}</notes>`:GC(s,t).trimStart();return e.slice(0,o.start)+n+e.slice(o.end)}if(a.selfClosing){let t=WC(e,a.start)??``,n=e.slice(a.start,a.end).replace(/\s*\/>$/,`>`);return`${e.slice(0,a.start)}${n}\n${GC(s,`${t} `)}\n${t}</slide>${e.slice(a.end)}`}let c=a.innerEnd,l=WC(e,c);if(l===null)return`${e.slice(0,c)}<notes>${s.join(`<br/>`)}</notes>${e.slice(c)}`;let u=UC(e,c)-1;return`${e.slice(0,u)}\n${GC(s,`${l} `)}${e.slice(u)}`}const qC=(e,t)=>Math.min(Math.max(e,0),t),JC=e=>typeof e==`number`&&Number.isFinite(e);function YC(e){if(!Va(e))return null;let{slide:t,x:n,y:r,text:i,path:a,nodes:o}=e;if(typeof t!=`string`||t.length===0||t.length>bg.id)return null;let s={slide:t};if(n!==void 0||r!==void 0){if(!JC(n)||!JC(r))return null;s.x=qC(n,_g.w),s.y=qC(r,_g.h)}for(let[e,t,n]of[[`text`,i,bg.text],[`path`,a,bg.path]])if(t!==void 0){if(typeof t!=`string`)return null;t&&(s[e]=t.slice(0,n))}if(o!==void 0){if(!Array.isArray(o))return null;let e=o.slice(0,20).map(XC);if(e.includes(null))return null;e.length&&(s.nodes=e)}return s}function XC(e){if(!Va(e))return null;let{block:t,tag:n,text:r}=e;return typeof t!=`string`||!t||t.length>64||typeof n!=`string`||!/^[a-z][a-z0-9]{0,15}$/.test(n)||typeof r!=`string`?null:{block:t,tag:n,text:r.slice(0,bg.text)}}const ZC={read:YC,same:(e,t)=>e.slide===t.slide&&e.x===t.x&&e.y===t.y,missing:`a new thread needs a slide anchor (the slide id); dropped it`},QC=()=>({version:1,threads:[]}),$C=e=>Ga(e,ZC),ew=(e,t,n,r,i,a)=>Za(e,t,n,r,i,a,ZC);function tw(e,t,n,r,i){return t.op===`create`?{...e,threads:[...e.threads,eo(t.anchor,`human`,t.text,n,r,i)]}:no(e,t,n,r,i)}function nw(e,t,n,r,i){if(t.op!==`add`)return uo(e,t,n,r,i);let a=eo(t.anchor,`agent`,t.text,n,r,{name:i});return{file:{...e,threads:[...e.threads,a]},threadId:a.id,messageId:a.messages[0].id}}function rw(e,t){return t?t.some(({id:t})=>t===e.slide)?null:`orphan`:null}const iw={empty:QC,saved:$C,merge:ew,human:(e,t,n,r,i)=>tw(e,t,n,r,i),agent:nw};function aw(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.op!==`create`){let t=ms(e);return t&&t.op!==`create`?t:null}let n=YC(t.anchor);return n&&fs(t.text)&&t.text.length>0?{op:`create`,anchor:n,text:t.text}:null}function ow(e){if(typeof e!=`object`||!e)return null;let t=e,n=fs(t.text)&&t.text.length>0?t.text:null;return t.op===`add`?n&&typeof t.slide==`string`&&t.slide.length>0&&t.slide.length<=200?{op:`add`,slide:t.slide,text:n}:null:typeof t.threadId!=`string`||t.threadId.length===0?null:t.op===`reply`?n?{op:`reply`,threadId:t.threadId,text:n}:null:t.op===`resolve`?{op:`resolve`,threadId:t.threadId}:null}function sw(e){let t=/* @__PURE__ */ new Map,n=$o(e.stateDir,`slides`),r=t=>Es(e.stateDir,`slides/${t}`),i=n=>{let r=t.get(n);return r||(r=vs(p.default.join(e.root,`slides`,n,`comments.json`),iw,e.names,{artifact:`slides/${n}`,savesDir:p.default.join(e.stateDir,`slides`,n,`comment-saves`)}),t.set(n,r)),r},a=t=>{let n=e.outline(t);return i(t).current().threads.filter(e=>rw(e.anchor,n)===`orphan`).map(e=>e.id)},o=t=>e.broadcast({type:`slides-comments`,artifact:`slides/${t}`,comments:i(t).current(),orphans:a(t),listening:r(t)}),s=t=>{let n=e.outline(t);return e=>{let t=n?.findIndex(t=>t.id===e.anchor.slide)??-1;return{...e,slide:e.anchor.slide,number:t===-1?null:t+1,title:t===-1?null:n[t].title,orphan:rw(e.anchor,n)===`orphan`,waitingOn:ro(e),messages:e.messages.map(({avatar:e,...t})=>t)}}};return{comments:e=>i(e).current(),listening:r,orphans:a,state:e=>({comments:i(e).current(),orphans:a(e),listening:r(e)}),warnings:e=>i(e).warnings(),apply(e,t){return i(e).apply(t),o(e),i(e).current()},applyAgent(t,n,r){let a;if(n.op===`add`){let r=e.outline(t);if(!r)throw Error(`slides/${t} has no readable deck yet: finish the deck first`);if(!r.some(e=>e.id===n.slide)){let e=r.flatMap(e=>e.id?[e.id]:[]);throw Error(`no slide ${n.slide} in slides/${t}; its slides are: ${e.join(`, `)}`)}a={op:`add`,anchor:{slide:n.slide},text:n.text}}else a=n;let{threadId:s,messageId:c}=i(t).applyAgent(a,r);return o(t),{threadId:s,...c?{messageId:c}:{}}},list(e,t,r){i(e).sync()&&o(e);let a=i(e).current(),c=s(e);if(r)return a.threads.filter(e=>!e.messages.every(e=>e.deleted)).map(c);let{threads:l,newest:u}=co(a,n.get(e,t));return u&&n.set(e,t,u),l.map(c)},sync(e){i(e).sync()&&o(e)},deckChanged(e){t.has(e)&&o(e)}}}const cw=Buffer.from([137,80,78,71,13,10,26,10]),lw=/^sheet-(\d+)\.png$/,uw=e=>e.length>cw.length&&e.subarray(0,cw.length).equals(cw);function dw(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=t=>p.default.join(e,`slides`,t),i=(e,t)=>p.default.join(r(e),`sheet-${t+1}.png`);return{of:e=>t.get(e),fail(e,r,i){n.delete(e),t.set(e,{version:r,files:[],unavailable:i})},put(e,{version:a,index:o,count:s},c){let l=n.get(e);if(l&&l.version===a&&l.count===s||(l={version:a,count:s,got:/* @__PURE__ */ new Set},n.set(e,l)),d.default.mkdirSync(r(e),{recursive:!0}),d.default.writeFileSync(i(e,o),c,{mode:384}),l.got.add(o),l.got.size<s)return!1;n.delete(e);for(let t of d.default.readdirSync(r(e)))Number(lw.exec(t)?.[1])>s&&d.default.rmSync(p.default.join(r(e),t),{force:!0});return t.set(e,{version:a,files:Array.from({length:s},(t,n)=>i(e,n))}),!0}}}const fw=/^\/api\/slides\/([^/]+)\/state$/,pw=/^\/api\/slides\/([^/]+)\/comments$/,mw=/^\/api\/slides\/([^/]+)\/notes$/,hw=/^\/api\/slides\/([^/]+)\/structure$/,gw=/^\/api\/slides\/([^/]+)\/sheet$/,_w=/^\/api\/agent\/slides\/([^/]+)\/comments$/,vw={path:fw,auth:`viewer`,handle:(e,t,n,{match:r})=>{let i=r[1];W(n.root,`slides`,i)?B(t,200,n.slidesComments.state(i)):B(t,404,{error:`slides/${i} not found`})}},yw={path:pw,methods:[`POST`],auth:`same-origin`,handle:async(e,t,n,{match:r})=>{let i=r[1];if(!W(n.root,`slides`,i)){B(t,404,{error:`slides/${i} not found`});return}let a=aw(await yc(e));if(!a)B(t,400,{error:`not a slides comment op`});else try{n.slidesComments.apply(i,a),B(t,200,n.slidesComments.state(i))}catch(e){B(t,400,{error:e.message})}}},bw={path:_w,methods:[`POST`],auth:`agent`,handle:async(e,t,n,{match:r})=>{let i=r[1];if(!W(n.root,`slides`,i)){B(t,404,{error:`slides/${i} not found`});return}let a=await yc(e),o=typeof a==`object`&&a?a:{},s=ow(o);if(!s)B(t,400,{error:`not an agent comment op: use add {slide, text}, reply {threadId, text} or resolve {threadId}; text must not be empty`});else try{B(t,200,n.slidesComments.applyAgent(i,s,bc(o)))}catch(e){B(t,400,{error:e.message})}}},xw={path:mw,methods:[`POST`],auth:`same-origin`,handle:async(e,t,n,{match:r})=>{let i=r[1],a=W(n.root,`slides`,i),o=a&&Vb(a);if(!a||!o){B(t,404,{error:`slides/${i} not found`});return}let s=await yc(e),{slide:c,notes:l}=typeof s==`object`&&s?s:{};if(typeof c!=`string`||!c||c.length>bg.id||typeof l!=`string`||l.length>bg.notes){B(t,400,{error:`send {slide, notes}: a slide id and the notes as text`});return}let u=o.source===`xml`,f=u?ct(a,o.origins.get(c)??`deck.xml`):p.default.join(a,Lb),m=f&&d.default.readFileSync(f,`utf8`),h=typeof m==`string`?(u?KC:oC)(m,c,l):null;!f||h===null?B(t,404,{error:`slides/${i} has no slide ${c}`}):(h!==m&&sC(f,h),B(t,200,{ok:!0}))}},Sw=e=>{let t=e.undo?.files;return t?Object.keys(t):[]},Cw={path:hw,methods:[`POST`],auth:`same-origin`,handle:async(e,t,n,{match:r})=>{let i=r[1],a=W(n.root,`slides`,i);if(!a){B(t,404,{error:`slides/${i} not found`});return}let o=BC(a,i,p.default.join(n.root,`.state`),await yc(e,50331648));if(o.status===200){let e=Sw(o.body);e.length>0?n.deckFiles.written(i,e):o.body.undo&&n.writeState({type:`slides`,id:i},a)}B(t,o.status,o.body)}},ww=e=>e!==null&&/^\d+$/.test(e)?Number(e):-1,Tw={relay:`deny`,path:gw,methods:[`POST`],auth:`same-origin`,handle:async(e,t,n,{match:r,url:i})=>{let a=r[1],o=W(n.root,`slides`,a);if(!o){B(t,404,{error:`slides/${a} not found`});return}let s=Number(i.searchParams.get(`version`)??NaN),c=i.searchParams.get(`failed`);if(c!==null&&Number.isFinite(s)){if(s!==Gb(o,a).version){B(t,409,{error:`slides/${a} has changed since this sheet was drawn`});return}let e=c.replaceAll(/\p{Cc}+/gu,` `).trim();n.slidesSheets.fail(a,s,e.slice(0,bg.text)||`unknown`),n.writeState({type:`slides`,id:a},o),B(t,200,{ok:!0});return}let l=ww(i.searchParams.get(`index`)),u=ww(i.searchParams.get(`count`));if(!Number.isFinite(s)||u<1||u>bg.sheets||l<0||l>=u){B(t,400,{error:`send ?version=&index=&count= with a PNG as the body`});return}let d=await vc(e,bg.sheetBytes);if(!d){B(t,413,{error:`a sheet is at most 4 MB`});return}if(!uw(d)){B(t,400,{error:`a sheet is a PNG`});return}if(s!==Gb(o,a).version){B(t,409,{error:`slides/${a} has changed since this sheet was drawn`});return}let f=n.slidesSheets.put(a,{version:s,index:l,count:u},d);f&&n.writeState({type:`slides`,id:a},o),B(t,200,{ok:!0,complete:f})}};function Ew(e,t,n,r){let i=Hb(n);e.deckDeps.track(`slides/${t}`,i.files);let a=i.title&&i.title!==t?i.title:void 0;for(let n of e.deckBacklinks.update(t,[...i.embeds,...i.refs],a)){let t=W(e.root,n.type,n.id);t&&(e.writeState(n,t),e.broadcast({type:`change`,artifact:`${n.type}/${n.id}`,files:[]}))}if(!(`outline`in r))return{extra:{}};let o=Kb(r,e.slidesReports.get(`slides/${t}`),e.slidesSheets.of(t)),s=TC(e.stateDir,t);return{extra:{ran:o.ran,diagnostics:[...o.diagnostics,...xC(e.stateDir,t,n)],sheet:o.sheet,...s?{structure:s}:{},...o.pending.length?{pending:o.pending}:{}},files:{"outline.json":o.outline}}}const Dw={read:(e,t)=>Gb(e,t),prepare:async(e,t)=>{Gb(e,t),await cl.idle()},runtimeWarning:e=>`runtime: ${e}`,threads:(e,t)=>e.slidesComments.comments(t).threads,backlinksAs:`slides`,refreshOnStart:!0,state:Ew,onFilesChanged:(e,t,n,r)=>{r.includes(`comments.json`)&&e.slidesComments.sync(t),(r.some(e=>e!==`comments.json`)||r.length===0)&&e.slidesComments.deckChanged(t)},clientMessages:{"slides-report":qb},check:{evidence:Ci},relayOps:{state:(e,t)=>e.slidesComments.state(t),comment:(e,t,n)=>(e.slidesComments.apply(t,Xi(n,aw)),e.slidesComments.state(t))},publishExtras:(e,t)=>({measured:e.slidesReports.get(`slides/${t}`)}),pull:{generated:e=>e.has(`deck.xml`)?[`index.html`]:[]},publishFiles:e=>{let t=Vb(e,void 0,{audience:!0});return t?.source===`xml`?/* @__PURE__ */ new Map([[Lb,Buffer.from(t.html)]]):void 0},publish:(e,t,n,r,{measured:i})=>({title:n,outline:Kb(r,i).outline.slides.filter(e=>!e.hidden)}),cloudPage:e=>e===`index.html`?{deckRuntimeUrl:`/_ryugi/runtime/ryugi-deck.js`}:null,review:VC,routes:[bw,vw,yw,xw,Cw,Tw],resolveFile:ct,compiledPage:(e,t,n)=>t===`index.html`?Bb(e,n===`local`,n===`cloud`):null,pageRuntime:(e,t)=>({deckRuntimeUrl:t(`ryugi-deck.js`)}),isPage:e=>e===`index.html`,keepsLocal:e=>e===wi},Ow=/^marks\/[\w-]{1,100}-1\.jpg$/,kw=e=>typeof e==`string`&&e.length>0&&e.length<=200,Aw=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0&&e<=86400,jw=e=>Math.min(Math.max(e,0),1);function Mw(e){if(!Va(e))return null;let{x:t,y:n,w:r,h:i}=e;if(![t,n,r,i].every(e=>typeof e==`number`&&Number.isFinite(e)))return null;let a=jw(t),o=jw(n),s=Math.min(jw(r),1-a),c=Math.min(jw(i),1-o);return s>0&&c>0?{x:a,y:o,w:s,h:c}:null}function Nw(e){if(!Va(e)||!kw(e.shot))return null;let t={shot:e.shot};if(e.line!==void 0){if(!kw(e.line)||e.t!==void 0||e.cut!==void 0)return null;t.line=e.line}if(e.cut!==void 0){if(!Number.isInteger(e.cut)||e.cut<1||e.t===void 0)return null;t.cut=e.cut}if(e.t!==void 0){if(!Aw(e.t))return null;t.t=Math.round(e.t*1e3)/1e3}if(e.mark!==void 0){let n=Mw(e.mark);if(!n||t.t===void 0)return null;t.mark=n}return typeof e.crop==`string`&&Ow.test(e.crop)&&(t.crop=e.crop),t}const Pw={read:Nw,same:(e,t)=>e.shot===t.shot&&e.line===t.line&&e.t===t.t&&e.cut===t.cut,missing:`a new thread needs a storyboard anchor (a shot id); dropped it`},Fw=()=>({version:1,threads:[]}),Iw=e=>Ga(e,Pw),Lw=(e,t,n,r,i,a)=>Za(e,t,n,r,i,a,Pw);function Rw(e,t,n,r,i){return t.op===`create`?{...e,threads:[...e.threads,eo(t.anchor,`human`,t.text,n,r,i)]}:no(e,t,n,r,i)}function zw(e,t,n,r,i){if(t.op!==`add`)return uo(e,t,n,r,i);let a=eo(t.anchor,`agent`,t.text,n,r,{name:i});return{file:{...e,threads:[...e.threads,a]},threadId:a.id,messageId:a.messages[0].id}}function Bw(e,t){return t?t.includes(e.shot)?null:`orphan`:null}function Vw(e,t){let n=e.shots.find(e=>t>=e.start&&t<e.end);if(n)return n.id;let r=e.shots.at(-1);return r&&t>=r.end&&t-r.end<1e-6?r.id:null}const Hw=[`x`,`y`,`scale`,`opacity`,`gain`],Uw=[`linear`,`in`,`out`,`in-out`],Ww=[`cut`,`dissolve`,`black`],Gw=[`voice`,`music`,`sfx`],Kw={min:.25,max:4},qw=.2,Jw=.4,Yw=e=>e===void 0?void 0:e.trim()===``?NaN:Number(e),Xw=e=>Math.round(e*1e3)/1e3,Zw=(e,t)=>Yw(e)??t;function Qw(e){return{prop:e.attrs.get(`prop`)??``,at:Zw(e.attrs.get(`at`),NaN),value:Zw(e.attrs.get(`value`),NaN),ease:e.attrs.get(`ease`)??`linear`,source:e.line}}function $w(e){return{id:e.attrs.get(`id`)??``,src:e.attrs.get(`src`)??``,at:Zw(e.attrs.get(`at`),0),gain:Zw(e.attrs.get(`gain`),0),fadeIn:Zw(e.attrs.get(`fade-in`),0),fadeOut:Zw(e.attrs.get(`fade-out`),0),source:e.line}}function eT(e,t){let n=Yw(e.attrs.get(`from`)),r=Yw(e.attrs.get(`to`));return{id:e.attrs.get(`id`)??``,src:e.attrs.get(`src`)??``,at:Zw(e.attrs.get(`at`),0),...n===void 0?{}:{from:n},...r===void 0?{}:{to:r},gain:Zw(e.attrs.get(`gain`),0),duck:Zw(e.attrs.get(`duck`),0),fadeIn:Zw(e.attrs.get(`fade-in`),0),fadeOut:Zw(e.attrs.get(`fade-out`),0),keys:t,source:e.line}}function tT(e){let t=Yw(e.attrs.get(`gain`));return{speed:Zw(e.attrs.get(`speed`),1),srcIn:Zw(e.attrs.get(`src-in`),0),transition:e.attrs.get(`transition`)??`cut`,transitionDur:Zw(e.attrs.get(`transition-dur`),.4),...t===void 0?{}:{gain:t}}}const nT={linear:e=>e,in:e=>e**3,out:e=>1-(1-e)**3,"in-out":e=>e<.5?4*e**3:1-(-2*e+2)**3/2};function rT(e,t,n,r){let i=e.filter(e=>e.prop===t).sort((e,t)=>e.at-t.at),a=i[0];if(!a)return r;if(n<=a.at)return a.value;for(let e=1;e<i.length;e+=1){let t=i[e];if(n>=t.at)continue;let r=i[e-1],a=t.at-r.at,o=a>0?(nT[t.ease]??nT.linear)((n-r.at)/a):1;return r.value+(t.value-r.value)*o}return i.at(-1).value}const iT=(e,t)=>Math.min(e.dur,t.dur)/2;function aT(e,t,n){let r=e.shots[n],i=e.shots[n-1],a=t.shots[n];if(!r||!i||!a||r.transition===`cut`||!Ww.includes(r.transition))return null;let o=Math.min(r.transitionDur,iT(i,r));return o>0?{kind:r.transition,start:Xw(a.start-o/2),end:Xw(a.start+o/2)}:null}function oT(e,t){return e.shots.flatMap((e,n)=>e.sfx.map(r=>({id:r.id,shot:e.id,src:r.src,start:Xw((t.shots[n]?.start??0)+r.at),gain:r.gain,fadeIn:r.fadeIn,fadeOut:r.fadeOut})))}function sT(e){return e.music.map(e=>{let t=e.from??0;return{id:e.id,src:e.src,start:e.at,from:t,...e.to===void 0?{}:{end:Xw(e.at+e.to-t)},gain:e.gain,duck:e.duck,fadeIn:e.fadeIn,fadeOut:e.fadeOut,keys:e.keys}})}function cT(e,t,n){if(n===0)return 0;let r=0;for(let n of e){let e=0;t>=n.start&&t<=n.end?e=1:t<n.start&&t>n.start-qw?e=1-(n.start-t)/qw:t>n.end&&t<n.end+Jw&&(e=1-(t-n.end)/Jw),r=Math.max(r,e)}return r===0?0:n*r}const lT=/^[a-z0-9-]+$/,uT=[`16:9`,`9:16`,`1:1`],dT=e=>e===void 0?void 0:e.trim()===``?NaN:Number(e),fT=e=>Math.round(e*1e3)/1e3;function pT(e){if(e===void 0)return;let t=/^\s*(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)\s*$/.exec(e);if(!t)return`invalid`;let n=Number(t[1]),r=Number(t[2]);return n<=r?{min:n,max:r}:`invalid`}function mT(e){let t=e.match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/gu)?.length??0,n=e.replaceAll(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/gu,` `).split(/\s+/).filter(e=>/[\p{L}\p{N}]/u.test(e)).length;return Math.max(.5,t*.25+n*.4)}function hT(e,t){let n=[],r=[],i=[],a=[];for(let o of e.children.filter(q))if(o.name===`action`)n.push(bh(o).trim());else if(o.name===`key`)i.push(Qw(o));else if(o.name===`sfx`)a.push($w(o));else if(o.name===`line`){let e=bh(o).trim();r.push({id:o.attrs.get(`id`)??``,text:e,caption:o.attrs.get(`caption`)??e,gain:dT(o.attrs.get(`gain`))??0,source:o.line,...o.attrs.has(`at`)?{at:dT(o.attrs.get(`at`))}:{}})}else t.push({name:o.name,source:o.line});let o=dT(e.attrs.get(`take-in`));return{id:e.attrs.get(`id`)??``,title:(e.attrs.get(`title`)??``).trim(),dur:dT(e.attrs.get(`dur`))??NaN,source:e.line,actions:n,lines:r,keys:i,sfx:a,...tT(e),...e.attrs.get(`src`)?{src:e.attrs.get(`src`)}:{},...e.attrs.get(`take`)?{take:e.attrs.get(`take`)}:{},...o===void 0?{}:{takeIn:o}}}function gT(e){let{root:t,errors:n}=xh(e);if(n.length||!t)return{model:null,errors:(n.length?n:[{line:1,message:`storyboard.xml is empty`}]).map(e=>({code:`E_STORYBOARD_XML`,message:e.message,location:`line ${e.line}`,severity:`error`}))};if(t.name!==`storyboard`)return{model:null,errors:[{code:`E_STORYBOARD_ROOT`,message:`the root element is <${t.name}>; it must be <storyboard>`,location:`line ${t.line}`,severity:`error`}]};let r=[],i=[],a=[],o=[];for(let e of t.children.filter(q))if(e.name===`shot`)i.push(hT(e,r));else if(e.name===`music`){let t=[];for(let n of e.children.filter(q))n.name===`key`?t.push(Qw(n)):r.push({name:n.name,source:n.line});o.push(eT(e,t))}else if(e.name===`lexicon`)for(let t of e.children.filter(q))if(t.name!==`say`)r.push({name:t.name,source:t.line});else{let e=t.attrs.get(`hint`)?.trim();a.push({word:t.attrs.get(`word`)??``,as:t.attrs.get(`as`)??``,...e?{hint:e}:{}})}else r.push({name:e.name,source:e.line});let s=pT(t.attrs.get(`target`));return{errors:[],model:{title:(t.attrs.get(`title`)??``).trim(),aspect:t.attrs.get(`aspect`)??`16:9`,lang:t.attrs.get(`lang`)??`en`,voice:t.attrs.get(`voice`)??``,...s===void 0?{}:{target:s},lexicon:a,music:o,mute:(t.attrs.get(`mute`)??``).split(/\s+/).filter(Boolean),captions:t.attrs.get(`captions`)!==`off`,shots:i,strangers:r}}}function _T(e,t){let n=[],r=[],i=0;for(let a of e.shots){let e=Number.isFinite(a.dur)&&a.dur>0?a.dur:0,o=null;for(let e of a.lines){let n=t.get(e.id),s=n??mT(e.text),c=e.at!==void 0&&Number.isFinite(e.at)?e.at:(o??0)+.3;o=c+s,r.push({id:e.id,shot:a.id,start:fT(i+c),end:fT(i+c+s),measured:n!==void 0})}n.push({id:a.id,start:fT(i),end:fT(i+e)}),i=fT(i+e)}return{shots:n,lines:r,total:i}}var vT=class extends Error{};const yT=/^(\d+)\.json$/,bT=/\.(mp4|m4v)$/i,xT=e=>Math.round(e*1e3)/1e3,ST=`cuts`,CT=e=>{let t=e;return typeof t==`object`&&!!t&&typeof t.id==`string`&&Number.isFinite(t.start)&&Number.isFinite(t.end)};function wT(e,t){if(!Number.isInteger(t)||t<1)return null;try{let n=JSON.parse(d.default.readFileSync(p.default.join(e,ST,`${t}.json`),`utf8`));return!n||typeof n.file!=`string`||!Array.isArray(n.shots)||!n.shots.every(CT)?null:{...n,n:t}}catch{return null}}function TT(e){let t;try{t=d.default.readdirSync(p.default.join(e,ST))}catch{return[]}return t.flatMap(t=>{let n=yT.exec(t),r=n?wT(e,Number(n[1])):null;return r?[r]:[]}).sort((e,t)=>e.n-t.n)}const ET=e=>TT(e).map(({n:e,file:t,hashes:n,registeredAt:r,shots:i})=>({n:e,file:t,shots:i,...r?{registeredAt:r}:{},...n?{hashes:n}:{}}));function DT(e,t){let n=e?.shots;if(!Array.isArray(n)||n.length===0)throw new vT(`a map is {"shots": [{"id", "start", "end"}, ...]} in the order they play`);let r=null,i=/* @__PURE__ */ new Set;return n.map(e=>{if(!CT(e))throw new vT(`each shot in the map needs an id, a start and an end in seconds`);let n={id:e.id,start:xT(e.start),end:xT(e.end)};if(!t.has(n.id))throw new vT(`the storyboard has no shot "${n.id}" that the map names`);if(i.has(n.id))throw new vT(`shot "${n.id}" appears twice in the map`);if(n.start<0||n.end<=n.start)throw new vT(`shot "${n.id}" ends before it starts (${n.start}s → ${n.end}s)`);if(r&&n.start<r.end-1e-6)throw new vT(`shot "${n.id}" overlaps "${r.id}" (${n.start}s is before ${r.end}s)`);return i.add(n.id),r=n,n})}function OT(e,t){if(!bT.test(t.file))throw new vT(`register the 1080p H.264 .mp4 of the cut`);if(!d.default.existsSync(t.file)||!d.default.statSync(t.file).isFile())throw new vT(`${t.file} not found`);let n=t.model??null;if(!n)try{n=gT(d.default.readFileSync(p.default.join(e,H.storyboard),`utf8`)).model}catch{n=null}if(!n)throw new vT(`${H.storyboard} does not parse; fix it before registering a cut`);let r=new Set(n.shots.map(e=>e.id)),i=t.map===void 0?_T(n,/* @__PURE__ */ new Map).shots.map(({id:e,start:t,end:n})=>({id:e,start:t,end:n})):DT(t.map,r),a=(TT(e).at(-1)?.n??0)+1,o=`${ST}/${a}.mp4`,s=p.default.join(e,o);d.default.mkdirSync(p.default.dirname(s),{recursive:!0});let c=`${s}.${process.pid}.tmp`;d.default.copyFileSync(t.file,c),d.default.renameSync(c,s);let l={version:1,n:a,file:o,source:p.default.resolve(t.file),...t.master?{master:t.master}:{},registeredAt:(t.now??(()=>/* @__PURE__ */ new Date))().toISOString(),shots:i,...t.hashes?{hashes:t.hashes}:{}},u=p.default.join(e,ST,`${a}.json`);return d.default.writeFileSync(`${u}.${process.pid}.tmp`,`${JSON.stringify(l,null,2)}\n`),d.default.renameSync(`${u}.${process.pid}.tmp`,u),{...l,mapped:t.map===void 0?`storyboard`:`map`}}const kT=/^data:image\/jpeg;base64,([A-Za-z0-9+/]+={0,2})$/,AT={empty:Fw,saved:Iw,merge:Lw,human:(e,t,n,r,i)=>Rw(e,t,n,r,i),agent:zw};function jT(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.op!==`create`){let t=ms(e);return t&&t.op!==`create`?t:null}let n=Nw(t.anchor);if(!n||!fs(t.text)||t.text.length===0)return null;let{crop:r,...i}=n;return{op:`create`,anchor:i,text:t.text,...typeof t.crop==`string`&&i.mark?{crop:t.crop}:{}}}const MT=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0,NT=e=>typeof e==`string`&&e.length>0&&e.length<=200;function PT(e){if(typeof e!=`object`||!e)return null;let t=e,n=fs(t.text)&&t.text.length>0?t.text:null;return t.op===`add`?!n||t.shot!==void 0&&!NT(t.shot)||t.line!==void 0&&!NT(t.line)||t.at!==void 0&&!MT(t.at)||t.cut!==void 0&&!(Number.isInteger(t.cut)&&t.cut>=1)||t.shot===void 0&&t.cut===void 0?null:{op:`add`,text:n,...t.shot===void 0?{}:{shot:t.shot},...t.line===void 0?{}:{line:t.line},...t.at===void 0?{}:{at:t.at},...t.cut===void 0?{}:{cut:t.cut}}:typeof t.threadId!=`string`||t.threadId.length===0?null:t.op===`reply`?n?{op:`reply`,threadId:t.threadId,text:n}:null:t.op===`resolve`?{op:`resolve`,threadId:t.threadId}:null}function FT(e){let t=/* @__PURE__ */ new Map,n=$o(e.stateDir,`storyboard`),r=t=>Es(e.stateDir,`storyboard/${t}`),i=t=>p.default.join(e.root,`storyboard`,t),a=n=>{let r=t.get(n);return r||(r=vs(p.default.join(i(n),`comments.json`),AT,e.names,{artifact:`storyboard/${n}`,savesDir:p.default.join(e.stateDir,`storyboard`,n,`comment-saves`)}),t.set(n,r)),r},o=t=>e.model(t)?.shots.map(e=>e.id)??null,s=e=>{let t=o(e);return a(e).current().threads.filter(e=>Bw(e.anchor,t)===`orphan`).map(e=>e.id)},c=e=>({comments:a(e).current(),orphans:s(e),listening:r(e)}),l=t=>e.broadcast({type:`storyboard-comments`,artifact:`storyboard/${t}`,...c(t)}),u=(e,t)=>{if(t.cut===void 0||t.t===void 0)return t;let n=wT(i(e),t.cut),r=n?Vw(n,t.t):null;return r?{...t,shot:r}:t},f=(e,t,n)=>{let r=i(e),o=kT.exec(n)?.[1];if(!o)return;let s=Buffer.from(o,`base64`);if(s.length>184320||s[0]!==255||s[1]!==216||s[2]!==255)return;let c=`marks/${t}-1.jpg`,l=p.default.join(r,c);d.default.mkdirSync(p.default.dirname(l),{recursive:!0});let u=`${l}.${process.pid}.tmp`;d.default.writeFileSync(u,s),d.default.renameSync(u,l),a(e).update(e=>({...e,threads:e.threads.map(e=>e.id===t?{...e,anchor:{...e.anchor,crop:c}}:e)}))},m=t=>{let n=e.model(t),r=i(t);return e=>{let t=n?.shots.findIndex(t=>t.id===e.anchor.shot)??-1,i=t===-1?null:n.shots[t],a=e.anchor.line?i?.lines.find(t=>t.id===e.anchor.line):void 0;return{...e,shot:e.anchor.shot,number:t===-1?null:t+1,title:i?.title??null,at:e.anchor.t??null,cut:e.anchor.cut??null,line:e.anchor.line??null,lineText:a?.text??null,orphan:Bw(e.anchor,n?n.shots.map(e=>e.id):null)===`orphan`,...e.anchor.crop?{cropPath:p.default.join(r,e.anchor.crop)}:{},waitingOn:ro(e),messages:e.messages.map(({avatar:e,...t})=>t)}}};return{comments:e=>a(e).current(),listening:r,orphans:s,state:c,warnings:e=>a(e).warnings(),apply(e,t){if(t.op!==`create`)return a(e).apply(t),l(e),c(e);let{crop:n,...r}=t,i=new Set(a(e).current().threads.map(e=>e.id));a(e).apply({...r,anchor:u(e,r.anchor)});let o=a(e).current().threads.find(e=>!i.has(e.id));return o&&n&&f(e,o.id,n),l(e),c(e)},applyAgent(t,n,r){let o;if(n.op===`add`){let r=e.model(t);if(!r)throw Error(`storyboard/${t} has no readable storyboard.xml yet: fix it first`);let a=n.shot;if(n.cut!==void 0){if(n.at===void 0)throw Error(`a comment on a cut needs --at <seconds>`);let e=wT(i(t),n.cut);if(!e)throw Error(`storyboard/${t} has no cut ${n.cut}`);if(a=Vw(e,n.at)??void 0,!a)throw Error(`cut ${n.cut} has no shot at ${n.at}s`)}let s=r.shots.find(e=>e.id===a);if(!s)throw Error(`no shot ${a} in storyboard/${t}; its shots are: ${r.shots.map(e=>e.id).join(`, `)}`);if(n.line&&!s.lines.some(e=>e.id===n.line))throw Error(`shot ${s.id} has no line ${n.line}; its lines are: ${s.lines.map(e=>e.id).join(`, `)||`none`}`);let c=Nw({shot:s.id,...n.line?{line:n.line}:{},...n.at===void 0?{}:{t:n.at},...n.cut===void 0?{}:{cut:n.cut}});if(!c)throw Error(`a comment takes --line or --at, not both`);o={op:`add`,anchor:c,text:n.text}}else o=n;let{threadId:s,messageId:c}=a(t).applyAgent(o,r);return l(t),{threadId:s,...c?{messageId:c}:{}}},list(e,t,r){a(e).sync()&&l(e);let i=a(e).current(),o=m(e);if(r)return i.threads.filter(e=>!e.messages.every(e=>e.deleted)).map(o);let{threads:s,newest:c}=co(i,n.get(e,t));return c&&n.set(e,t,c),s.map(o)},agentView:e=>m(e),sync(e){a(e).sync()&&l(e)},storyboardChanged(e){t.has(e)&&l(e)}}}var Y=class extends Error{};const IT=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`),LT=e=>IT(e).replaceAll(`"`,`&quot;`),RT=e=>`${Math.round(e*10)/10}s`;function zT(e){let{root:t,errors:n}=xh(e);if(n.length||!t||t.name!==`storyboard`)throw new Y(`storyboard.xml does not parse; fix it before editing in the page`);return{root:t,shots:t.children.filter(q).filter(e=>e.name===`shot`)}}const BT=(e,t)=>e.children.filter(q).filter(e=>e.name===t);function VT({shots:e},t){let n=e.find(e=>e.attrs.get(`id`)===t);if(!n)throw new Y(`no shot "${t}"`);return n}function HT(e,t,n,r){let i=t.selfClosing?t.end:t.innerStart,a=e.slice(t.start,i),o=RegExp(`(\\s${n}\\s*=\\s*)("[^"]*"|'[^']*')`),s=o.test(a)?a.replace(o,(e,t)=>`${t}"${LT(r)}"`):a.replace(/\s*(\/?>)$/,(e,t)=>` ${n}="${LT(r)}"${t}`);return e.slice(0,t.start)+s+e.slice(i)}function UT(e,t,n){if(!t.selfClosing)return e.slice(0,t.innerStart)+IT(n)+e.slice(t.innerEnd);let r=e.slice(t.start,t.end).replace(/\s*\/>$/,`>`);return`${e.slice(0,t.start)}${r}${IT(n)}</${t.name}>${e.slice(t.end)}`}function WT(e,t){let n=t.start;for(;n>0&&(e[n-1]===` `||e[n-1]===` `);)--n;let r=n===0||e[n-1]===`
478
- `;if(!r)return{start:t.start,end:t.end,indent:``,ownLine:r};let i=t.end;return e[i]===`\r`&&e[i+1]===`
479
- `?i+=2:e[i]===`
480
- `&&(i+=1),{start:n,end:i,indent:e.slice(n,t.start),ownLine:r}}function GT(e,t,n=1){if(n<=1&&!t.has(e))return e;for(let r=Math.max(2,n);;r+=1)if(!t.has(`${e}-${r}`))return`${e}-${r}`}const KT=e=>e.toLowerCase().normalize(`NFKD`).replaceAll(/[^a-z0-9]+/g,`-`).replaceAll(/^-+|-+$/g,``).slice(0,40).replace(/-+$/,``)||`shot`;function qT(e){let t=/* @__PURE__ */ new Set,n=e=>{let r=e.attrs.get(`id`);r&&t.add(r),e.children.filter(q).forEach(n)};return n(e),t}function JT(e){let t=e.trim();if(t.length>2e3)throw new Y(`keep it under 2000 characters`);return t}function YT(e,t,n,r){let i=r??t.shots[0];if(!i){let r=t.root.innerEnd;return`${e.slice(0,r).replace(/\s*$/,``)}\n ${n}\n${e.slice(r).replace(/^\s*/,``)}`}let a=WT(e,i);if(!a.ownLine){let t=r?i.end:i.start;return e.slice(0,t)+n+e.slice(t)}let o=r?a.end:a.start,s=r&&e[a.end-1]!==`
481
- `?`
482
- `:``;return`${e.slice(0,o)}${s}${a.indent}${n}\n${e.slice(o)}`}function XT(e,t,n){let r=t.selfClosing?t.end:t.innerStart,i=e.slice(t.start,r).replace(RegExp(`\\s+${n}\\s*=\\s*("[^"]*"|'[^']*')`),``);return e.slice(0,t.start)+i+e.slice(r)}function ZT(e,t,n,r){let i=WT(e,t).indent,a=`${i} `;if(t.selfClosing){let r=e.slice(t.start,t.end).replace(/\s*\/>$/,`>`);return`${e.slice(0,t.start)}${r}\n${a}${n}\n${i}</${t.name}>${e.slice(t.end)}`}if(r){let t=WT(e,r);return t.ownLine?`${e.slice(0,t.end)}${a}${n}\n${e.slice(t.end)}`:e.slice(0,r.end)+n+e.slice(r.end)}let o=e.slice(t.innerStart,t.innerEnd);if(!o.includes(`
483
- `)){let r=o.trim(),s=r?`\n${a}${r}`:``;return`${e.slice(0,t.innerStart)}\n${a}${n}${s}\n${i}${e.slice(t.innerEnd)}`}return`${e.slice(0,t.innerStart)}\n${a}${n}${e.slice(t.innerStart)}`}const QT=e=>Math.round(e*1e3)/1e3,$T=e=>String(QT(e)),eE=65536,tE=(e,t)=>({min:e,max:t}),nE={root:{mute:`mute`,captions:[`on`,`off`]},shot:{speed:tE(Kw.min,Kw.max),"src-in":tE(0,36e3),"take-in":tE(0,36e3),transition:Ww,"transition-dur":tE(.01,60),gain:tE(-60,24)},line:{gain:tE(-60,24),at:tE(0,3600)},music:{at:tE(0,36e3),from:tE(0,36e3),to:tE(.01,36e3),gain:tE(-60,24),duck:tE(-60,0),"fade-in":tE(0,600),"fade-out":tE(0,600)},sfx:{at:tE(0,3600),gain:tE(-60,24),"fade-in":tE(0,600),"fade-out":tE(0,600)}},rE={transition:`cut`,captions:`on`,mute:``},iE=(e,t)=>Math.abs(e-t)<1e-6,aE=e=>typeof e==`number`&&Number.isFinite(e);function oE(e,t){if(t.kind===`root`)return e.root;if(t.kind===`shot`)return VT(e,t.id);if(t.kind===`music`){let n=BT(e.root,`music`).find(e=>e.attrs.get(`id`)===t.id);if(!n)throw new Y(`no music "${t.id}"`);return n}let n=e.shots.flatMap(e=>BT(e,t.kind)).find(e=>e.attrs.get(`id`)===t.id);if(!n)throw new Y(`no ${t.kind===`sfx`?`sound effect`:`line`} "${t.id}"`);return n}function sE(e,t,n){let r=nE[e]?.[t];if(!r)throw new Y(`${t} cannot be changed on a ${e} in the page`);if(n===null)return null;if(r===`mute`){let e=String(n).split(/\s+/).filter(Boolean);if(e.some(e=>!Gw.includes(e)))throw new Y(`mute takes ${Gw.join(`, `)}`);return e.join(` `)}if(Array.isArray(r)){if(!r.includes(String(n)))throw new Y(`${t} is one of ${r.join(`, `)}`);return String(n)}let i=typeof n==`number`?n:Number(n),a=r;if(!Number.isFinite(i)||i<a.min||i>a.max)throw new Y(`${t} is a number from ${a.min} to ${a.max}`);return $T(i)}function cE(e,t){let n=oE(zT(e),t.target),r=sE(t.target.kind,t.name,t.value),i=t.target.kind===`root`?`the storyboard`:`${t.target.kind} "${t.target.id}"`;return r===null||r===rE[t.name]?{xml:XT(e,n,t.name),change:`${i}: ${t.name} back to its default`}:{xml:HT(e,n,t.name,r),change:`${i}: ${t.name} = ${r}`}}const lE=(e,t,n,r)=>`<key prop="${e}" at="${$T(t)}" value="${$T(n)}"${r&&r!==`linear`?` ease="${r}"`:``}/>`;function uE(e,t){return oE(e,t)}function dE(e,t){return t.kind===`shot`?gT(e).model?.shots.find(e=>e.id===t.id)?.dur??0:1/0}function fE(e,t){let n=uE(zT(e),t.owner),r=t.owner.kind===`music`?[`gain`]:Hw;if(!r.includes(t.prop))throw new Y(`a key animates ${r.join(`, `)}`);if(t.ease!==void 0&&!Uw.includes(t.ease))throw new Y(`ease is one of ${Uw.join(`, `)}`);if(!aE(t.at)||t.at<0||t.at>dE(e,t.owner)+1e-6)throw new Y(`a key sits inside its ${t.owner.kind}`);let i=BT(n,`key`),a=i.find(e=>e.attrs.get(`prop`)===t.prop&&iE(Number(e.attrs.get(`at`)),t.at)),o=`${t.owner.kind} "${t.owner.id}" ${t.prop} at ${$T(t.at)}s`;if(t.value===null){if(!a)throw new Y(`no key for ${o}`);let t=WT(e,a);return{xml:e.slice(0,t.start)+e.slice(t.end),change:`removed the key for ${o}`}}if(!aE(t.value))throw new Y(`a key value is a number`);if(a){let n=lE(t.prop,t.at,t.value,t.ease);return{xml:e.slice(0,a.start)+n+e.slice(a.end),change:`${o} = ${$T(t.value)}`}}let s=i.filter(e=>Number(e.attrs.get(`at`))<=t.at).at(-1)??null;return{xml:ZT(e,n,lE(t.prop,t.at,t.value,t.ease),s),change:`${o} = ${$T(t.value)}`}}function pE(e,t){let n=t.split(`/`).pop()?.replace(/\.[a-z0-9]+$/i,``)??`sound`;return GT(KT(n),qT(e.root))}function mE(e,t,n,r){let i=BT(t.root,`music`),a=r??null;if(a){let t=WT(e,a);return`${e.slice(0,t.start)}${t.indent}${n}\n${e.slice(t.start)}`}let o=i.at(-1);if(o)return ZT(e,t.root,n,o);let s=t.shots[0];if(s){let t=WT(e,s);return`${e.slice(0,t.start)}${t.indent}${n}\n${e.slice(t.start)}`}return ZT(e,t.root,n,null)}function hE(e,t){if(!/^sound\/[^/]+$/.test(t.src))throw new Y(`a sound lives directly under sound/`);if(!aE(t.at)||t.at<0)throw new Y(`a sound starts at 0 seconds or later`);let n=zT(e),r=t.id??pE(n,t.src);if(qT(n.root).has(r))throw new Y(`id "${r}" is taken`);let i=`<${t.kind} id="${r}" src="${LT(t.src)}" at="${$T(t.at)}"/>`;if(t.kind===`music`)return{xml:mE(e,n,i,null),change:`added music "${r}" at ${$T(t.at)}s`,created:r};if(!t.shot)throw new Y(`a sound effect belongs to a shot`);let a=VT(n,t.shot);return{xml:ZT(e,a,i,BT(a,`sfx`).at(-1)??BT(a,`key`).at(-1)??null),change:`added sound effect "${r}" to shot "${t.shot}"`,created:r}}function gE(e,t,n){let r=(t===`music`?BT(e.root,`music`):e.shots.flatMap(e=>BT(e,`sfx`))).find(e=>e.attrs.get(`id`)===n);if(!r)throw new Y(`no ${t===`music`?`music`:`sound effect`} "${n}"`);return r}function _E(e,t){let n=WT(e,gE(zT(e),t.kind,t.id));return{xml:e.slice(0,n.start)+e.slice(n.end),change:`removed ${t.kind===`music`?`music`:`sound effect`} "${t.id}"`}}function vE(e,t){if(t.xml.length>eE)throw new Y(`that block is too large`);let{root:n,errors:r}=xh(`<storyboard>${t.xml}</storyboard>`),i=n?.children.filter(q)??[],a=i[0];if(r.length||i.length!==1||a?.name!==t.kind)throw new Y(`send one <${t.kind}> element`);let o=zT(e),s=qT(o.root),c=[],l=e=>{let t=e.attrs.get(`id`);t&&c.push(t),e.children.filter(q).forEach(l)};if(l(a),c.some(e=>s.has(e)))throw new Y(`an id in that block is already used`);let u=t.xml.trim(),d=a.attrs.get(`id`)??``;if(t.kind===`shot`){let n=t.before===null?null:VT(o,t.before);if(n){let t=WT(e,n);return{xml:`${e.slice(0,t.start)}${t.indent}${u}\n${e.slice(t.start)}`,change:`restored shot "${d}"`,created:d}}let r=o.shots.at(-1)??null;return{xml:ZT(e,o.root,u,r),change:`restored shot "${d}"`,created:d}}if(t.kind===`music`)return{xml:mE(e,o,u,t.before===null?null:gE(o,`music`,t.before)),change:`restored music "${d}"`,created:d};if(!t.shot)throw new Y(`a sound effect belongs to a shot`);let f=VT(o,t.shot),p=t.before===null?null:gE(o,`sfx`,t.before);if(p){let t=WT(e,p);return{xml:`${e.slice(0,t.start)}${t.indent}${u}\n${e.slice(t.start)}`,change:`restored sound effect "${d}"`,created:d}}return{xml:ZT(e,f,u,BT(f,`sfx`).at(-1)??BT(f,`key`).at(-1)??null),change:`restored sound effect "${d}"`,created:d}}const yE=(e,t)=>[...t].sort((e,t)=>t.start-e.start).reduce((e,t)=>{let n=WT(e,t);return e.slice(0,n.start)+e.slice(n.end)},e);function bE(e,t,n){let r=e.slice(t.start,t.end),i=zT(`<storyboard>${r}</storyboard>`).root.children.filter(q)[0],a=HT(`<storyboard>${r}</storyboard>`,i,`at`,$T(n));return a.slice(12,a.length-13)}function xE(e,t,n){let r=gT(e).model,i=_T(r,n),a=i.shots.find(e=>e.id===t)?.start??0;return new Map(i.lines.filter(e=>e.shot===t).map(e=>[e.id,QT(e.start-a)]))}const SE=(e,t)=>gT(e).model?.shots.find(e=>e.id===t)?.keys??[];function CE(e,t,n){let r=zT(e),i=VT(r,t.shot),a=gT(e).model.shots.find(e=>e.id===t.shot),o=QT(t.at);if(!(o>1e-6&&o<a.dur-1e-6))throw new Y(`split shot "${t.shot}" between 0 and ${a.dur}s`);let s=t.id??GT(`${t.shot}-b`,qT(r.root));if(qT(r.root).has(s))throw new Y(`id "${s}" is taken`);let c=xE(e,t.shot,n),l=BT(i,`line`).filter(e=>(c.get(e.attrs.get(`id`)??``)??0)>=o-1e-6),u=BT(i,`sfx`).filter(e=>Number(e.attrs.get(`at`)??0)>=o-1e-6),d=BT(i,`key`).filter(e=>Number(e.attrs.get(`at`))>o+1e-6),f=[],p=[];for(let e of new Set(a.keys.map(e=>e.prop))){let t=rT(a.keys,e,o,0),n=a.keys.filter(t=>t.prop===e&&t.at>o+1e-6).sort((e,t)=>e.at-t.at)[0];p.push(lE(e,0,t)),n&&f.push(lE(e,o,t,n.ease))}let m=[...p,...d.map(t=>bE(e,t,Number(t.attrs.get(`at`))-o)),...u.map(t=>bE(e,t,Number(t.attrs.get(`at`)??0)-o)),...l.map(t=>bE(e,t,(c.get(t.attrs.get(`id`)??``)??0)-o))],h=[`id="${s}"`,`title="${LT(a.title)}"`,`dur="${$T(a.dur-o)}"`,...a.src?[`src="${LT(a.src)}"`,`src-in="${$T(a.srcIn+o*a.speed)}"`]:[],...a.take?[`take="${LT(a.take)}"`,`take-in="${$T((a.takeIn??0)+o*a.speed)}"`]:[],...a.speed===1?[]:[`speed="${$T(a.speed)}"`],...a.gain===void 0?[]:[`gain="${$T(a.gain)}"`]].join(` `),g=yE(e,[...d,...u,...l]);for(let e of f){let n=VT(zT(g),t.shot);g=ZT(g,n,e,BT(n,`key`).at(-1)??null)}let _=VT(zT(g),t.shot);g=HT(g,_,`dur`,$T(o));let v=VT(zT(g),t.shot),y=WT(g,v),b=y.indent,x=m.length?`<shot ${h}>\n${m.map(e=>`${b} ${e}`).join(`
484
- `)}\n${b}</shot>`:`<shot ${h}/>`;return g=y.ownLine?`${g.slice(0,y.end)}${b}${x}\n${g.slice(y.end)}`:g.slice(0,v.end)+x+g.slice(v.end),{xml:g,change:`split shot "${t.shot}" at ${$T(o)}s into "${t.shot}" and "${s}"`,created:s}}function wE(e,t,n){let r=zT(e),i=r.shots.findIndex(e=>e.attrs.get(`id`)===t.shot);if(i<0)throw new Y(`no shot "${t.shot}"`);let a=r.shots[i+1];if(!a)throw new Y(`shot "${t.shot}" is the last; nothing to join`);let o=a.attrs.get(`id`)??``,s=gT(e).model.shots[i],c=s.dur,l=xE(e,o,n),u=SE(e,o),d=s.keys,f=/* @__PURE__ */ new Set,p=[];for(let e of u.filter(e=>iE(e.at,0))){if(!iE(rT(d,e.prop,c,NaN),e.value))continue;f.add(e.prop);let t=BT(r.shots[i],`key`).find(t=>t.attrs.get(`prop`)===e.prop&&iE(Number(t.attrs.get(`at`)),c));t&&u.some(t=>t.prop===e.prop&&t.at>1e-6)&&p.push(t)}let m={key:BT(a,`key`).filter(e=>!(iE(Number(e.attrs.get(`at`)),0)&&f.has(e.attrs.get(`prop`)??``))).map(t=>bE(e,t,Number(t.attrs.get(`at`))+c)),sfx:BT(a,`sfx`).map(t=>bE(e,t,Number(t.attrs.get(`at`)??0)+c)),line:BT(a,`line`).map(t=>bE(e,t,(l.get(t.attrs.get(`id`)??``)??0)+c)),action:BT(a,`action`).map(t=>e.slice(t.start,t.end))},h=WT(e,a),g=e.slice(0,h.start)+e.slice(h.end);g=yE(g,p);for(let e of[`key`,`sfx`,`line`,`action`])for(let n of m[e]){let r=VT(zT(g),t.shot),i=BT(r,e).at(-1)??(e===`sfx`?BT(r,`key`).at(-1):null)??null;g=ZT(g,r,n,i)}let _=VT(zT(g),t.shot);return g=HT(g,_,`dur`,$T(c+Number(a.attrs.get(`dur`)??0))),{xml:g,change:`joined shot "${o}" into "${t.shot}"`}}function TE(e,t,n=/* @__PURE__ */ new Map){return t.op===`attr`?cE(e,t):t.op===`key`?fE(e,t):t.op===`add-sound`?hE(e,t):t.op===`remove`?_E(e,t):t.op===`insert`?vE(e,t):t.op===`split`?CE(e,t,n):wE(e,t,n)}const EE=e=>typeof e==`string`,DE=e=>EE(e)&&e.length>0&&e.length<=200,OE=e=>e===`music`||e===`sfx`;function kE(e){let t=e;return!t||typeof t!=`object`?null:t.kind===`root`?{kind:`root`}:(t.kind===`shot`||t.kind===`line`||t.kind===`music`||t.kind===`sfx`)&&DE(t.id)?{kind:t.kind,id:t.id}:null}function AE(e){let{op:t}=e;if(t===`attr`){let n=kE(e.target),r=e.value;return!n||!DE(e.name)||!(r===null||aE(r)||EE(r)&&r.length<=200)?null:{op:t,target:n,name:e.name,value:r}}if(t===`key`){let n=kE(e.owner);return!n||n.kind!==`shot`&&n.kind!==`music`||!DE(e.prop)||!aE(e.at)||!(e.value===null||aE(e.value))||!(e.ease===void 0||DE(e.ease))?null:{op:t,owner:{kind:n.kind,id:n.id},prop:e.prop,at:e.at,value:e.value,...e.ease?{ease:e.ease}:{}}}return t===`add-sound`?!OE(e.kind)||!DE(e.src)||!aE(e.at)||!(e.shot===void 0||DE(e.shot))||!(e.id===void 0||DE(e.id))?null:{op:t,kind:e.kind,src:e.src,at:e.at,...e.shot?{shot:e.shot}:{},...e.id?{id:e.id}:{}}:t===`remove`?OE(e.kind)&&DE(e.id)?{op:t,kind:e.kind,id:e.id}:null:t===`insert`?!(e.kind===`shot`||OE(e.kind))||!(e.before===null||DE(e.before))||!EE(e.xml)||e.xml.length>eE||!(e.shot===void 0||DE(e.shot))?null:{op:t,kind:e.kind,before:e.before,xml:e.xml,...e.shot?{shot:e.shot}:{}}:t===`split`?!DE(e.shot)||!aE(e.at)||!(e.id===void 0||DE(e.id))?null:{op:t,shot:e.shot,at:e.at,...e.id?{id:e.id}:{}}:t===`join`&&DE(e.shot)?{op:t,shot:e.shot}:null}function jE(e,t,n){let r=VT(zT(e),t);if(n===t)throw new Y(`a shot cannot move before itself`);let i=WT(e,r),a=e.slice(i.start,i.end),o=e.slice(0,i.start)+e.slice(i.end),s=zT(o),c=n===null?null:VT(s,n),l;if(c)l=WT(o,c).start;else{let e=s.shots.at(-1);l=e?WT(o,e).end:s.root.innerEnd}return{xml:o.slice(0,l)+a+o.slice(l),change:n===null?`moved shot "${t}" to the end`:`moved shot "${t}" before "${n}"`}}function ME(e,t){let n=zT(e),r=VT(n,t),i=qT(n.root),a=e.slice(r.start,r.end),o=zT(`<storyboard>${a}</storyboard>`).shots[0],s=GT(t,i,2);i.add(s);let c=[{el:o,value:s},...BT(o,`line`).map(e=>{let t=GT(e.attrs.get(`id`)??`line`,i,2);return i.add(t),{el:e,value:t}})].sort((e,t)=>t.el.start-e.el.start),l=`<storyboard>${a}</storyboard>`;for(let{el:e,value:t}of c)l=HT(l,e,`id`,t);return{xml:YT(e,n,l.slice(12,l.length-13),r),change:`duplicated shot "${t}" as "${s}"`,created:s}}function NE(e,t,n){if(t.op===`attr`||t.op===`key`||t.op===`add-sound`||t.op===`remove`||t.op===`insert`||t.op===`split`||t.op===`join`)return TE(e,t,n);if(t.op===`move`)return jE(e,t.shot,t.before);if(t.op===`duplicate`)return ME(e,t.shot);let r=zT(e);if(t.op===`line`){let n=r.shots.flatMap(e=>BT(e,`line`)).find(e=>e.attrs.get(`id`)===t.line);if(!n)throw new Y(`no line "${t.line}"`);let i=JT(t.text);if(!i)throw new Y(`a line needs words; remove it in storyboard.xml`);return{xml:UT(e,n,i),change:`line "${t.line}": "${i}" (was "${bh(n).trim()}")`}}if(t.op===`add`){let n=JT(t.title);if(!n)throw new Y(`a new shot needs a title`);let i=t.after===null?null:VT(r,t.after),a=GT(KT(n),qT(r.root));return{xml:YT(e,r,`<shot id="${a}" title="${LT(n)}" dur="3"></shot>`,i),change:`added shot "${a}" "${n}" ${t.after===null?`at the start`:`after "${t.after}"`}`,created:a}}let i=VT(r,t.shot);if(t.op===`delete`){let n=WT(e,i);return{xml:e.slice(0,n.start)+e.slice(n.end),change:`deleted shot "${t.shot}" "${i.attrs.get(`title`)??``}"`}}if(t.op===`dur`){if(!Number.isFinite(t.dur)||t.dur<=0||t.dur>3600)throw new Y(`a duration is seconds above 0 and at most 3600`);let n=Math.max(.1,Math.round(t.dur*10)/10),r=Number(i.attrs.get(`dur`));return{xml:HT(e,i,`dur`,String(n)),change:`shot "${t.shot}" now lasts ${RT(n)}${Number.isFinite(r)?` (was ${RT(r)})`:``}`}}if(t.op===`title`){let n=JT(t.text);if(!n)throw new Y(`a shot needs a title`);return{xml:HT(e,i,`title`,n),change:`shot "${t.shot}" title: "${n}" (was "${i.attrs.get(`title`)??``}")`}}if(t.insert){let n=JT(t.text);if(!n)throw new Y(`an action needs words`);let r=BT(i,`action`),a=t.index>0?r[t.index-1]??r.at(-1)??null:null;return{xml:ZT(e,i,`<action>${IT(n)}</action>`,a),change:`shot "${t.shot}": added action "${n}"`}}let a=BT(i,`action`)[t.index];if(!a)throw new Y(`shot "${t.shot}" has no action ${t.index+1}`);let o=JT(t.text),s=bh(a).trim();if(!o){let n=WT(e,a);return{xml:e.slice(0,n.start)+e.slice(n.end),change:`shot "${t.shot}": removed action "${s}"`}}return{xml:UT(e,a,o),change:`shot "${t.shot}" action ${t.index+1}: "${o}" (was "${s}")`}}const PE=e=>typeof e==`string`,FE=e=>PE(e)&&e.length>0&&e.length<=200;function IE(e){if(!Array.isArray(e)||e.length===0||e.length>50)return null;let t=[];for(let n of e){if(!n||typeof n!=`object`)return null;let{op:e}=n;if(e===`move`&&FE(n.shot)&&(n.before===null||FE(n.before)))t.push({op:e,shot:n.shot,before:n.before});else if(e===`dur`&&FE(n.shot)&&typeof n.dur==`number`)t.push({op:e,shot:n.shot,dur:n.dur});else if(e===`title`&&FE(n.shot)&&PE(n.text))t.push({op:e,shot:n.shot,text:n.text});else if(e===`action`&&FE(n.shot)&&Number.isInteger(n.index)&&PE(n.text))t.push({op:e,shot:n.shot,index:n.index,text:n.text,...n.insert===!0?{insert:!0}:{}});else if(e===`line`&&FE(n.line)&&PE(n.text))t.push({op:e,line:n.line,text:n.text});else if(e===`add`&&(n.after===null||FE(n.after))&&PE(n.title))t.push({op:e,after:n.after,title:n.title});else if((e===`duplicate`||e===`delete`)&&FE(n.shot))t.push({op:e,shot:n.shot});else{let e=AE(n);if(!e)return null;t.push(e)}}return t}const LE=(e,t)=>Math.abs(e-t)<1e-6;function RE(e,t){let n=e.findIndex(e=>e.attrs.get(`id`)===t);return n>=0?e[n+1]?.attrs.get(`id`)??null:null}function zE(e,t){let n=zT(e),r=e=>n.shots.find(t=>t.attrs.get(`id`)===e);switch(t.op){case`dur`:return[{op:`dur`,shot:t.shot,dur:Number(r(t.shot)?.attrs.get(`dur`))}];case`title`:return[{op:`title`,shot:t.shot,text:r(t.shot)?.attrs.get(`title`)??``}];case`line`:{let n=gT(e).model?.shots.flatMap(e=>e.lines).find(e=>e.id===t.line);return[{op:`line`,line:t.line,text:n?.text??``}]}case`action`:{let n=gT(e).model?.shots.find(e=>e.id===t.shot)?.actions??[];if(t.insert)return[{op:`action`,shot:t.shot,index:t.index,text:``}];let r=n[t.index]??``;return t.text.trim()?[{op:`action`,shot:t.shot,index:t.index,text:r}]:[{op:`action`,shot:t.shot,index:t.index,text:r,insert:!0}]}case`move`:return[{op:`move`,shot:t.shot,before:RE(n.shots,t.shot)}];case`add`:return[{op:`delete`,shot:GT(KT(t.title.trim()),qT(n.root))}];case`duplicate`:return[{op:`delete`,shot:GT(t.shot,qT(n.root),2)}];case`delete`:{let i=r(t.shot);return[{op:`insert`,kind:`shot`,before:RE(n.shots,t.shot),xml:e.slice(i.start,i.end)}]}case`attr`:{let e=t.target.kind===`root`?n.root:t.target.kind===`shot`?r(t.target.id):t.target.kind===`music`?BT(n.root,`music`).find(e=>e.attrs.get(`id`)===t.target.id):n.shots.flatMap(e=>BT(e,t.target.kind)).find(e=>e.attrs.get(`id`)===t.target.id);return[{op:`attr`,target:t.target,name:t.name,value:e?.attrs.get(t.name)??null}]}case`key`:{let e=t.owner.kind===`shot`?r(t.owner.id):BT(n.root,`music`).find(e=>e.attrs.get(`id`)===t.owner.id),i=e?BT(e,`key`).find(e=>e.attrs.get(`prop`)===t.prop&&LE(Number(e.attrs.get(`at`)),t.at)):void 0;return i?[{op:`key`,owner:t.owner,prop:t.prop,at:t.at,value:Number(i.attrs.get(`value`)),ease:i.attrs.get(`ease`)??`linear`}]:[{op:`key`,owner:t.owner,prop:t.prop,at:t.at,value:null}]}case`add-sound`:return[{op:`remove`,kind:t.kind,id:t.id??pE(n,t.src)}];case`remove`:{let r=gE(n,t.kind,t.id);if(t.kind===`music`)return[{op:`insert`,kind:`music`,before:RE(BT(n.root,`music`),t.id),xml:e.slice(r.start,r.end)}];let i=n.shots.find(e=>BT(e,`sfx`).includes(r));return[{op:`insert`,kind:`sfx`,shot:i.attrs.get(`id`)??``,before:RE(BT(i,`sfx`),t.id),xml:e.slice(r.start,r.end)}]}case`insert`:{let e=/\bid="([^"]+)"/.exec(t.xml)?.[1]??``;return t.kind===`shot`?[{op:`delete`,shot:e}]:[{op:`remove`,kind:t.kind,id:e}]}case`split`:return[{op:`join`,shot:t.shot}];case`join`:{let e=n.shots.findIndex(e=>e.attrs.get(`id`)===t.shot),r=n.shots[e+1];return[{op:`split`,shot:t.shot,at:Number(n.shots[e]?.attrs.get(`dur`)),id:r?.attrs.get(`id`)??void 0}]}}}const BE=`audio`,VE=`audio/manifest.json`;function HE(e){let t=[e.text,e.voice,e.lang];return e.direction&&t.push(e.direction),(0,u.createHash)(`sha256`).update(JSON.stringify(t)).digest(`hex`).slice(0,16)}const UE=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`),WE=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,GE=`[[\\p{L}\\p{N}]--[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}]]`,KE=e=>{let t=WE.test(e.at(0))?``:`(?<!${GE})`,n=WE.test(e.at(-1))?``:`(?!${GE})`;return RegExp(`${t}${UE(e)}${n}`,`gv`)};function qE(e,t){return e.lexicon.reduce((e,t)=>t.word.trim()&&t.as.trim()?e.replaceAll(KE(t.word),()=>t.as):e,t.text)}function JE(e,t){return e.lexicon.filter(e=>e.word.trim()&&e.as.trim()&&KE(e.word).test(t.text)).map(e=>{let t=`Say "${e.as}" exactly as it is spelled: it is how "${e.word}" is pronounced.`;return e.hint?`${t} ${e.hint}`:t}).join(` `)}const YE=(e,t)=>HE({text:qE(e,t),voice:e.voice,lang:e.lang,direction:JE(e,t)});function XE(e){try{let t=JSON.parse(d.default.readFileSync(p.default.join(e,VE),`utf8`));if(t&&typeof t==`object`&&t.lines&&typeof t.lines==`object`)return{version:1,lines:t.lines,cache:t.cache&&typeof t.cache==`object`?t.cache:{}}}catch{}return{version:1,lines:{},cache:{}}}function ZE(e,t){let n=XE(e),r=/* @__PURE__ */ new Map;for(let i of t.shots)for(let a of i.lines){let i=n.lines[a.id];i&&i.hash===YE(t,a)&&Number.isFinite(i.duration)&&i.duration>0&&d.default.existsSync(p.default.join(e,i.file))&&r.set(a.id,i)}return r}const QE=e=>e!==void 0&&Number.isFinite(e),$E=e=>QE(e)&&e>=0;function eD(e,t,n,r,{error:i}){let a=/* @__PURE__ */ new Set;for(let o of e){let e=e=>i(`E_STORYBOARD_KEY`,`a key on ${t} ${e}`,o.source);r.includes(o.prop)?Uw.includes(o.ease)?!$E(o.at)||n!==null&&o.at>n+1e-6?e(`is at ${o.at}s, outside 0-${n??`…`}s`):QE(o.value)?a.has(`${o.prop}@${o.at}`)&&e(`repeats ${o.prop} at ${o.at}s`):e(`needs a number value`):e(`has ease "${o.ease}"; use ${Uw.join(`, `)}`):e(`animates "${o.prop}"; use ${r.join(`, `)}`),a.add(`${o.prop}@${o.at}`)}}function tD(e,t,n){let{claim:r,error:i,warn:a}=n,o=(e,n,r)=>{t.has(e)||i(`E_STORYBOARD_MISSING_FILE`,`${n} names ${e}, which does not exist`,r)};for(let t of e.mute)Gw.includes(t)||i(`E_STORYBOARD_MUTE`,`mute names "${t}"; use ${Gw.join(`, `)}`);for(let t of e.music){r(t.id,`a music`,t.source),o(t.src,`music "${t.id}"`,t.source);let e=t.from??0;$E(t.at)&&$E(e)&&(t.to===void 0||QE(t.to)&&t.to>e)||i(`E_STORYBOARD_MUSIC`,`music "${t.id}" needs at and from of 0 or more and a to after from`,t.source),(![t.gain,t.duck,t.fadeIn,t.fadeOut].every(QE)||t.fadeIn<0||t.fadeOut<0)&&i(`E_STORYBOARD_MUSIC`,`music "${t.id}" has a gain, duck or fade that is not a number`,t.source),eD(t.keys,`music "${t.id}"`,null,[`gain`],n)}e.shots.forEach((t,s)=>{let c=`shot "${t.id}"`;if((!QE(t.speed)||t.speed<Kw.min||t.speed>Kw.max)&&i(`E_STORYBOARD_SPEED`,`${c} has speed ${t.speed}; use ${Kw.min} to ${Kw.max}`,t.source),$E(t.srcIn)||i(`E_STORYBOARD_SRC_IN`,`${c} has a src-in that is not a number of seconds from 0 up`,t.source),t.gain!==void 0&&!QE(t.gain)&&i(`E_STORYBOARD_GAIN`,`${c} has a gain that is not a number`,t.source),!Ww.includes(t.transition))i(`E_STORYBOARD_TRANSITION`,`${c} has transition "${t.transition}"; use ${Ww.join(`, `)}`,t.source);else if(t.transition!==`cut`){let n=e.shots[s-1];!QE(t.transitionDur)||t.transitionDur<=0?i(`E_STORYBOARD_TRANSITION`,`${c} needs a transition-dur above 0`,t.source):n&&Number.isFinite(n.dur)&&Number.isFinite(t.dur)&&t.transitionDur>iT(n,t)+1e-6&&i(`E_STORYBOARD_TRANSITION`,`${c} has a ${t.transitionDur}s transition, longer than half of the shorter shot beside it (${iT(n,t)}s)`,t.source)}eD(t.keys,c,Number.isFinite(t.dur)?t.dur:null,Hw,n);for(let e of t.lines)QE(e.gain)||i(`E_STORYBOARD_GAIN`,`line "${e.id}" has a gain that is not a number`,e.source);for(let e of t.sfx)r(e.id,`a sound effect`,e.source),o(e.src,`sound effect "${e.id}"`,e.source),!$E(e.at)||![e.gain,e.fadeIn,e.fadeOut].every(QE)?i(`E_STORYBOARD_SFX`,`sound effect "${e.id}" needs at from 0 up and number gain and fades`,e.source):Number.isFinite(t.dur)&&e.at>=t.dur&&a(`W_STORYBOARD_SFX_AFTER_SHOT`,`sound effect "${e.id}" starts at ${e.at}s, after ${c} ends at ${t.dur}s`,e.source)})}const nD=e=>`line ${e}`,rD=e=>String(Math.round(e*100)/100);function iD(e,t){let n=[],r=(e,t,r)=>n.push({code:e,message:t,severity:`error`,...r===void 0?{}:{location:nD(r)}});uT.includes(e.aspect)||r(`E_STORYBOARD_ASPECT`,`aspect "${e.aspect}" is not one of ${uT.join(`, `)}`),e.target===`invalid`&&r(`E_STORYBOARD_TARGET`,`target must be a range of seconds such as "65-80"`);for(let t of e.lexicon)t.word.trim()&&t.as.trim()||r(`E_STORYBOARD_LEXICON`,`each <say> in the lexicon needs both word and as`);for(let t of e.strangers)r(`E_STORYBOARD_ELEMENT`,`<${t.name}> is not part of a storyboard: use <shot>, <action>, <line>, <key>, <sfx>, <music>, <lexicon> and <say>`,t.source);e.shots.length===0&&r(`E_STORYBOARD_EMPTY`,`the storyboard has no <shot>`);let i=/* @__PURE__ */ new Set,a=(e,t,n)=>{lT.test(e)?(i.has(e)&&r(`E_STORYBOARD_DUPLICATE_ID`,`id "${e}" is used more than once; shot and line ids share one namespace`,n),i.add(e)):r(`E_STORYBOARD_ID`,`${t} id "${e}" must use lowercase letters, digits and hyphens`,n)};for(let n of e.shots){a(n.id,`a shot`,n.source),n.title||r(`E_STORYBOARD_SHOT_TITLE`,`shot "${n.id}" has no title`,n.source),(!Number.isFinite(n.dur)||n.dur<=0)&&r(`E_STORYBOARD_SHOT_DUR`,`shot "${n.id}" needs dur, a number of seconds above 0`,n.source);for(let e of[n.src,n.take])e!==void 0&&!t.files.has(e)&&r(`E_STORYBOARD_MISSING_FILE`,`shot "${n.id}" names ${e}, which does not exist`,n.source);n.takeIn!==void 0&&!(Number.isFinite(n.takeIn)&&n.takeIn>=0)&&r(`E_STORYBOARD_TAKE_IN`,`shot "${n.id}" has a take-in that is not a number of seconds from 0 up`,n.source);for(let e of n.lines)a(e.id,`a line`,e.source),e.text||r(`E_STORYBOARD_LINE_TEXT`,`line "${e.id}" has no words`,e.source),e.at!==void 0&&!(Number.isFinite(e.at)&&e.at>=0)&&r(`E_STORYBOARD_LINE_AT`,`line "${e.id}" has an at that is not a number of seconds from 0 up`,e.source)}tD(e,t.files,{claim:a,error:r,warn:(e,t,r)=>n.push({code:e,message:t,severity:`warning`,...r===void 0?{}:{location:nD(r)}})});let o=_T(e,t.audio),s=new Map(o.shots.map(e=>[e.id,e])),c=new Map(e.shots.flatMap(e=>e.lines.map(e=>[e.id,e.source]))),l=null;for(let e of o.lines){let t=s.get(e.shot);e.measured&&t&&e.end>t.end+1e-6&&r(`E_STORYBOARD_LINE_OVERRUN`,`line "${e.id}" ends ${rD(e.end-t.end)}s after shot "${e.shot}" does: lengthen the shot, move the line earlier or shorten it`,c.get(e.id)),l&&l.shot===e.shot&&l.measured&&e.measured&&e.start<l.end-1e-6&&r(`E_STORYBOARD_LINE_OVERLAP`,`line "${e.id}" starts before line "${l.id}" has finished`,c.get(e.id)),l=e}return e.target&&e.target!==`invalid`&&(o.total<e.target.min||o.total>e.target.max)&&n.push({code:`W_STORYBOARD_TARGET`,message:`the storyboard runs ${rD(o.total)}s, outside its target of ${e.target.min}-${e.target.max}s`,severity:`warning`}),{issues:n,pending:o.lines.filter(e=>!e.measured).map(e=>e.id)}}const aD={"16:9":[1920,1080],"9:16":[1080,1920],"1:1":[1080,1080]},oD=e=>aD[e]??aD[`16:9`],sD=e=>10**(e/20);function cD(e,t,n){let r=new Map(e.shots.flatMap(e=>e.lines.map(e=>[e.id,e])));return{voice:t.lines.flatMap(e=>{let t=n[e.id];return t?[{kind:`voice`,key:`voice:${e.id}`,file:t.file,start:e.start,end:e.start+t.duration,from:0,gain:r.get(e.id)?.gain??0,fadeIn:0,fadeOut:0,keys:[]}]:[]}),music:sT(e).map(e=>({kind:`music`,key:`music:${e.id}`,file:e.src,start:e.start,end:e.end??t.total,from:e.from,gain:e.gain,duck:e.duck,fadeIn:e.fadeIn,fadeOut:e.fadeOut,keys:e.keys})),sfx:oT(e,t).map(e=>({kind:`sfx`,key:`sfx:${e.id}`,file:e.src,start:e.start,end:t.total,from:0,gain:e.gain,fadeIn:e.fadeIn,fadeOut:e.fadeOut,keys:[]})),takes:e.shots.flatMap((e,n)=>e.take&&e.gain!==void 0?[{kind:`take`,key:`take:${e.id}`,file:e.take,start:t.shots[n]?.start??0,end:t.shots[n]?.end??0,from:e.takeIn??0,speed:e.speed,gain:e.gain,fadeIn:0,fadeOut:0,keys:e.keys.filter(e=>e.prop===`gain`)}]:[]),mute:e.mute,total:t.total}}function lD(e,t){let n=1;return e.fadeIn>0&&t<e.start+e.fadeIn&&(n=Math.min(n,(t-e.start)/e.fadeIn)),e.fadeOut>0&&t>e.end-e.fadeOut&&(n=Math.min(n,(e.end-t)/e.fadeOut)),Math.max(0,n)}function uD(e,t,n){if(n<e.start||n>=e.end||e.kind!==`take`&&t.mute.includes(e.kind))return 0;let r=n-e.start,i=rT(e.keys,`gain`,r,e.gain);return e.kind===`music`&&e.duck&&(i+=cT(t.voice,n,e.duck)),sD(i)*lD(e,n)}const dD=.05,fD=/\b(?:src|href)\s*=\s*["']([^"'#?]+)/g,pD=(e,t)=>e===`source`?void 0:t,mD=e=>(0,u.createHash)(`sha256`).update(JSON.stringify(e,pD)).digest(`hex`).slice(0,16),hD=e=>e.map(({prop:e,at:t,value:n,ease:r})=>({prop:e,at:t,value:n,ease:r}));function gD(e){try{let t=d.default.statSync(e);return[t.size,t.mtimeMs]}catch{return null}}function _D(e,t){let n=p.default.join(e,t),r;try{r=d.default.readFileSync(n,`utf8`)}catch{return[t,null]}let i=[...new Set([...r.matchAll(fD)].map(e=>e[1]))].filter(e=>!/^[a-z]+:/i.test(e)&&!e.startsWith(`/`)).sort().map(e=>[e,gD(p.default.resolve(p.default.dirname(n),e))]);return[t,r,i]}function vD(e,t){return Object.fromEntries(t.shots.map(n=>[n.id,mD([n,t.aspect,30,n.src?_D(e,n.src):null,n.take?[n.take,gD(p.default.join(e,n.take))]:null])]))}function yD(e,t){let n=Math.min(e.end,t.total),r=[];for(let i=e.start;i<n+dD/2;i+=dD){let a=Math.min(i,n),o=Math.min(a,n-1e-6);r.push([Math.round(a*1e3)/1e3,Math.round(uD(e,t,o)*1e4)/1e4])}return r.filter((e,t)=>t===0||t===r.length-1||e[1]!==r[t-1][1]||e[1]!==r[t+1][1])}const bD=(e,t)=>({file:e.file,start:e.start,end:e.end,from:e.from,gain:e.gain,fadeIn:e.fadeIn,fadeOut:e.fadeOut,keys:hD(e.keys),...e.duck===void 0?{}:{duck:e.duck},...e.speed!==void 0&&e.speed!==1?{speed:e.speed}:{},envelope:yD(e,t)});function xD({audio:e,cache:t,dir:n,hashes:r,model:i,n:a,out:o,renderUrl:s}){let c=_T(i,new Map(Object.entries(e).map(([e,t])=>[e,t.duration]))),l=cD(i,c,e),u=r??vD(n,i),[d,f]=oD(i.aspect),m=i.shots.map((e,t)=>aT(i,c,t));return{version:1,n:a,aspect:i.aspect,width:d,height:f,fps:30,duration:c.total,dir:p.default.resolve(n),captions:i.captions,mute:i.mute,renderUrl:s,out:o,cache:t,shots:i.shots.map((e,t)=>{let n=c.shots[t],r=m[t],a=m[t+1];return{id:e.id,title:e.title,start:n.start,dur:Math.round((n.end-n.start)*1e3)/1e3,hash:u[e.id],segment:mD([u[e.id],r?[r,u[i.shots[t-1].id]]:null,a?[a,u[i.shots[t+1].id]]:null,i.captions,d,f]),picture:e.take?{kind:`take`,file:e.take,in:e.takeIn??0}:e.src?{kind:`page`,file:e.src,in:e.srcIn}:{kind:`card`},speed:e.speed,transition:r?{kind:r.kind,dur:Math.round((r.end-r.start)*1e3)/1e3}:null,keys:hD(e.keys)}}),audio:{voice:l.voice.map(e=>bD(e,l)),music:l.music.map(e=>bD(e,l)),sfx:l.sfx.map(e=>bD(e,l)),takes:l.takes.map(e=>bD(e,l))}}}const SD=/<!--[\s\S]*?-->|<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi,CD=/<sb-(cursor|type|clip)\b([^>]*)>/g,wD=/\s([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,TD=/@(\d+(?:\.\d+)?)/g,ED=e=>String(Math.round(e*1e3)/1e3),DD=e=>e.replaceAll(/[^\n]/g,` `);function OD(e){let t=e.replaceAll(SD,DD);return[...t.matchAll(CD)].map(n=>{let r=n[1],i=n.index+4+r.length,a=/* @__PURE__ */ new Map;for(let e of n[2].matchAll(wD)){let t=e[2]??e[3]??``,n=i+e.index+e[0].length-1;a.set(e[1],{value:t,start:n-t.length,end:n})}let o=n.index+n[0].length,s=r===`type`?t.indexOf(`</sb-type>`,o):-1;return{kind:r,attrs:a,nameEnd:i,text:s>=0?e.slice(o,s).replaceAll(/<[^>]*>/g,``):``}})}const kD=(e,t,n)=>{let r=e.attrs.get(t)?.value,i=Number(r);return r!==void 0&&r.trim()!==``&&Number.isFinite(i)?i:n},AD=e=>[...e.matchAll(TD)].map(e=>Number(e[1]));function jD(e){if(e.kind===`cursor`){let t=AD(e.attrs.get(`path`)?.value??``);return t.length?{start:Math.min(...t),end:Math.max(...t)}:{start:0,end:0}}let t=kD(e,`at`,0);if(e.kind===`type`)return{start:t,end:t+Array.from(e.text).length/kD(e,`cps`,20)};let n=kD(e,`to`,NaN);return{start:t,end:Number.isFinite(n)?t+n-kD(e,`from`,0):null}}const MD=e=>OD(e).map((e,t)=>({index:t,kind:e.kind,...jD(e)}));function ND(e,t,n){let r=OD(e)[t];if(!r)throw Error(`no overlay ${t} on this page`);let i=Math.max(n,-jD(r).start);if(r.kind===`cursor`){let t=r.attrs.get(`path`);if(!t)return e;let n=t.value.replaceAll(TD,(e,t)=>`@${ED(Number(t)+i)}`);return e.slice(0,t.start)+n+e.slice(t.end)}let a=r.attrs.get(`at`),o=ED(kD(r,`at`,0)+i);return a?e.slice(0,a.start)+o+e.slice(a.end):`${e.slice(0,r.nameEnd)} at="${o}"${e.slice(r.nameEnd)}`}const PD=/^shots\/(?!.*\.\.)[\w./-]+\.html$/,FD=/\b(setTimeout|setInterval|requestAnimationFrame)\s*\(/g,ID=/\binfinite\b|iterations\s*:\s*Infinity/i,LD=/<!--[\s\S]*?-->/g,RD=/<(script|style)\b[^>]*>([\s\S]*?)<\/\1>|\sstyle\s*=\s*("[^"]*"|'[^']*')/gi,zD=e=>[...e.replaceAll(LD,``).matchAll(RD)].map(e=>e[2]??e[3]??``).join(`
485
- `),BD=e=>PD.test(e),VD=e=>(0,u.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16),HD=e=>e&&!e.take&&e.src&&BD(e.src)?e.src:null;function UD(e,t){let n=/* @__PURE__ */ new Map,r={};for(let i of t.shots){let t=HD(i);if(!t)continue;if(!n.has(t))try{let r=d.default.readFileSync(p.default.join(e,t),`utf8`);n.set(t,{hash:VD(r),items:MD(r)})}catch{n.set(t,null)}let a=n.get(t);a&&(r[i.id]=a)}return r}const WD=e=>[...new Set(e.shots.flatMap(e=>e.src&&BD(e.src)?[e.src]:[]))];function GD(e){try{let{model:t}=gT(d.default.readFileSync(p.default.join(e,H.storyboard),`utf8`));return t?WD(t):[]}catch{return null}}function KD(e,t){return WD(t).flatMap(t=>{let n;try{n=zD(d.default.readFileSync(p.default.join(e,t),`utf8`))}catch{return[]}return[...[...new Set([...n.matchAll(FD)].map(e=>e[1]))].map(e=>`${t} uses ${e}: move it with CSS animations or Web Animations so the player can seek it`),...ID.test(n)?[`${t} has an animation that repeats forever: give it an iteration count so the shot looks the same at every play`]:[]]})}const qD=`sound`,JD=/^([a-z0-9_-][a-z0-9._-]*?)(\.(?:mp3|wav|m4a|ogg))$/;function YD(e){let t=p.default.posix.basename(e.replaceAll(`\\`,`/`)).toLowerCase(),n=t.replaceAll(/[^a-z0-9._-]+/g,`-`).replace(/^[.-]+/,``);if(JD.test(n))return n;let r=/\.(?:mp3|wav|m4a|ogg)$/.exec(t)?.[0];return r&&/^[^a-z0-9]*$/.test(t.slice(0,-r.length))?`sound${r}`:null}function XD(e,t,n){let[,r,i]=JD.exec(t),a=p.default.join(e,qD);d.default.mkdirSync(a,{recursive:!0});for(let e=1;;e+=1){let o=e===1?t:`${r}-${e}${i}`;try{return d.default.writeFileSync(p.default.join(a,o),n,{flag:`wx`}),`${qD}/${o}`}catch(e){if(e.code!==`EEXIST`)throw e}}}function ZD(e){let t;try{t=d.default.readdirSync(p.default.join(e,qD))}catch{return[]}return t.filter(e=>JD.test(e)).sort().flatMap(t=>{try{let n=d.default.statSync(p.default.join(e,qD,t));return n.isFile()?[{file:`${qD}/${t}`,bytes:n.size}]:[]}catch{return[]}})}const QD=/* @__PURE__ */ new Set([`.state`,`node_modules`,`.git`]);function $D(e,t=``){let n;try{n=d.default.readdirSync(p.default.join(e,t),{withFileTypes:!0})}catch{return[]}return n.flatMap(n=>{if(n.name.startsWith(`.`)||QD.has(n.name))return[];let r=t?`${t}/${n.name}`:n.name;return n.isDirectory()?$D(e,r):n.isFile()?[r]:[]})}const eO=e=>e.location?`${e.message} (${e.location})`:e.message;function tO(e,t,n){let r=ir(e,`comments.json`),i;try{i=n??d.default.readFileSync(p.default.join(e,H.storyboard),`utf8`)}catch{return{title:t,warnings:[`${H.storyboard} not found`],version:r,hash:``,storyboard:null,timeline:null,audio:{},cuts:ET(e),voicePending:[]}}let{model:a,errors:o}=gT(i);if(!a)return{title:t,warnings:o.map(eO),blockers:o.map(eO),version:r,hash:VD(i),storyboard:null,timeline:null,audio:{},cuts:ET(e),voicePending:[]};let s=ZE(e,a),c=new Map([...s].map(([e,t])=>[e,t.duration])),{issues:l,pending:u}=iD(a,{files:new Set($D(e)),audio:c}),f=new Set(a.shots.flatMap(e=>e.take?[e.take]:[]));return{title:a.title||t,warnings:[...l.map(eO),...KD(e,a)],blockers:l.filter(e=>e.severity===`error`&&!(e.code===`E_STORYBOARD_MISSING_FILE`&&[...f].some(t=>e.message.includes(t)))).map(eO),version:r,hash:VD(i),storyboard:a,timeline:_T(a,c),overlays:UD(e,a),shotHashes:vD(e,a),sounds:ZD(e),audio:Object.fromEntries([...s].map(([e,t])=>[e,{file:t.file,duration:t.duration}])),cuts:ET(e),voicePending:u}}const nO=(e,t)=>tC(e,`storyboard`,t,`edit`);function rO(e,t){let{model:n}=gT(t);return n?new Map([...ZE(e,n)].map(([e,t])=>[e,t.duration])):/* @__PURE__ */ new Map}function iO(e,t,n,r){let i=typeof r==`object`&&r?r:{},a=IE(i.ops);if(!a||typeof i.hash!=`string`)return{status:400,body:{error:`send {hash, ops}`}};let o=p.default.join(e,H.storyboard),s;try{s=d.default.readFileSync(o,`utf8`)}catch{return{status:404,body:{error:`storyboard/${t} has no ${H.storyboard}`}}}let c=VD(s);if(i.hash!==c)return{status:409,body:{error:`storyboard/${t} changed since you last saw it`,hash:c}};let l=[],u=[],f=[],m=s;try{for(let t of a){let n=NE(m,t,rO(e,m));f.unshift(...zE(m,t)),m=n.xml,l.push(n.change),n.created&&u.push(n.created)}}catch(e){if(e instanceof Y)return{status:400,body:{error:e.message}};throw e}let h=`${o}.${process.pid}.${Date.now()}.tmp`;return d.default.writeFileSync(h,m),d.default.renameSync(h,o),nO(n,t).append(l),{status:200,body:{hash:VD(m),changes:l,created:u,undo:f}}}const aO=[`B`,`KB`,`MB`,`GB`];function oO(e){let t=e,n=0;for(;t>=1024&&n<aO.length-1;)t/=1024,n++;return`${n===0?t:Number(t.toFixed(1))} ${aO[n]}`}function sO(e){try{return gT(d.default.readFileSync(p.default.join(e,H.storyboard),`utf8`)).model}catch{return null}}function cO(e){let t=$D(e),n=sO(e),r=n?ZE(e,n):/* @__PURE__ */ new Map,i=new Set([...r.values()].map(e=>e.file)),a=TT(e).at(-1)??null,o=a?`cuts/${a.n}.json`:null,s=a&&o?[a.file,o]:[],c=/* @__PURE__ */ new Map;for(let e of t)e.startsWith(`audio/`)&&e!==`audio/manifest.json`&&!i.has(e)&&c.set(e,null),e.startsWith(`cuts/`)&&!s.includes(e)&&c.set(e,null);if(t.includes(`audio/manifest.json`)&&c.set(VE,Buffer.from(JSON.stringify({version:1,lines:Object.fromEntries(r)},null,2))),a&&o){let{source:e,master:t,...n}=a;c.set(o,Buffer.from(JSON.stringify(n,null,2)))}return{cut:a?{n:a.n,bytes:d.default.statSync(p.default.join(e,a.file)).size,paths:s}:null,notes:[],overrides:c,uncounted:new Set(a?[a.file]:[])}}function lO(e,t){let{cut:n}=e;if(!n||n.bytes<=t)return e;let r=new Map(e.overrides);for(let e of n.paths)r.set(e,null);return{cut:null,notes:[...e.notes,`cut ${n.n} is ${oO(n.bytes)}, ${oO(n.bytes-t)} over your plan's ${oO(t)} cut allowance, so it was not published; the rest of the storyboard was`],overrides:r,uncounted:/* @__PURE__ */ new Set}}const uO=`audio/manifest.json`;function dO(e,t){let n=t.get(uO);if(!n)return t;let r;try{r=JSON.parse(d.default.readFileSync(p.default.join(e,uO),`utf8`)).cache}catch{return t}if(!r||typeof r!=`object`)return t;let i=JSON.parse(n.toString(`utf8`));return new Map(t).set(uO,Buffer.from(JSON.stringify({...i,cache:r},null,2)))}const fO={threads:(e,t)=>{let n=e.storyboardComments.agentView(t);return e.storyboardComments.comments(t).threads.map(e=>{let t=n(e);return{...e,...t,anchor:{...e.anchor,...t.title===null?{deleted:!0}:{title:t.title,number:t.number},...t.lineText===null?{}:{lineText:t.lineText},...t.cropPath?{cropPath:t.cropPath}:{}},messages:t.messages}})},changes:{load:async(e,t)=>async n=>nO(p.default.join(e.root,`.state`),t).since(n),seen:(e,t,n)=>{nO(p.default.join(e.root,`.state`),t).markSeen(n),e.writeState({type:`storyboard`,id:t},W(e.root,`storyboard`,t))}}},pO=e=>({status:400,body:{error:e}});function mO(e,t,n,r){let{shot:i,hash:a,index:o,delta:s}=typeof r==`object`&&r?r:{};if(typeof i!=`string`||typeof a!=`string`)return pO(`send {shot, hash, index, delta}`);if(typeof o!=`number`||!Number.isInteger(o)||o<0)return pO(`index must be a whole number from 0`);if(typeof s!=`number`||!Number.isFinite(s)||Math.abs(s)>3600)return pO(`delta must be a number of seconds`);let c;try{c=d.default.readFileSync(p.default.join(e,H.storyboard),`utf8`)}catch{return{status:404,body:{error:`${H.storyboard} not found`}}}let l=HD(gT(c).model?.shots.find(e=>e.id===i));if(!l)return pO(`shot ${i} does not show a page with overlays`);let u=p.default.join(e,l),f;try{f=d.default.readFileSync(u,`utf8`)}catch{return pO(`${l} not found`)}if(VD(f)!==a)return{status:409,body:{error:`${l} changed`,hash:VD(f)}};let m;try{m=ND(f,o,s)}catch(e){return pO(e.message)}let h=MD(f)[o],g=MD(m)[o],_=g.start-h.start,v=`${u}.${process.pid}.${Date.now()}.tmp`;d.default.writeFileSync(v,m),d.default.renameSync(v,u);let y=e=>`${Math.round(e*1e3)/1e3}s`;return nO(n,t).append([`moved the ${h.kind} overlay in shot "${i}" (${l}) from ${y(h.start)} to ${y(g.start)}`]),{status:200,body:{hash:VD(m),applied:Math.round(_*1e3)/1e3}}}const hO=/^\/api\/storyboard\/([^/]+)\/voice$/,gO=/^\/api\/storyboard\/([^/]+)\/cut$/,_O=/^\/api\/storyboard\/([^/]+)\/state$/,vO=/^\/api\/storyboard\/([^/]+)\/comments$/,yO=/^\/api\/agent\/storyboard\/([^/]+)\/comments$/,bO=/^\/api\/storyboard\/([^/]+)\/edit$/,xO=/^\/api\/storyboard\/([^/]+)\/overlay$/,SO=/^\/api\/storyboard\/([^/]+)\/sound$/,CO=/^\/api\/storyboard\/([^/]+)\/export$/,wO=/^\/api\/storyboard\/([^/]+)\/export\/snapshot$/,TO=262144,EO=/^(?:127\.\d+\.\d+\.\d+|::1|::ffff:127\.\d+\.\d+\.\d+)$/,DO=e=>Yp(e)||EO.test(e.socket.remoteAddress??``),OO={relay:`background`,path:hO,auth:`viewer`,methods:[`POST`],handle:async(e,t,n,{match:r})=>{if(!DO(e)){B(t,403,{error:`voices are only made from this machine`});return}let i=r[1],a=W(n.root,`storyboard`,i);if(!a){B(t,404,{error:`storyboard/${i} not found`});return}let o=await yc(e),s=typeof o==`object`&&o?o:{},c=await n.voiceRunner.synthesize(a,`storyboard/${i}`,{...typeof s.line==`string`?{line:s.line}:{},force:s.force===!0});B(t,c.error?409:200,c)}},kO={path:bO,methods:[`POST`],auth:`same-origin`,handle:async(e,t,n,{match:r})=>{let i=r[1],a=W(n.root,`storyboard`,i);if(!a){B(t,404,{error:`storyboard/${i} not found`});return}let o=iO(a,i,p.default.join(n.root,`.state`),await yc(e,TO));o.status===200&&n.writeState({type:`storyboard`,id:i},a),B(t,o.status,o.body)}},AO={path:xO,methods:[`POST`],auth:`same-origin`,handle:async(e,t,n,{match:r})=>{let i=r[1],a=W(n.root,`storyboard`,i);if(!a){B(t,404,{error:`storyboard/${i} not found`});return}let o=mO(a,i,p.default.join(n.root,`.state`),await yc(e,TO));o.status===200&&n.writeState({type:`storyboard`,id:i},a),B(t,o.status,o.body)}},jO={relay:`deny`,path:SO,methods:[`POST`],auth:`same-origin`,handle:async(e,t,n,{match:r,url:i})=>{if(!DO(e)){B(t,403,{error:`sounds are only added from this machine`});return}let a=r[1],o=W(n.root,`storyboard`,a);if(!o){B(t,404,{error:`storyboard/${a} not found`});return}let s=YD(i.searchParams.get(`name`)??``);if(!s){B(t,400,{error:`send ?name= with an mp3, wav, m4a or ogg file name`});return}let c=Number(e.headers[`content-length`]??0)>52428800?null:await vc(e,52428800);if(!c){B(t,413,{error:`a sound file is at most 50 MB`});return}let l=XD(o,s,c);n.writeState({type:`storyboard`,id:a},o),B(t,200,{file:l})}},MO={path:CO,auth:`viewer`,methods:[`GET`,`POST`,`DELETE`],handle:(e,t,n,{match:r})=>{if(!DO(e)){B(t,403,{error:`exports only run from this machine`});return}let i=r[1],a=`storyboard/${i}`,o=W(n.root,`storyboard`,i);if(!o){B(t,404,{error:`${a} not found`});return}if(e.method===`DELETE`){B(t,n.exportRunner.cancel(a)?200:409,n.exportRunner.status(a)??{});return}if(e.method===`GET`){B(t,200,n.exportRunner.status(a)??{});return}let s=n.exportRunner.start(o,a);s.ok?B(t,202,n.exportRunner.status(a)):B(t,s.status,{error:s.error})}},NO={relay:`deny`,path:wO,auth:`viewer`,handle:(e,t,n,{match:r})=>{if(!DO(e)){B(t,403,{error:`exports only run from this machine`});return}let i=r[1],a=W(n.root,`storyboard`,i),o=a?n.exportRunner.snapshot(`storyboard/${i}`):null;!a||!o?B(t,404,{error:`no export of storyboard/${i} is running`}):B(t,200,{...o,contentBase:`${n.contentPrefix}storyboard/${i}/`})}},PO={path:_O,auth:`viewer`,handle:(e,t,n,{match:r})=>{let i=r[1];W(n.root,`storyboard`,i)?B(t,200,n.storyboardComments.state(i)):B(t,404,{error:`storyboard/${i} not found`})}},FO={path:vO,methods:[`POST`],auth:`same-origin`,handle:async(e,t,n,{match:r})=>{let i=r[1];if(!W(n.root,`storyboard`,i)){B(t,404,{error:`storyboard/${i} not found`});return}let a=jT(await yc(e,524288));if(!a)B(t,400,{error:`not a storyboard comment op`});else try{B(t,200,n.storyboardComments.apply(i,a))}catch(e){B(t,400,{error:e.message})}}},IO={path:yO,methods:[`POST`],auth:`agent`,handle:async(e,t,n,{match:r})=>{let i=r[1];if(!W(n.root,`storyboard`,i)){B(t,404,{error:`storyboard/${i} not found`});return}let a=await yc(e),o=typeof a==`object`&&a?a:{},s=bc(o);if(o.op===`list`){B(t,200,{type:`comments`,artifact:`storyboard/${i}`,threads:n.storyboardComments.list(i,s??`Agent`,o.all===!0)});return}let c=PT(o);if(!c)B(t,400,{error:`not an agent comment op: use list, add {shot, line? | at?} or {cut, at}, reply {threadId, text} or resolve {threadId}; text must not be empty`});else try{B(t,200,n.storyboardComments.applyAgent(i,c,s))}catch(e){B(t,400,{error:e.message})}}},LO={relay:`deny`,path:gO,auth:`viewer`,methods:[`POST`],handle:async(e,t,n,{match:r})=>{if(!DO(e)){B(t,403,{error:`cuts are only registered from this machine`});return}let i=r[1],a=W(n.root,`storyboard`,i);if(!a){B(t,404,{error:`storyboard/${i} not found`});return}let o=await yc(e,TO),s=typeof o==`object`&&o?o:{};if(typeof s.file!=`string`||!p.default.isAbsolute(s.file))B(t,400,{error:`send {file, map?, master?} with an absolute file path`});else try{let e=OT(a,{file:s.file,...s.map===void 0?{}:{map:s.map},...typeof s.master==`string`?{master:s.master}:{}});n.writeState({type:`storyboard`,id:i},a),B(t,200,e)}catch(e){if(e instanceof vT)B(t,400,{error:e.message});else throw e}}},RO=/^(?:takes|voice|render|marks)\//,zO={read:(e,t)=>tO(e,t),runtimeWarnings:(e,t,n)=>e.shotRuns.state(t,n).warnings,threads:(e,t)=>e.storyboardComments.comments(t).threads,meta:(e,t)=>({voiceFailures:e.voiceRunner.failures(`storyboard/${t}`),export:e.exportRunner.status(`storyboard/${t}`)}),backlinksAs:`storyboard`,state:(e,t,n,r)=>{if(!(`voicePending`in r))return{extra:{}};let i=nO(e.stateDir,t).unread();return{extra:{dynamic:e.shotRuns.state(t,n).dynamic,pending:r.voicePending.map(e=>`voice:${e}`),...i?{structure:i}:{}}}},onFilesChanged:(e,t,n,r)=>{(r.includes(`storyboard.xml`)||r.length===0)&&(e.voiceRunner.schedule(n,`storyboard/${t}`),e.storyboardComments.storyboardChanged(t)),r.includes(`comments.json`)&&e.storyboardComments.sync(t)},acceptReport:(e,t,n,r)=>Wc(e,e.shotRuns,{type:`storyboard`,id:t},n,r),relayOps:{state:(e,t)=>e.storyboardComments.state(t),comment:(e,t,n)=>e.storyboardComments.apply(t,Xi(n,jT))},publishBlockers:e=>`blockers`in e?[...e.blockers??[]]:[...e.warnings],publishPlan:{plan:cO,allowCut:lO},pull:{keeps:e=>e.startsWith(`cuts/`),restore:dO},publish:(e,t,n,r)=>{let{storyboard:i,timeline:a,audio:o,cuts:s}=r,c=i?.shots.map(({take:e,takeIn:t,...n})=>n);return{title:n,storyboard:i&&{...i,shots:c},timeline:a,audio:o,cuts:s.slice(-1)}},cloudPage:e=>e.startsWith(`shots/`)&&e.endsWith(`.html`)?{storyboardRuntimeUrl:`/_ryugi/runtime/ryugi-storyboard.js`}:null,review:fO,routes:[OO,kO,AO,jO,MO,NO,PO,FO,IO,LO],resolveFile:ut,pageRuntime:(e,t)=>e.startsWith(`shots/`)?{storyboardRuntimeUrl:t(`ryugi-storyboard.js`)}:{},isPage:e=>e.endsWith(`.html`),keepsLocal:e=>e===`comments.json`||RO.test(e)},BO=/* @__PURE__ */ new Set([`br`,`hr`,`img`]),VO=/<(\/?)([a-z][\w-]*)\b((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>/gi,HO=/<(?:"[^"]*"|'[^']*'|[^>"'])*>/g,UO=/<!\[CDATA\[[\s\S]*?\]\]>|<!--[\s\S]*?-->/g,WO=/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,GO=/^[a-z0-9][a-z0-9-]*$/,KO={"&lt;":`<`,"&gt;":`>`,"&quot;":`"`,"&apos;":`'`,"&amp;":`&`},qO=/* @__PURE__ */ new Set([`p`,`ul`,`ol`,`li`,`codeblock`,`img`,`alert`,`details`,`table`,`tr`,`th`,`td`,`steps`,`step`,`b`,`strong`,`i`,`em`,`u`,`s`,`code`,`a`,`br`]),JO=e=>e.replaceAll(/&(?:lt|gt|quot|apos|amp);/g,e=>KO[e]),YO=e=>JO(e.replaceAll(HO,``)).trim(),XO=/* @__PURE__ */ new Set([`table`,`steps`]),ZO=/* @__PURE__ */ new Set([`change`,`small`,`none`]);function QO(e){for(let t of fk(e)){let e=t.name===`tr`?t.attrs.cost:void 0;if(e!==void 0&&!ZO.has(e))return e;let n=QO(t.inner);if(n!==null)return n}return null}const $O=/<!\[CDATA\[([\s\S]*?)\]\]>/g,ek=/[a-z0-9]/i,tk=/\d/,nk=e=>e.evidence.flatMap(e=>e.kind===`rich`?[e.xml]:[]),rk=e=>nk(e).some(e=>fk(e).some(e=>XO.has(e.name)));function ik(e,t,n){for(let r of fk(e))if(r.name===`code`){let e=YO(r.inner);t&&tk.test(e)&&n.add(e)}else ik(r.inner,t||XO.has(r.name),n)}function ak(e){let t=new Set(e.resultValues);for(let n of nk(e))ik(n,!1,t);return[...t]}function ok(e,t){for(let n of fk(e))n.name===`codeblock`?n.inner.includes(`<![CDATA[`)?t.push(n.inner.replaceAll($O,(e,t)=>t).trim()):t.push(JO(n.inner).trim()):ok(n.inner,t)}function sk(e){let t=[];for(let n of nk(e))ok(n,t);return t}function ck(e,t){let n=[];if(!t)return n;let r=ek.test(t[0]),i=ek.test(t.at(-1));for(let a=e.indexOf(t);a!==-1;a=e.indexOf(t,a+1)){let o=a+t.length,s=e[a-1]??``,c=e[o]??``,l=r&&(ek.test(s)||s===`.`&&tk.test(e[a-2]??``)),u=i&&(ek.test(c)||c===`.`&&tk.test(e[o+1]??``));!l&&!u&&n.push([a,o])}return n}const lk=(e,t)=>ck(e,t).length>0;function uk(e){let t={};for(let n of e.matchAll(WO))t[n[1]]=JO(n[2]??n[3]??``);return t}const dk=e=>e.replaceAll(/[^\n]/g,` `);function fk(e,t){let n=e.replaceAll(UO,dk),r=[],i=[],a=0,o=0,s=null;for(let c of n.matchAll(VO)){let[n,l,u,d,f]=c,p=u.toLowerCase(),m=c.index,h=!!f||BO.has(p);if(!l){if(i.length===0&&(s=c,a=m,o=m+n.length,h)){r.push({name:p,attrs:uk(d),inner:``,raw:e.slice(m,o),start:m,end:o}),s=null;continue}h||i.push(p);continue}let g=i.pop();if(g!==p)return t?.(g?`</${p}> closes <${g}>`:`</${p}> has no opening tag`),r;if(i.length===0&&s){let t=m+n.length;r.push({name:p,attrs:uk(s[3]),inner:e.slice(o,m),raw:e.slice(a,t),start:a,end:t}),s=null}}return i.length&&t?.(`<${i.at(-1)}> is never closed`),r}function pk(e){let t=null,n=e=>{for(let r of fk(e,e=>t??=e)){if(t)return;n(r.inner)}};return n(e),t}function mk(e){for(let t of fk(e)){if(!qO.has(t.name))return t.name;let e=mk(t.inner);if(e)return e}return null}function hk(e,t){let{id:n,judge:r,from:i,capturedAt:a}=e.attrs;if(!n)return t.push(`a <claim> needs an id`),null;if(r!==`agent`&&r!==`human`)return t.push(`claim "${n}" judge must be "agent" or "human"`),null;let o=fk(e.inner),s=o.find(e=>e.name===`title`),c=o.find(e=>e.name===`ask`),l=o.find(e=>e.name===`result`),u=l?fk(l.inner).flatMap(e=>e.name===`code`&&YO(e.inner)?[YO(e.inner)]:[]):[];!s||!YO(s.inner)?t.push(`claim "${n}" needs a <title>`):r!==`human`||c&&YO(c.inner)||t.push(`claim "${n}" is judged by a person: add an <ask> saying what would make it wrong`);let d=[],f=[],p=()=>{f.length&&(d.push({kind:`rich`,xml:e.inner.slice(f[0].start,f.at(-1).end)}),f=[])};for(let e of o){if(e.name===`title`||e.name===`ask`||e.name===`result`)continue;if(e.name===`output`){p();let r=e.attrs.src??``;!/^evidence\/[^/].*$/.test(r)||r.split(`/`).includes(`..`)?t.push(`claim "${n}" output must be a file under evidence/: ${r}`):/\.html?$/i.test(r)?t.push(`claim "${n}" output must not be an .html file: save it as .txt`):d.push({kind:`output`,src:r});continue}let r=qO.has(e.name)?mk(e.inner):e.name;if(r)t.push(`<${r}> is not allowed inside a claim`);else{let r=QO(e.raw);r!==null&&t.push(`claim "${n}" has cost="${r}": use change, small or none`),f.push(e)}}return p(),{kind:`claim`,id:n,judge:r,...i?{from:i}:{},...a?{capturedAt:a}:{},title:s?YO(s.inner):``,...c&&YO(c.inner)?{ask:YO(c.inner)}:{},...l&&YO(l.inner)?{result:YO(l.inner)}:{},...u.length?{resultValues:u}:{},evidence:d,source:e.raw}}function gk(e,t){let n=e.attrs.id;if(!n)return t.push(`a <gap> needs an id`),null;let r=t=>YO(fk(e.inner).find(e=>e.name===t)?.inner??``),[i,a,o]=[r(`title`),r(`why`),r(`needs`)];return i?a&&o||t.push(`gap "${n}" needs a <why> and a <needs>`):t.push(`gap "${n}" needs a <title>`),{kind:`gap`,id:n,title:i,why:a,needs:o,source:e.raw}}function _k(e,t){let{artboard:n,group:r}=e.attrs;return n&&r?{kind:`row`,artboard:n,group:r}:(t.push(`a top-level <ref> must name an artboard and a group`),null)}function vk(e){let t=pk(e);if(t)return{report:null,warnings:[t]};let n=fk(e),r=n[0];if(n.length!==1||r?.name!==`verify`)return{report:null,warnings:[`verify.xml must be one <verify> element`]};let i=[],a=r.attrs.title?.trim()??``;a||i.push(`<verify> needs a title`);let o=[],s=/* @__PURE__ */ new Set,c;for(let[e,t]of fk(r.inner).entries()){if(t.name===`p`){e===0&&!mk(t.inner)?c=t.raw:i.push(`<p> is only allowed once, before the first claim`);continue}let n=t.name===`claim`?hk(t,i):t.name===`gap`?gk(t,i):t.name===`ref`?_k(t,i):null;n?(n.kind!==`row`&&(GO.test(n.id)?s.has(n.id)&&i.push(`id "${n.id}" is used twice`):i.push(`id "${n.id}" must be lowercase letters, digits and hyphens`),s.add(n.id)),o.push(n)):[`claim`,`gap`,`ref`].includes(t.name)||i.push(`<${t.name}> is not allowed at the top of a verify report: use <claim>, <gap> or <ref artboard group>`)}return{report:i.length?null:{title:a,...c?{intro:c}:{},items:o},warnings:i}}const yk=e=>e.messages.some(e=>!e.deleted),bk=e=>e.messages[0]?.at??e.statusAt,xk=(e,t)=>bk(e)<bk(t)?-1:+(bk(e)>bk(t)),Sk=e=>`${e.artboard}/${e.group}`,Ck=e=>e.evidence.some(e=>e.kind===`output`?!e.missing:/<codeblock[\s>]/i.test(e.xml));function wk(e,t,n){let r=t.filter(t=>t.anchor.claim===e.id&&t.anchor.verdict&&yk(t)).sort(xk),i=r.filter(e=>e.anchor.verdict===`reject`&&e.status===`open`).length,a=r.at(-1);if(!a)return{state:e.judge===`agent`&&e.from?.trim()&&Ck(e)&&!e.unmatched?.length?`checked`:`pending`,evidenceUpdated:!1,rejectThreads:i};let o=bk(a);if(n.has(a.id))return{state:`pending`,at:o,evidenceUpdated:!0,rejectThreads:i};let s=a.messages[0]?.author===`agent`?{by:`agent`}:{};return a.anchor.verdict===`pass`?{state:`pass`,at:o,...s,evidenceUpdated:!1,rejectThreads:i}:a.status===`open`?{state:`reject`,at:o,...s,evidenceUpdated:!1,rejectThreads:i}:{state:`pending`,at:o,evidenceUpdated:!1,rejectThreads:i}}function Tk(e,t,n){let r=t.filter(t=>t.anchor.gap===e.id&&t.anchor.waive&&yk(t)).sort(xk).at(-1);return!!r&&!n.has(r.id)}function Ek(e,t,n,r){let i=new Set(e.items.flatMap(e=>e.kind===`claim`?[e.id]:[])),a={needs:[],checked:[],gaps:[],orphans:t.filter(e=>e.anchor.verdict===`reject`&&e.status===`open`&&yk(e)&&!i.has(e.anchor.claim??``))};for(let i of e.items)if(i.kind===`gap`)a.gaps.push({item:i,waived:Tk(i,t,n)});else if(i.kind===`row`)a.needs.push({item:i,state:r[Sk(i)]??`missing`});else{let e=wk(i,t,n);(e.state===`checked`?a.checked:a.needs).push({item:i,state:e})}return a}const Dk=e=>typeof e.state==`string`?e.state:e.state.state;function Ok(e){let t=e.needs.map(Dk),n=t.filter(e=>e===`pending`).length,r=t.filter(e=>e===`reject`).length,i=e.gaps.filter(e=>!e.waived).length;return{needYou:n,rejected:r,checked:e.checked.length,notVerified:i,orphaned:e.orphans.length,done:n===0&&r===0&&i===0&&e.orphans.length===0&&!t.includes(`missing`)}}function kk(e){let t=0;for(let n of e.evidence)if(n.kind===`rich`)for(let[,e]of n.xml.matchAll(/<table\b[^>]*>([\s\S]*?)<\/table>/g)){let n=[...e.matchAll(/<tr\b([^>]*)>([\s\S]*?)<\/tr>/g)];if(n.some(e=>/\bcost\s*=/.test(e[1])))continue;let r=n.findIndex(e=>/<td\b/.test(e[2]));t=Math.max(t,r===-1?0:n.length-r)}return t}function Ak(e,t=Date.now()){let n=[];for(let r of e.items){if(r.kind!==`claim`)continue;let e=`claim "${r.id}"`;if(r.from?.trim()||n.push(`${e} has no "from": say which environment and build its evidence came from`),!r.capturedAt?.trim())n.push(`${e} has no "capturedAt": say when its evidence was captured`);else{let i=Date.parse(r.capturedAt);Number.isNaN(i)?n.push(`${e} field "capturedAt" is not an ISO time`):i>t+6e4&&n.push(`${e} field "capturedAt" is in the future`)}if(r.judge===`agent`&&!Ck(r)&&n.push(`${e} is judged by the agent but holds no output, so it waits on a verdict`),r.judge===`agent`&&!r.result&&n.push(`${e} has no <result>: write what it proved in one line`),r.judge===`human`){let t=kk(r);t>12&&n.push(`${e} has a table of ${t} rows with no cost: mark each row cost="change|small|none" so only change opens`)}r.judge===`agent`&&rk(r)&&ak(r).length===0&&n.push(`${e} shows a table or steps but marks no value as copied from its output: put copied values in <code>`)}return n}const jk=/<table\b[^>]*>([\s\S]*?)<\/table>/g,Mk=/<tr\b([^>]*)>[\s\S]*?<\/tr>/g,Nk=/\s+cost\s*=\s*(?:"([^"]*)"|'([^']*)')/,Pk=/* @__PURE__ */ new Set([`change`,`small`,`none`]),Fk={en:{small:`Small cost if wrong`,none:`No cost if wrong`},zh:{small:`错了有小代价`,none:`错了也没影响`}};function Ik(e,t){let n=t?Fk.zh:Fk.en;return e.replaceAll(jk,(e,t)=>{let r=[...t.matchAll(Mk)].map(e=>{let t=Nk.exec(e[1]);return{raw:e[0].replace(Nk,``),cost:t?t[1]??t[2]:null,cells:e[0]}});if(!r.some(e=>e.cost!==null))return e;let i=r.findIndex(e=>e.cost!==null||/<td\b/.test(e.cells)),a=i===-1?r.length:i,o=r.slice(0,a).map(e=>e.raw).join(``),s=r.slice(a),c=e=>e===null?`small`:Pk.has(e)?e:`change`,l=e=>s.filter(t=>c(t.cost)===e).map(e=>e.raw),u=e=>`<table>${o}${e.join(``)}</table>`,d=l(`change`),f=[`small`,`none`].flatMap(e=>{let t=l(e);return t.length?[`<details summary="${n[e]} · ${t.length}">${u(t)}</details>`]:[]});return[d.length?u(d):``,...f].join(``)})}const Lk=e=>e?e.replace(/\n$/,``).split(`
486
- `).length:0,Rk=e=>e.evidence.flatMap(e=>e.kind===`output`?[e.src]:[]);function zk(e){let t={title:``,report:null,rich:Object.create(null),versions:{},lines:{}};Zv(e);let n;try{n=d.default.readFileSync(p.default.join(e,H.verify),`utf8`)}catch{return{...t,warnings:[`${H.verify} not found`]}}let{report:r,warnings:i}=vk(n);if(!r)return{...t,warnings:i};let a=Object.create(null),o={},s={},c=[...i],l=(t,n)=>{let r=a[t]??=[],i=cl.tree(n,e);if(!i)r.push(null);else if(`state`in i)r.push(i.state);else{if(!i.rejected)throw Error(i.error);r.push(null),c.push(`${t||`intro`}: ${i.error}`)}};r.intro&&l(``,r.intro);let u=/[\u3400-\u9FFF]/.test(r.title),f=r.items.map(t=>{if(t.kind!==`claim`)return t;let n=sk(t),r=t.evidence.map(r=>{if(r.kind===`rich`)return l(t.id,Ik(r.xml,u)),r;let i=ot(e,r.src);if(i){o[r.src]=d.default.statSync(i).mtimeMs;let e=d.default.readFileSync(i,`utf8`);return s[r.src]=Lk(e),n.push(e),r}return c.push(`claim "${t.id}" output not found: ${r.src}`),{...r,missing:!0}}),i=n.length?ak(t).filter(e=>!n.some(t=>lk(t,e))):[];for(let e of i)c.push(`claim "${t.id}" shows "${e}" as copied from its output, but its output does not contain it`);return{...t,evidence:r,...i.length?{unmatched:i}:{}}}),m={...r,items:f};return{title:m.title,report:m,rich:a,versions:o,lines:s,warnings:c}}const Bk=e=>u.default.createHash(`sha1`).update(e.join(`\0`)).digest(`hex`);function Vk(e,t){return Bk([t.source,...Rk(t).map(t=>{let n=ot(e,t);return n?Bk([d.default.readFileSync(n).toString(`base64`)]):`missing`})])}const Hk=e=>typeof e==`string`;function Uk(e){if(typeof e!=`object`||!e)return null;let t=e;return t.op===`verdict`&&Hk(t.claim)&&(t.verdict===`pass`||t.verdict===`reject`)?{op:`verdict`,claim:t.claim,verdict:t.verdict,text:Hk(t.text)?t.text:``,...Hk(t.hash)?{hash:t.hash}:{}}:t.op===`waive`&&Hk(t.gap)?{op:`waive`,gap:t.gap}:t.op===`undo`&&Hk(t.threadId)?{op:`undo`,threadId:t.threadId}:t.op===`reply`&&Hk(t.threadId)&&Hk(t.text)?{op:`reply`,threadId:t.threadId,text:t.text}:null}function Wk(e){let t=t=>p.default.join(e.root,`verify`,t),n=e=>p.default.join(t(e),`comments.json`),r=e=>{try{let t=JSON.parse(d.default.readFileSync(n(e),`utf8`));if(Array.isArray(t.threads))return t}catch{return{version:1,threads:[]}}return{version:1,threads:[]}},i=e=>{let{report:n,warnings:r}=zk(t(e));if(!n)throw Error(`verify/${e} cannot be read: ${r[0]??`no report`}`);return n},a=(e,n)=>Object.fromEntries(n.items.flatMap(n=>n.kind===`claim`?[[`claim:${n.id}`,Vk(t(e),n)]]:n.kind===`gap`?[[`gap:${n.id}`,Bk([n.source])]]:[])),o=(e,t,n)=>{let r=a(e,t);return n.filter(({anchor:e})=>{let t=e.claim?`claim:${e.claim}`:e.gap?`gap:${e.gap}`:``;return t!==``&&e.hash!==void 0&&r[t]!==e.hash}).map(e=>e.id)},s=t=>Object.fromEntries(t.items.flatMap(t=>t.kind===`row`?[[Sk(t),e.rowState?.(t.artboard,t.group)??`missing`]]:[])),c=e=>{let t=r(e),n=[];try{n=o(e,i(e),t.threads)}catch{n=[]}return{comments:t,stale:n}},l=e=>{let t=r(e),n;try{n=i(e)}catch{return{comments:{version:1,threads:[]},stale:[],rows:[],hashes:{}}}let c=s(n);return{comments:t,stale:o(e,n,t.threads),rows:n.items.flatMap(e=>e.kind===`row`?[{artboard:e.artboard,group:e.group,state:c[Sk(e)]}]:[]),hashes:a(e,n)}},u=t=>{let{comments:n,stale:r,hashes:i}=l(t);e.broadcast({type:`report-comments`,artifact:`verify/${t}`,comments:n,stale:r,hashes:i})},f=(e,t)=>{U(n(e),t),u(e)},m=(e,t,n,r)=>{let i=(/* @__PURE__ */ new Date()).toISOString();return{id:cs(10),anchor:e,status:e.verdict===`reject`?`open`:`resolved`,statusAt:i,messages:[{id:cs(10),author:t,...r?{name:r}:{},text:n,at:i}]}},h=(e,n,r,i,a,o)=>{let s=r.items.find(e=>e.kind===`claim`&&e.id===i.claim);if(!s)throw Error(`no claim ${i.claim} in verify/${e}`);let c=i.text.trim();if(i.verdict===`reject`&&!c)throw Error(`a reject needs a reason`);let l=Vk(t(e),s);if(i.hash!==void 0&&i.hash!==l)throw Error(`the evidence changed since this page loaded: look again, then decide`);let u=m({claim:s.id,verdict:i.verdict,hash:l},a,c||`Pass`,o),d=u.statusAt,f=i.verdict===`pass`?n.threads.map(e=>e.anchor.claim===s.id&&e.anchor.verdict===`reject`&&e.status===`open`?{...e,status:`resolved`,statusAt:d}:e):n.threads;return{file:{...n,threads:[...f,u]},threadId:u.id}},g=(e,t,n,r,i,a)=>{let o=n.items.find(e=>e.kind===`gap`&&e.id===r);if(!o)throw Error(`no gap ${r} in verify/${e}`);let s=m({gap:o.id,waive:!0,hash:Bk([o.source])},i,`Waived`,a);return{file:{...t,threads:[...t.threads,s]},threadId:s.id}},_=(e,t,n,r,i)=>{if(!n.trim())throw Error(`a reply needs text`);if(!e.threads.some(e=>e.id===t))throw Error(`no thread ${t}`);let a=(/* @__PURE__ */ new Date()).toISOString();return{...e,threads:e.threads.map(e=>e.id===t?{...e,messages:[...e.messages,{id:cs(10),author:r,...i?{name:i}:{},text:n.trim(),at:a}]}:e)}},v=e=>{let t=i(e),{threads:n}=r(e),a=Ek(t,n,new Set(o(e,t,n)),s(t)),c=new Map([...a.needs,...a.checked].flatMap(e=>e.item.kind===`claim`?[[e.item.id,e.state]]:[]));return{claims:t.items.flatMap(e=>e.kind===`claim`?[{id:e.id,title:e.title,judge:e.judge,...e.from?{from:e.from}:{},...e.capturedAt?{capturedAt:e.capturedAt}:{},...c.get(e.id)}]:[]),rows:t.items.flatMap(e=>e.kind===`row`?[{artboard:e.artboard,group:e.group,state:s(t)[Sk(e)]??`missing`}]:[]),gaps:a.gaps.map(({item:e,waived:t})=>({id:e.id,title:e.title,waived:t})),tally:Ok(a)}};return{comments:c,meta:l,view:v,threads:e=>{let{comments:t,stale:n}=c(e);return t.threads.map(e=>({...e,stale:n.includes(e.id)}))},changed:e=>u(e),apply:(e,t)=>{let n=r(e);if(t.op===`undo`){let r=n.threads.find(e=>e.id===t.threadId);if(!r||!(r.anchor.verdict===`pass`||r.anchor.waive))throw Error(`only a pass or a waiver can be undone`);return f(e,{...n,threads:n.threads.filter(e=>e.id!==t.threadId)}),{threadId:t.threadId}}if(t.op===`reply`)return f(e,_(n,t.threadId,t.text,`human`)),{threadId:t.threadId};let a=i(e),o=t.op===`waive`?g(e,n,a,t.gap,`human`):h(e,n,a,t,`human`);return f(e,o.file),{threadId:o.threadId}},applyAgent:(e,t,n)=>{let a=r(e);if(t.op===`reply`)return f(e,_(a,t.threadId,t.text,`agent`,n)),{claims:[],threadIds:[t.threadId]};let o=i(e);if(t.op===`waive`){let r=g(e,a,o,t.gap,`agent`,n);return f(e,r.file),{claims:[],threadIds:[r.threadId]}}let s=v(e).claims.filter(e=>e.state===`pending`||e.state===`reject`).map(e=>e.id),c=t.all?s:t.claim?[t.claim]:[];if(!c.length&&!t.all)throw Error(`verdict needs {claim} or {all: true}`);let l=[];for(let r of c){let i=h(e,a,o,{claim:r,verdict:t.verdict,text:t.text},`agent`,n);a=i.file,l.push(i.threadId)}return l.length&&f(e,a),{claims:c,threadIds:l}}}}function Gk(e,t,n){let{configFile:r}=e.options,i=r?Gr(r).config.artifacts:null;return e.verify.meta(n).rows.map(e=>{let n=i?.[`artboard/${e.artboard}`]?.cloud?.id??t.idOf(e.artboard,`artboard`);return n?{...e,to:n}:e})}function Kk(e,t,n,r,{rows:i}){let{report:a,rich:o,versions:s,lines:c,warnings:l}=zk(e);return{title:n,report:a,rich:o,versions:s,lines:c,warnings:l,...Wk({root:p.default.dirname(p.default.dirname(e)),broadcast:()=>{}}).meta(p.default.basename(e)),...i?{rows:i}:{}}}const qk=/^\/api\/agent\/verify\/([^/]+)\/comments$/,Jk=/^\/api\/verify\/([^/]+)\/comments$/,Yk=e=>typeof e==`string`?e:``;function Xk(e,t,n){let r=Yk(n.agent).trim()||void 0;if(n.op===`list`)return{type:`report`,artifact:`verify/${t}`,...e.view(t),threads:e.threads(t).map(({id:e,anchor:t,status:n,stale:r,messages:i})=>({id:e,anchor:{...t,hash:void 0},status:n,stale:r,messages:i.map(({author:e,text:t,at:n})=>({author:e,text:t,at:n}))}))};if(n.op===`verdict`){if(n.verdict!==`pass`&&n.verdict!==`reject`)throw Error(`verdict needs {verdict: "pass" | "reject"}`);if(n.all!==!0&&!Yk(n.claim))throw Error(`verdict needs {claim} or {all: true}`);return e.applyAgent(t,{op:`verdict`,verdict:n.verdict,text:Yk(n.text),...n.all===!0?{all:!0}:{claim:Yk(n.claim)}},r)}if(n.op===`waive`){if(!Yk(n.gap))throw Error(`waive needs {gap}`);return e.applyAgent(t,{op:`waive`,gap:Yk(n.gap)},r)}if(n.op===`reply`){if(!Yk(n.threadId))throw Error(`reply needs {threadId}`);let i=e.applyAgent(t,{op:`reply`,threadId:Yk(n.threadId),text:Yk(n.text)},r);return{...i,threadId:i.threadIds[0]}}throw Error(`a report takes list, verdict, waive or reply`)}const Zk={path:qk,methods:[`POST`],auth:`agent`,handle:async(e,t,n,{match:r})=>{let i=r[1];if(!W(n.root,`verify`,i)){B(t,404,{error:`verify/${i} not found`});return}let a=await yc(e),o=typeof a==`object`&&a?a:{};try{B(t,200,Xk(n.verify,i,o))}catch(e){B(t,400,{error:e.message})}}};async function Qk(e,t,n,r){if(!W(n.root,`verify`,r)){B(t,404,{error:`verify/${r} not found`});return}let i=Uk(await yc(e));if(!i)B(t,400,{error:`not a report op`});else try{B(t,200,{...n.verify.apply(r,i),...n.verify.meta(r)})}catch(e){B(t,400,{error:e.message})}}const $k={read:zk,prepare:async e=>{zk(e),await cl.idle()},meta:(e,t)=>e.verify.meta(t),onFilesChanged:(e,t,n,r)=>{r.some(e=>e!==`comments.json`)&&e.verify.changed(t)},check:{answer:(e,t,{payload:n})=>`report`in n&&n.report?{provenance:Ak(n.report)}:{}},publishExtras:(e,t,n)=>({rows:Gk(e,n,t)}),pull:{publishedRecordings:!0},publish:Kk,routes:[Zk,{path:Jk,methods:[`POST`],auth:`same-origin`,handle:(e,t,n,{match:r})=>Qk(e,t,n,r[1])}],resolveFile:ot,isPage:e=>e.endsWith(`.html`),keepsLocal:e=>e===`comments.json`||e===`report.xml`};function eA(e,t,n){let r=e.whiteboards.scene(t,n);return r!==null&&e.whiteboards.geometry(t,n)?.sceneVersion===lb(r)}async function tA(e,t,n){let r=()=>n.some(n=>{let r=e.whiteboards.scene(t,n),i=e.whiteboards.geometry(t,n);return r!==null&&i!==null&&i.sceneVersion!==lb(r)});for(let e=0;e<1e4&&r();e+=100)await new Promise(e=>setTimeout(e,100))}const nA={pages:(e,t)=>(e.whiteboards.sync(t),e.whiteboards.livePages(t).map(e=>e.id)),settle:(e,t,n,r)=>tA(e,t,r),onlyPage:gb,evidence:(e,t,{pages:n})=>({required:!0,observed:n.every(n=>eA(e,t,n))})};function rA(e,{artifact:t,elements:n,completion:r,files:i,page:a}){if(typeof t!=`string`||!Array.isArray(n))return;let o=G(t);if(o?.type!==`whiteboard`||t!==`whiteboard/${o.id}`)return;let s=a===void 0?Ve:a;if(!e.whiteboards.livePages(o.id).some(e=>e.id===s))return;let c=n.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`&&typeof e.type==`string`),l=i&&typeof i==`object`&&!Array.isArray(i)?Object.fromEntries(Object.entries(i).filter(([,e])=>typeof e==`object`&&!!e)):void 0;e.whiteboards.applyBrowser(o.id,c,{page:s,completion:r===!0,...l?{files:l}:{}})}const iA=e=>{if(typeof e!=`object`||!e)return null;let{op:t,id:n,name:r,to:i}=e;return typeof n==`string`?(t===`add`||t===`rename`)&&typeof r==`string`?{op:t,id:n,name:r.slice(0,200)}:t===`move`&&typeof i==`number`&&Number.isInteger(i)?{op:t,id:n,to:i}:t===`delete`||t===`restore`?{op:t,id:n}:null:null};function aA(e,{artifact:t,op:n}){if(typeof t!=`string`)return;let r=G(t);if(r?.type!==`whiteboard`||t!==`whiteboard/${r.id}`)return;let i=iA(n);i&&e.whiteboards.applyPages(r.id,i)}const oA=`embed.html`,sA=e=>e.replaceAll(/[&<>"]/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`})[e]);function cA(e){return`<!doctype html>
487
- <html>
488
- <head>
489
- <meta charset="utf-8">
490
- <style>html,body{margin:0;height:100%;background:transparent;overflow:hidden}#ryugi-whiteboard-embed{width:100%;height:100%}</style>
491
- </head>
492
- <body>
493
- <div id="ryugi-whiteboard-embed"></div>
494
- <script type="module" src="${sA(e)}"><\/script>
495
- </body>
496
- </html>
497
- `}const lA=()=>/* @__PURE__ */ new Map([[oA,Buffer.from(cA(`/_ryugi/runtime/ryugi-whiteboard-embed.js`))]]),uA=[`type`,`x`,`y`,`width`,`height`,`angle`,`points`,`text`,`textAlign`,`strokeColor`,`backgroundColor`,`frameId`];function dA(e){let t=Array.isArray(e.elements)?e.elements:[],n=[];for(let e of t){if(n.length>=500)break;if(!e||typeof e!=`object`)continue;let t=e;if(t.isDeleted||typeof t.type!=`string`)continue;let r={};for(let e of uA)t[e]!==void 0&&(r[e]=t[e]);t.type===`richtext`&&(r.text=Hy(t.content)),t.type===`svg`&&typeof t.svg==`string`&&t.svg.length<=2e4&&(r.svg=t.svg),n.push(r)}return n}function fA(e,t,n,r){let i=my(d.default.readFileSync(p.default.join(e,`scene.excalidraw`),`utf8`));if(`error`in i)throw Error(i.error);let a=Je(vy(e).pages);return{title:n,sceneVersion:r.sceneVersion,scene:dA(i.scene),...a.length>1?{pages:a.map(e=>({id:e.id,...e.name?{name:e.name}:{}}))}:{}}}const pA={threads:(e,t,n)=>{let r=new Map(e.whiteboardComments.list(t,n,!0).map(e=>[e.id,e]));return e.whiteboardComments.comments(t).threads.map(e=>({...e,...r.get(e.id),messages:e.messages.map(({avatar:e,...t})=>t)}))}},mA=/* @__PURE__ */ new Set([`arrow`,`line`]);function hA(e){let t=dy(e),n=t.author??null;return{author:n,editedBy:t.lastBy&&t.lastBy!==n?t.lastBy:null}}function gA(e,t={}){let n=e.elements.filter(e=>!e.isDeleted),r=/* @__PURE__ */ new Map;for(let e of n)e.type===`text`&&e.containerId&&typeof e.text==`string`&&r.set(e.containerId,e.text);let i=new Map(n.map(e=>[e.id,e.frameId??null])),a=e=>e.type===`richtext`?Hy(e.content)||null:e.type===`svg`?Gy(e.svg):typeof e.text==`string`?e.text:null,o=e=>({id:e.id,type:e.type,text:r.get(e.id)??a(e),sticky:e.type===`richtext`||e.type===`rectangle`&&e.backgroundColor===`#ffec99`,group:e.groupIds?.[0]??null,...hA(e)}),s=n.filter(e=>e.type!==`frame`&&!mA.has(e.type)&&!(e.type===`text`&&e.containerId)),c=n.filter(e=>e.type===`frame`&&(!t.frame||e.id===t.frame)).map(e=>({id:e.id,name:typeof e.name==`string`?e.name:e.id,items:s.filter(t=>t.frameId===e.id).map(o)})),l=t.frame?[]:s.filter(e=>!e.frameId).map(o),u=e=>e!==null&&i.get(e)===t.frame;return{frames:c,loose:l,arrows:n.filter(e=>mA.has(e.type)).map(e=>({arrow:e,from:e.startBinding?.elementId??null,to:e.endBinding?.elementId??null})).filter(({arrow:e,from:n,to:r})=>!t.frame||e.frameId===t.frame||u(n)||u(r)).map(({arrow:e,from:t,to:n})=>({id:e.id,from:t,to:n,label:r.get(e.id)??null,...hA(e)})),selected:t.selected??[]}}const _A=e=>e.replaceAll(/\s*\n\s*/g,` / `),vA=({author:e,editedBy:t})=>e?` · ${e}${t?`, ${t} edited`:``}`:``,yA=e=>e.sticky?`sticky`:e.type===`svg`&&!e.text?`svg illustration`:e.type,bA=e=>` ${e.id} ${yA(e)}${e.text?` "${_A(e.text)}"`:``}${vA(e)}`;function xA(e){let t=[];for(let n of e.frames)t.push(`frame ${n.id} "${n.name}" (${n.items.length})`),t.push(...n.items.map(bA));if(e.loose.length&&(t.push(`not in a frame (${e.loose.length})`),t.push(...e.loose.map(bA))),e.arrows.length){t.push(`arrows (${e.arrows.length})`);for(let n of e.arrows)t.push(` ${n.from??`?`} → ${n.to??`?`}${n.label?` ("${_A(n.label)}")`:``}${vA(n)}`)}return e.selected.length&&t.push(`selected: ${e.selected.join(`, `)}`),t}const SA=e=>typeof e==`number`&&Number.isFinite(e),CA=e=>typeof e==`string`&&e.length>0&&e.length<=200;function wA(e){if(!Va(e)||!SA(e.x)||!SA(e.y))return null;let t={x:e.x,y:e.y};if(Ge(e.page)&&(t.page=e.page),e.elements!==void 0){if(!Array.isArray(e.elements)||e.elements.length>50||!e.elements.every(CA))return null;e.elements.length&&(t.elements=e.elements)}if(e.revs!==void 0){if(!Va(e.revs)||Array.isArray(e.revs))return null;let n=Object.entries(e.revs);if(n.length>50||!n.every(([e,t])=>CA(e)&&SA(t)))return null;t.revs=Object.fromEntries(n)}return t}const TA={read:wA,same:(e,t)=>e.x===t.x&&e.y===t.y&&(e.elements??[]).join(`\0`)===(t.elements??[]).join(`\0`),missing:`a new thread needs a whiteboard anchor (x, y); dropped it`},EA=()=>({version:1,threads:[]}),DA=e=>Ga(e,TA),OA=(e,t,n,r,i,a)=>Za(e,t,n,r,i,a,TA);function kA(e,t,n,r,i){return t.op===`create`?{...e,threads:[...e.threads,eo(t.anchor,`human`,t.text,n,r,i)]}:no(e,t,n,r,i)}function AA(e,t,n,r,i){if(t.op!==`add`)return uo(e,t,n,r,i);let a=eo(t.anchor,`agent`,t.text,n,r,{name:i});return{file:{...e,threads:[...e.threads,a]},threadId:a.id,messageId:a.messages[0].id}}function jA(e,t){if(!t)return null;if(!e.elements?.length)return t.livePage(e.page??`main`)?null:`orphan`;let n=e.elements.map(e=>t.find(e));return n.some(e=>!e)?`orphan`:n.some((t,n)=>(dy(t.element).rev??1)!==(e.revs?.[e.elements[n]]??1))?`stale`:null}function MA(e,t){for(let n of e.elements??[]){let e=t?.find(n)?.page;if(e)return e}return e.page??`main`}function NA(e,t){if(!e.elements?.length||!t)return e;let n=e.elements.flatMap(e=>{let n=t.find(e);return n?[[e,n]]:[]}),r=Object.fromEntries(n.map(([e,t])=>[e,dy(t.element).rev??1])),i=n[0]?.[1].page;return{...e,revs:r,...i&&i!==`main`?{page:i}:{}}}const PA={empty:EA,saved:DA,merge:OA,human:(e,t,n,r,i)=>kA(e,t,n,r,i),agent:AA},FA=({revs:e,...t})=>t;function IA(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.op!==`create`){let t=ms(e);return t&&t.op!==`create`?t:null}let n=wA(t.anchor);return n&&fs(t.text)&&t.text.length>0?{op:`create`,anchor:FA(n),text:t.text}:null}function LA(e){if(typeof e!=`object`||!e)return null;let t=e,n=fs(t.text)&&t.text.length>0?t.text:null;if(t.op===`add`){if(!n)return null;if(typeof t.element==`string`&&t.element.length>0&&t.element.length<=200)return{op:`add`,element:t.element,text:n};let e=e=>typeof e==`number`&&Number.isFinite(e);return!e(t.x)||!e(t.y)?null:{op:`add`,x:t.x,y:t.y,...typeof t.page==`string`&&t.page?{page:t.page}:{},text:n}}return typeof t.threadId!=`string`||t.threadId.length===0?null:t.op===`reply`?n?{op:`reply`,threadId:t.threadId,text:n}:null:t.op===`resolve`?{op:`resolve`,threadId:t.threadId}:null}function RA(e){let t=/* @__PURE__ */ new Map,n=$o(e.stateDir,`whiteboard`),r=t=>Es(e.stateDir,`whiteboard/${t}`),i=n=>{let r=t.get(n);return r||(r=vs(p.default.join(e.root,`whiteboard`,n,`comments.json`),PA,e.names,{artifact:`whiteboard/${n}`,savesDir:p.default.join(e.stateDir,`whiteboard`,n,`comment-saves`)}),t.set(n,r)),r},a=(t,n)=>{let r=e.board(t);return i(t).current().threads.filter(e=>jA(e.anchor,r)===n).map(e=>e.id)},o=t=>{let n=e.board(t);return Object.fromEntries(i(t).current().threads.map(e=>[e.id,MA(e.anchor,n)]))},s=t=>e.broadcast({type:`whiteboard-comments`,artifact:`whiteboard/${t}`,comments:i(t).current(),stale:a(t,`stale`),orphans:a(t,`orphan`),placed:o(t),listening:r(t)}),c=t=>{let n=e.board(t);return e=>{let t=jA(e.anchor,n);return{...e,page:MA(e.anchor,n),stale:t===`stale`,orphan:t===`orphan`,waitingOn:ro(e),messages:e.messages.map(({avatar:e,...t})=>t)}}},l=(t,n)=>{let r=e.board(t);if(n.element){let e=r?.find(n.element);if(!e)throw Error(`no element ${n.element} in whiteboard/${t}`);let{element:i}=e;return NA({x:(i.x??0)+(i.width??0)/2,y:(i.y??0)+(i.height??0)/2,elements:[i.id]},r)}if(typeof n.x!=`number`||typeof n.y!=`number`)throw Error(`a whiteboard comment needs --element or --x and --y`);if(!n.page)return{x:n.x,y:n.y};if(!r?.livePage(n.page))throw Error(`page ${n.page} is not on whiteboard/${t}`);return{x:n.x,y:n.y,page:n.page}};return{comments:e=>i(e).current(),listening:r,stale:e=>a(e,`stale`),placed:o,orphans:e=>a(e,`orphan`),warnings:e=>i(e).warnings(),apply(t,n){let r=n.op===`create`?{...n,anchor:NA(n.anchor,e.board(t))}:n;return i(t).apply(r),s(t),i(t).current()},applyAgent(e,t,n){let r=t.op===`add`?{op:`add`,anchor:l(e,t),text:t.text}:t,{threadId:a,messageId:o}=i(e).applyAgent(r,n);return s(e),{threadId:a,...o?{messageId:o}:{}}},list(e,t,r){i(e).sync()&&s(e);let a=i(e).current(),o=c(e);if(r)return a.threads.filter(e=>!e.messages.every(e=>e.deleted)).map(o);let{threads:l,newest:u}=co(a,n.get(e,t));return u&&n.set(e,t,u),l.map(o)},sync(e){i(e).sync()&&s(e)},sceneChanged(e){t.has(e)&&s(e)}}}const zA=/^\/api\/whiteboard\/([^/]+)\/scene$/,BA=/^\/api\/whiteboard\/([^/]+)\/pages$/,VA=/^\/api\/whiteboard\/([^/]+)\/comments$/,HA=/^\/api\/whiteboard\/([^/]+)\/(geometry)$/,UA=/^\/api\/whiteboard\/([^/]+)\/(render)$/,WA=/^\/api\/agent\/whiteboard\/([^/]+)\/comments$/,GA=/^\/api\/agent\/whiteboard\/([^/]+)\/scene$/,KA=(e,t,n)=>e.whiteboards.livePages(t).some(e=>e.id===n),qA={path:zA,auth:`viewer`,handle:(e,t,n,{match:r,url:i})=>{let a=r[1],o=i.searchParams.get(`page`)??`main`,s=KA(n,a,o)?n.whiteboards.scene(a,o):null;s?B(t,200,{scene:s,page:o,pages:n.whiteboards.pages(a),problem:n.whiteboards.problem(a,o),comments:n.whiteboardComments.comments(a),stale:n.whiteboardComments.stale(a),orphans:n.whiteboardComments.orphans(a)}):B(t,404,{error:`whiteboard/${a} page ${o} not found`})}},JA={path:BA,auth:`viewer`,handle:(e,t,n,{match:r})=>{let i=r[1];if(!W(n.root,`whiteboard`,i)){B(t,404,{error:`whiteboard/${i} not found`});return}let a={};for(let e of n.whiteboards.livePages(i))for(let t of n.whiteboards.scene(i,e.id)?.elements??[])t.type===`frame`&&!t.isDeleted&&!(t.id in a)&&(a[t.id]={name:typeof t.name==`string`?t.name:``,page:e.id});let o=n.whiteboards.scene(i)?.appState.name;B(t,200,{pages:n.whiteboards.pages(i),title:typeof o==`string`?o:``,frames:a})}},YA=async(e,t,n,{match:r,url:i})=>{let[,a=``,o]=r,s=await vc(e,o===`render`?8388608:2097152);if(!s){z(t,413,`Too large`);return}let c=i.searchParams.get(`page`)??`main`,l=!1;if(!KA(n,a,c))l=!1;else if(o===`render`){let e=i.searchParams.get(`version`);l=e!==null&&/^\d+$/.test(e)?n.whiteboards.reportRender(a,s,Number(e),c):!1}else try{l=n.whiteboards.reportGeometry(a,JSON.parse(s.toString(`utf8`)),c)}catch{l=!1}if(!l){B(t,400,{error:`not a whiteboard ${o} report`});return}let u=W(n.root,`whiteboard`,a);u&&n.writeState({type:`whiteboard`,id:a},u),z(t,204,``)},XA={path:HA,methods:[`POST`],auth:`same-origin`,handle:YA},ZA={relay:`deny`,path:UA,methods:[`POST`],auth:`same-origin`,handle:YA},QA={path:VA,methods:[`POST`],auth:`same-origin`,handle:async(e,t,n,{match:r})=>{let i=r[1];if(!W(n.root,`whiteboard`,i)){B(t,404,{error:`whiteboard/${i} not found`});return}let a=IA(await yc(e));if(!a)B(t,400,{error:`not a whiteboard comment op`});else try{B(t,200,{comments:n.whiteboardComments.apply(i,a),stale:n.whiteboardComments.stale(i),orphans:n.whiteboardComments.orphans(i)})}catch(e){B(t,400,{error:e.message})}}};async function $A(e,t,n,r){if(!W(n.root,`whiteboard`,r)){B(t,404,{error:`whiteboard/${r} not found`});return}let i=await yc(e),a=typeof i==`object`&&i?i:{},o=bc(a);if(a.op===`list`){B(t,200,{type:`comments`,artifact:`whiteboard/${r}`,threads:n.whiteboardComments.list(r,o??`Agent`,a.all===!0)});return}let s=LA(a);if(!s)B(t,400,{error:`not an agent comment op: use list, add {element | x, y, text}, reply {threadId, text} or resolve {threadId}; text must not be empty`});else try{B(t,200,n.whiteboardComments.applyAgent(r,s,o))}catch(e){B(t,400,{error:e.message})}}const ej={path:WA,methods:[`POST`],auth:`agent`,handle:(e,t,n,{match:r})=>$A(e,t,n,r[1])};async function tj(e,t,n,r){if(!W(n.root,`whiteboard`,r)){B(t,404,{error:`whiteboard/${r} not found`});return}n.whiteboards.sync(r);let i=await yc(e),a=typeof i==`object`&&i?i:{},o=typeof a.frame==`string`&&a.frame?a.frame:void 0,s=typeof a.page==`string`&&a.page?a.page:void 0,c=n.whiteboards.livePages(r);if(s&&!c.some(e=>e.id===s)){B(t,404,{error:`page ${s} is not on whiteboard/${r}; pages: ${c.map(e=>e.id).join(`, `)}`});return}let l=e=>{let t=n.whiteboards.scene(r,e),i=n.whiteboards.render(r,e),a=t?lb(t):0;return{sceneVersion:a,render:i?i.sceneVersion===a?`current`:`stale`:`none`,...i?{renderPath:n.whiteboards.renderPathOf(r,e),renderVersion:i.sceneVersion}:{}}};if(c.length>1&&!s&&!o){let e=c.map(e=>{let t=(n.whiteboards.scene(r,e.id)?.elements??[]).filter(e=>!e.isDeleted);return{id:e.id,name:e.name??null,frames:t.filter(e=>e.type===`frame`).map(e=>e.id),elements:t.length,...l(e.id)}}),i=new Set(e.map(e=>e.render));B(t,200,{artifact:`whiteboard/${r}`,sceneVersion:e.reduce((e,t)=>e+t.sceneVersion,0),render:i.size===1?[...i][0]:`stale`,problem:null,conflicts:[],pages:e,lines:e.map(e=>`page ${e.id}${e.name?` "${e.name}"`:``} · ${e.elements} elements · frames ${e.frames.join(`, `)||`none`} · render ${e.render}`)});return}let u=s??(o?n.whiteboards.elementPage(r,o):null)??`main`,d=n.whiteboards.scene(r,u);if(!d){B(t,404,{error:`whiteboard/${r} not found`});return}let f=nj(p.default.join(n.stateDir,`whiteboard`,r,`selection.json`)),m=gA(d,{...o?{frame:o}:{},selected:f});B(t,200,{artifact:`whiteboard/${r}`,...c.length>1?{page:u}:{},...l(u),problem:n.whiteboards.problem(r,u),conflicts:n.whiteboards.conflicts(r,u),lines:xA(m),summary:m})}function nj(e){try{return(JSON.parse(d.default.readFileSync(e,`utf8`)).selected??[]).flatMap(e=>typeof e.id==`string`?[e.id]:[])}catch{return[]}}const rj={path:GA,methods:[`POST`],auth:`agent`,handle:(e,t,n,{match:r})=>tj(e,t,n,r[1])};function ij(e){return{pages:e.includes(He),scenes:e.map(qe).filter(e=>e!==null)}}function aj(e,t,n){return hb({pages:e.livePages(t).flatMap(r=>{let i=e.scene(t,r.id);if(!i)return[];let a=d.default.statSync(p.default.join(n,Ke(r.id)),{throwIfNoEntry:!1})?.size??0;return[{id:r.id,scene:i,bytes:a,conflicts:e.conflicts(t,r.id),duplicates:e.duplicates(t,r.id),geometry:e.geometry(t,r.id),problem:r.id===`main`?null:e.problem(t,r.id)}]}),pagesWarnings:e.pagesWarnings(t)})}const oj={artboard:Nc,document:Wl,html:tu,whiteboard:{read:ub,runtimeWarnings:(e,t,n)=>aj(e.whiteboards,t,n).warnings,threads:(e,t)=>e.whiteboardComments.comments(t).threads,backlinksAs:`whiteboard`,state:(e,t,n)=>({extra:{pending:aj(e.whiteboards,t,n).pending}}),onFilesChanged:(e,t,n,r)=>{let{pages:i,scenes:a}=ij(r);(i||r.length===0)&&e.whiteboards.pagesChanged(t);let o=r.length===0?e.whiteboards.pages(t).map(e=>e.id):a;for(let n of o)e.whiteboards.fileChanged(t,n);r.includes(`comments.json`)&&e.whiteboardComments.sync(t)},clientMessages:{"whiteboard-update":rA,"whiteboard-pages":aA},check:nA,flushForPublish:(e,t)=>e.whiteboards.flush(t),publishFiles:()=>lA(),pull:{generated:()=>[oA]},publish:fA,review:pA,routes:[ej,rj,qA,JA,XA,ZA,QA],resolveFile:ft,ownPage:(e,t,n,r,i)=>i&&n===`embed.html`?cA(r(`ryugi-whiteboard-embed.js`)):void 0,isPage:e=>e.endsWith(`.html`),keepsLocal:e=>e===wi},verify:$k,slides:Dw,report:km,storyboard:zO},sj=md,cj={csp:Hc,origins:Vc,portFile:`.last-board-port`,route:Uc},lj={renderSymbol:lu,symbolRequest:au},uj=new Map([...we.flatMap(e=>{let{review:t}=oj[e];return t?[[e,t]]:[]}),[`preview`,sj.review]]),dj=e=>new Map(we.flatMap(t=>Object.entries(e(oj[t])??{}))),fj=dj(e=>e.clientMessages),pj=dj(e=>e.socketMessages),mj=e=>we.filter(t=>e(oj[t])).join(`|`),hj=`[a-z0-9][a-z0-9-]*`,gj=RegExp(`^(${mj(e=>e.mergeRemote)})/`),_j=RegExp(`^(?:${mj(e=>e.threads)}|preview)/${hj}$`),vj=RegExp(`^(?:${mj(e=>e.opensOnRegister)})/${hj}$`),yj=RegExp(`(?:^|/)(${we.join(`|`)})/([\\w-]+)`),bj=/^\/preview\/([a-z0-9][a-z0-9-]{0,63})\/?$/,xj=/^\/c\/([^/]+)\//,Sj=/^\/relay\/a\/([\w-]{1,64})$/,Cj=e=>{try{return d.default.realpathSync(p.default.resolve(e))}catch{return null}};function wj(e){let{index:t,loopback:n,memories:r,mountOf:i,ordered:a,port:o,ready:s,registered:c,token:l}=e,u=e=>{let t=e.searchParams.get(`key`);return n||t!==null&&I(t,l)},f=(e,t)=>u(t)||(e.headers.cookie??``).split(`;`).some(e=>I(e.trim(),`ryugi_artifacts_${o}=${l}`)),m=(e,t)=>e.headers.origin===void 0&&u(t),h=(e,t)=>{let n=e.headers[`x-ryugi-project`];if(typeof n!=`string`||!m(e,t))return null;let r=C(n),i=r===null?null:Cj(r);return i&&c(i)?i:null},g=e=>e.startsWith(`/api/preview-dev/`)||bj.test(e),_=(e,t=e.pathname)=>{if(!g(t))return null;let n=e.searchParams.get(`project`);if(!n)return null;let r=Cj(n);return r&&c(r)?r:null},v=(e,t)=>{try{let{artifacts:n}=Gr(p.default.join(e,`.ryugi`,`config.json`)).config;return Object.values(n).some(e=>e.cloud?.id===t)}catch{return!1}},y=e=>{for(let[t,n]of s)if(n.served().has(e))return t;return a().find(t=>v(t.dir,e))?.dir??null},b=e=>{let n=xj.exec(e);if(n){for(let[e,t]of r)if(t.contentToken===n[1])return e;return null}let i=Sj.exec(e);if(i)return y(i[1]);let o=bj.exec(e);if(o){let e=o[1];return a().find(t=>d.default.existsSync(p.default.join(t.dir,`.ryugi`,`preview`,e,`preview.json`)))?.dir??null}let s=yj.exec(e);if(s){let e=t.owners(s[1],s[2]);return e.length>1?{artifact:`${s[1]}/${s[2]}`,projects:e}:e[0]??y(s[2])}return null},x=e=>{let t=e===null?null:b(e);return typeof t==`string`?t:null},S=e=>{try{let t=new URL(e.headers.referer??``);return t.host===e.headers.host?_(t)??x(C(t.pathname)):null}catch{return null}},C=e=>{try{return decodeURIComponent(e)}catch{return null}};return{authorized:f,decode:C,fromAgent:m,route:async(e,t,n)=>{let r=t.searchParams.get(`at`),o=h(e,t)??_(t,n)??x(r&&C(r));if(o)return i(o);let s=b(n);if(s!==null&&typeof s!=`string`)return s;let c=s??S(e)??a()[0]?.dir??null;return c?i(c):null}}}const Tj=/^\/api\/hub\/(?:stop|restart|upgrade|log)$/;function Ej(e){return new Promise((t,n)=>{let r=0,i=[];e.on(`data`,t=>{r+=t.length,r>65536?(n(/* @__PURE__ */ Error(`body too large`)),e.destroy()):i.push(t)}),e.on(`end`,()=>{try{t(JSON.parse(Buffer.concat(i).toString(`utf8`)||`{}`))}catch{n(/* @__PURE__ */ Error(`body is not JSON`))}}),e.on(`error`,n)})}function Dj(e){let{authorized:t,feed:n,fromAgent:r,options:i,ordered:a,policy:o,register:s,remove:c}=e,l=e=>{try{let t=d.default.openSync(i.paths.log,`r`);try{let n=d.default.fstatSync(t).size,r=Math.min(n,262144),i=Buffer.alloc(r);d.default.readSync(t,i,0,r,n-r);let a=i.toString(`utf8`).split(`
498
- `).filter(Boolean);return r<n&&a.shift(),a.filter(t=>!e||t.includes(e)).slice(-500)}finally{d.default.closeSync(t)}}catch{return[]}};return{handleControl:(e,t,n)=>{let r=n.pathname.slice(9);if(r===`log`){e.method===`GET`?B(t,200,{lines:l(n.searchParams.get(`project`))}):z(t,405,`Method not allowed`);return}let a=i.control;e.method===`POST`?a?r===`stop`?(B(t,202,{stopping:!0}),setImmediate(a.stop)):r===`upgrade`&&!i.latest?.()?B(t,409,{error:`up to date`}):a.relaunch(r===`upgrade`)?B(t,202,{restarting:!0}):B(t,409,{error:`cannot relaunch`}):z(t,409,`Not available`):z(t,405,`Method not allowed`)},handleHubApi:async(e,i,l)=>{if(l.pathname===`/api/agent/subscribe`){if(!r(e,l))return z(i,403,`Forbidden: agent calls need ?key=`),!0;if(e.method!==`POST`)return z(i,405,`Method not allowed`),!0;let{host:t,session:a,project:o,artifact:s}=await Ej(e);if(typeof t!=`string`||!E.test(t)||typeof a!=`string`||!D.test(a)||typeof o!=`string`||typeof s!=`string`||!_j.test(s))return B(i,400,{error:`needs {host, session, project, artifact}`}),!0;let c=Cj(o);return c?(n.subscribe(t,a,c,s),B(i,200,{subscribed:!0}),!0):(B(i,404,{error:`no such project directory`}),!0)}if(l.pathname!==`/api/hub/projects`)return!1;let u=e.method===`DELETE`&&e.headers.origin!==void 0&&t(e,l)&&un(o,e.headers.origin);if(!r(e,l)&&!u)return z(i,403,`Forbidden: agent calls need ?key=`),!0;if(e.method===`GET`)return B(i,200,{projects:a()}),!0;let d=await Ej(e);if(typeof d.dir!=`string`)return B(i,400,{error:`needs {dir}`}),!0;if(e.method===`POST`){let e=typeof d.openCmd==`string`&&d.openCmd?d.openCmd:void 0,t=d.open===!0?{artifact:null,openCmd:e}:typeof d.open==`string`&&vj.test(d.open)?{artifact:d.open,openCmd:e}:void 0,n=await s(d.dir,t);B(i,200,{project:n.dir,root:pr(n.dir)})}else e.method===`DELETE`?(await c(d.dir),B(i,200,{removed:!0})):z(i,405,`Method not allowed`);return!0}}}const Oj={claude:`Claude Code`,codex:`Codex`,antigravity:`Antigravity`};function kj(e,t){return e.harness===`claude`?t.find(t=>t.host===`claude`&&t.id===e.sessionId)?.id??null:t.filter(t=>t.host===e.harness).sort((e,t)=>t.since-e.since)[0]?.id??null}const Aj=e=>e.kind!==`none`&&e.kind!==`login`,jj=e=>e.kind===`quiet`||e.kind===`command`&&e.stuck===!0,Mj=(e,t)=>e&&e.kind===t.kind&&e.line===t.line?{...t,since:e.since}:t;function Nj(e,t,n){let{observation:r,hookState:i,now:a}=t,o={kind:`none`,since:a};if(!r||r.state!==`running`)return o;let s=r.transcript?.error;if(s?.kind===`authentication_failed`)return{kind:`login`,since:s.at,line:s.text};if(s)return{kind:`error`,since:s.at,line:s.text};if(i===`your-turn`)return o;let c=r.screen;if(c?.login)return{kind:`login`,since:a,line:c.lastLine};if(c?.menu&&n&&!c.busy)return{kind:`menu`,since:a,line:c.menu.line,options:c.menu.options};let l=r.transcript?.pendingTool;if(l)return{kind:`command`,since:l.since,line:l.name,stuck:a-l.since>=6e5};let u=Math.max(e.hashSince,e.mtimeSince,t.hookAt);return i!==null&&a-u>=18e4?{kind:`quiet`,since:u,line:c?.lastLine??``}:o}function Pj(e,t){let n=t.observation?.screen?.hash??null,r=t.observation?.transcriptMtime??null,i={attention:e?.attention??{kind:`none`,since:t.now},hash:n,hashSince:e&&e.hash===n?e.hashSince:t.now,mtime:r,mtimeSince:e&&e.mtime===r?e.mtimeSince:t.now},a=e!==void 0&&e.hash===n,o=Mj(e?.attention,Nj(i,t,a));return{attention:o,memory:{...i,attention:o}}}const Fj={kind:`none`,since:0},Ij=(e,t)=>(e??Fj).kind===`none`&&(t??Fj).kind===`none`||JSON.stringify(e??Fj)===JSON.stringify(t??Fj);function Lj(e){let t=e?.sessions;return Array.isArray(t)?t.flatMap(e=>e&&typeof e.taskId==`string`&&typeof e.artifact==`string`&&typeof e.projectDir==`string`?[{taskId:e.taskId,artifact:e.artifact,projectDir:e.projectDir,harness:String(e.harness??``),sessionId:typeof e.sessionId==`string`?e.sessionId:null,state:String(e.state??``)}]:[]):[]}function Rj(e){let t=/* @__PURE__ */ new Map,n=!1,r=(e,t,n)=>t?t.state===`your-turn`?!e?.observedAt||n-e.observedAt>=6e4:n-t.at>=15e3:!0,i=(t,n)=>{let r=t.memory?.attention;t.memory=n,Ij(r,n.attention)||e.onChange(t.task.projectDir)},a=async(t,n,r)=>{let a=await e.call(`sessions.observe`,{sessionId:t.task.taskId}).catch(()=>null);t.observedAt=r,i(t,Pj(t.memory,{hookState:n?.state??null,hookAt:n?.at??0,observation:a,now:r}).memory)};return{async tick(){let o;try{o=await e.call(`sessions.local`,{}),n=!0}catch(e){throw n=!1,e}let s=Lj(o),c=e.now(),l=/* @__PURE__ */ new Set;for(let n of s){if(n.state!==`running`)continue;l.add(n.taskId);let o=t.get(n.taskId)??{task:n,observedAt:0};o.task=n,t.set(n.taskId,o);let s=await e.hookFor(n);s?.state===`your-turn`&&o.memory&&![`login`,`error`].includes(o.memory.attention.kind)&&i(o,{...o.memory,attention:{kind:`none`,since:c}}),r(o,s,c)&&await a(o,s,c)}for(let[n,r]of t)l.has(n)||(t.delete(n),r.memory&&r.memory.attention.kind!==`none`&&e.onChange(r.task.projectDir))},attention(n){return t.get(n)?.memory?.attention??{kind:`none`,since:e.now()}},async input(n,r,a){let o=t.get(n),s=o?.memory?.attention??Fj;if(r.kind===`text`&&!Aj(s))throw Error(`the agent is not waiting for a reply`);if(r.kind===`interrupt`&&!jj(s))throw Error(`the agent does not look stuck`);if(r.kind===`option`&&!s.options?.some(e=>e.key===r.key))throw Error(`that choice is not on the menu`);if(await e.call(`sessions.input`,{sessionId:n,...r,...`device`in a?{deviceId:a.device}:{local:!0}}),o?.memory){let t=e.now();i(o,{...o.memory,attention:{kind:`none`,since:t},hashSince:t,mtimeSince:t})}},available:()=>n,entries(n){return[...t.values()].filter(e=>e.task.projectDir===n).map(({task:t,memory:n})=>({artifact:t.artifact,taskId:t.taskId,harness:t.harness,state:t.state,sessionId:t.sessionId,attention:n?.attention??{kind:`none`,since:e.now()}}))}}}function zj(e,t){return async n=>{let r=n.harness===`claude`?`claude`:`codex`,i=r===`claude`?n.sessionId:kj({harness:`codex`,sessionId:null},t(n.projectDir).filter(e=>e.artifacts.includes(n.artifact)));if(!i)return null;let a=e.lookup(r,i);return a?{at:a.lastAt,state:a.state}:null}}function Bj(e){let t=typeof e==`object`&&e?e:{};if(t.kind===`interrupt`)return{kind:`interrupt`};if(t.kind===`option`&&typeof t.key==`string`)return{kind:`option`,key:t.key};if(t.kind===`text`&&typeof t.text==`string`)return{kind:`text`,text:t.text};throw Error(`a reply is text, a menu option or an interrupt`)}const Vj=/* @__PURE__ */ new Set([`agent-sessions`,`agent-screen`,`agent-input`]),Hj=e=>{let t=e?.op;return typeof t==`string`&&Vj.has(t)};function Uj(e){let t=async t=>{let n=e.bridge.entries(e.dir).find(e=>e.artifact===t)??await e.task(t);if(!n)throw Error(`no daemon session works on this artifact`);return n};return{available:()=>e.bridge.available(),entries:()=>e.bridge.entries(e.dir),request:async(n,r,i)=>{let a=r?.op;if(a===`agent-sessions`)return e.panel(n);if(!i)throw Error(`only this computer can see or answer the terminal from here`);if(a===`agent-screen`)return e.screen((await t(n)).taskId);if(a===`agent-input`)return await e.bridge.input((await t(n)).taskId,Bj(r),{local:!0}),{sent:!0};throw Error(`unknown agent request`)}}}const Wj=/* @__PURE__ */ new Set([`queued`,`running`,`starting`]);function Gj(e){let{daemon:t,sessions:n}=e,r=/* @__PURE__ */ new Set,i=async({dir:r,key:i,deviceId:a})=>{let o=n.get(r,i);if(e.liveSession(r,i,o)||o&&(await t.call(`sessions.list`,{deviceId:a}))?.sessions?.some(e=>e.taskId===o.taskId&&Wj.has(e.state??``)))return`live`;if(o?.harness===`claude`&&o.sessionId){let e=await t.call(`sessions.resume`,{deviceId:a,taskId:o.taskId,sessionId:o.sessionId,projectDir:r,artifact:i,harness:`claude`});return n.set(r,i,{...o,taskId:e?.taskId??o.taskId,sessionId:e?.sessionId??o.sessionId}),`resumed`}let s=o?.harness??e.lastHarness(r)??`claude`,c=await t.call(`tasks.start`,{deviceId:a,projectDir:r,harness:s,artifact:i,reason:`comment`});return c?.taskId&&n.set(r,i,{origin:`daemon`,taskId:c.taskId,sessionId:c.sessionId??null,harness:s}),`started`};return{async onHumanInput(e){let t=`${e.dir}\0${e.key}`;if(r.has(t))return`busy`;r.add(t);try{return await i(e)}catch{return`refused`}finally{r.delete(t)}}}}function Kj(e){let t=()=>{try{return JSON.parse(d.default.readFileSync(e(),`utf8`))}catch{return{}}};return{get(e,n){return t()[e]?.[n]??null},set(n,r,i){let a=t();U(e(),{...a,[n]:{...a[n],[r]:i}})}}}function qj(e){let{agentDirectory:t,mountOf:n,options:r,ready:i}=e,a=r.paths.projects,o=p.default.join(p.default.dirname(a),`daemon-harness.json`),s=()=>{try{let e=JSON.parse(d.default.readFileSync(o,`utf8`));return Object.fromEntries(Object.entries(e).filter(e=>nl(e[1])))}catch{return{}}},c=wt(r.daemonSocket??Ct()),l=Kj(()=>p.default.join(p.default.dirname(a),`daemon-sessions.json`)),u=Gj({daemon:c,sessions:l,lastHarness:e=>s()[e],liveSession:(e,n,r)=>r?.sessionId&&t.lookup(r.harness,r.sessionId)?!0:!!i.get(e)?.agentSessions().some(e=>e.artifacts.includes(n))}),f=async(e,t)=>{let n=l.get(e,t);if(!n)return null;let r=(await c.call(`sessions.local`,{}).catch(()=>null))?.sessions?.find(e=>e.taskId===n.taskId)?.state??`ended`;return{taskId:n.taskId,harness:n.harness,sessionId:n.sessionId,state:r}},m=async(e,r,i)=>{let a=(await n(e)).agentSessions().filter(e=>e.artifacts.includes(r)).map(e=>({agent:e.agent,host:e.host,id:e.id,state:e.state,since:e.since,turn:t.lookup(e.host,e.id)?.turn??null})),o=await f(e,r);return{agents:a,daemon:o?{...o,attention:g.attention(o.taskId)}:null,trusted:i}},h=async(e,t,n)=>{if(!n)throw Error(`the terminal opens only on a trusted device`);let r=await f(e,t);if(!r)throw Error(`no daemon session works on this artifact`);return c.call(`sessions.screen`,{deviceId:n,sessionId:r.taskId})},g=Rj({call:c.call,hookFor:zj(t,e=>i.get(e)?.agentSessions()??[]),now:Date.now,onChange:e=>i.get(e)?.publishAgentStatus()}),_=setInterval(()=>void g.tick().catch(()=>{}),r.relay?.pollMs??5e3);return _.unref?.(),{agentInput:async(e,t,n,r)=>{if(!r)throw Error(`replies come only from a trusted device`);let i=await f(e,t);if(!i)throw Error(`no daemon session works on this artifact`);return await g.input(i.taskId,Bj(n),{device:r}),{sent:!0}},agentPanel:m,agentScreen:h,daemonClient:c,deviceTrusted:async e=>e!==void 0&&((await c.call(`devices.check`,{deviceId:e}).catch(()=>null))?.trusted??!1),harnessFile:o,portFor:e=>Uj({dir:e,bridge:g,panel:t=>m(e,t,!0),task:t=>f(e,t),screen:e=>c.call(`sessions.screen`,{local:!0,sessionId:e})}),readHarness:s,resumer:u,sessionRecord:l,stop:()=>clearInterval(_)}}const Jj=(e,t)=>`${e}:${t}`,Yj=(e,t)=>`${e}\n${t}`;function Xj(e,t){try{let n=JSON.parse(d.default.readFileSync(e,`utf8`));return n&&typeof n==`object`?n:t}catch{return t}}function Zj(e,t=Date.now){let n=p.default.join(e,`agent-subscriptions.json`),r=p.default.join(e,`agent-deliveries.json`),i=Xj(n,{}),a=Xj(r,{}),o=()=>U(n,i),s=()=>U(r,a);return{subscribe(e,n,r,a){let s=i[Jj(e,n)]??={items:[],lastSeen:t()};s.lastSeen=t(),s.items.some(e=>e.project===r&&e.artifact===a)||s.items.push({project:r,artifact:a}),o()},unsubscribe(e,t){let n=Jj(e,t),r=n in i||n in a;delete i[n],delete a[n],r&&(o(),s())},subscriptions(e,t){return(i[Jj(e,t)]?.items??[]).map(e=>({...e}))},subscribers(e,t){return Object.entries(i).filter(([,n])=>n.items.some(n=>n.project===e&&n.artifact===t)).map(([e])=>{let t=e.indexOf(`:`);return{host:e.slice(0,t),session:e.slice(t+1)}})},seen(e,n){let r=i[Jj(e,n)];r&&(r.lastSeen=t(),o())},delivered(e,t,n,r){return a[Jj(e,t)]?.[Yj(n,r)]??null},saveDelivered(e,t,n,r,i){(a[Jj(e,t)]??={})[Yj(n,r)]=i,s()},sweep(e){let n=!1;for(let[r,o]of Object.entries(i)){let s=r.indexOf(`:`);e(r.slice(0,s),r.slice(s+1))||t()-o.lastSeen<864e5||(delete i[r],delete a[r],n=!0)}n&&(o(),s())}}}async function Qj(e){let{mountOf:t,options:n,ready:r}=e,i=/* @__PURE__ */ new Map,a=Zj(n.paths.home),o=null,s=Rn({store:a,send:(e,t)=>o?.send(e,t),watch:(e,n)=>{if(!d.default.existsSync(pr(e)))return()=>{};let r,i=!1;return t(e).then(e=>{i||(r=e.watch(n))}).catch(()=>void 0),()=>{i=!0,r?.()}},delivered:(e,t,n,i,a)=>r.get(e)?.deliverThreads(t,n,i,a),listening:(e,t)=>xs(p.default.join(pr(e),`.state`),t)}),c;if(n.agentSocket){let e=n.agentSocket,t=!1,r=()=>j({socketPath:e,version:n.version,onHello:e=>s.hello(e),onDelivered:(e,t)=>s.ack(e,t.id),onUnsubscribe:e=>s.unsubscribe(e),onClose:e=>s.close(e)}).catch(e=>(t||console.error(JSON.stringify({type:`agent-channel`,event:`error`,message:e.message})),t=!0,null));if(o=await r(),!o){let e=!1;c=setInterval(async()=>{e||o||(e=!0,o=await r(),e=!1,o&&clearInterval(c))},n.agentSocketRetryMs??3e4),c.unref()}}return{attach:e=>{i.set(e,Cs(p.default.join(pr(e),`.state`),{subscribe:(t,n,r)=>s.subscribe(t,n,e,r),subscribed:(t,n,r)=>a.subscriptions(t,n).some(t=>t.project===e&&t.artifact===r)}))},close:async()=>{clearInterval(c),s.closeAll(),await o?.close();for(let e of i.values())e()},feed:s,feedStore:a}}const $j=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`),eM=e=>String(e).padStart(2,`0`);function tM(e){return`${e.getUTCFullYear()}${eM(e.getUTCMonth()+1)}${eM(e.getUTCDate())}-${eM(e.getUTCHours())}${eM(e.getUTCMinutes())}`}const nM=()=>Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(4)),e=>`abcdefghijkmnpqrstuvwxyz23456789`[e%32]).join(``),rM=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);function iM(e,t){let n=(e.toLowerCase().match(/[a-z0-9]+/g)??[]).slice(0,5);return[`task`,tM(t),...n,nM()].join(`-`)}function aM(e,t){return{slug:iM(rM(e)[0]??``,t),xml:`<doc></doc>
499
- `}}function oM(e,t){let n=rM(e),r=n[0]??``,i=iM(r,t),a=`新任务:${[...r].length>40?`${[...r].slice(0,40).join(``)}…`:r}`,o=n.map(e=>` <p>${$j(e)}</p>`).join(`
500
- `);return{slug:i,title:a,xml:`<doc>\n <h1>${$j(a)}</h1>\n <h2>需求</h2>\n${o}\n</doc>\n`}}function sM(e){let{daemon:t}=e,n=async e=>{if(!(await t.call(`devices.check`,{deviceId:e}))?.trusted)throw Error(`device not trusted by this machine`)};return{async info(){let n;try{n=await t.call(`status`,{})??{}}catch{return null}let r=e.lastHarness();return{hostId:e.hostId,name:e.name,daemon:!0,remote:n.remote===!0,sessions:n.sessions??0,queued:n.queued??0,projects:e.projects().map(({name:e,dir:t})=>r[t]?{name:e,lastHarness:r[t]}:{name:e})}},async handle(r){let{deviceId:i}=r;switch(r.op){case`sessions.list`:return t.call(`sessions.list`,{deviceId:i});case`sessions.screen`:return t.call(`sessions.screen`,{deviceId:i,sessionId:r.sessionId});case`tasks.create`:{await n(i);let a=e.projects().find(e=>e.name===r.project);if(!a)throw Error(`no project ${r.project} on this machine`);let o=await t.call(`status`,{}).catch(()=>null)??{},s=Array.isArray(o.features)&&o.features.includes(`task-prompt`)?await cl.taskPrompt({text:r.text,content:r.content,harness:r.harness,at:Date.now()}).catch(e=>{throw Error(`document engine unavailable: ${e.message}`)}):void 0,c=await e.createTask(a.dir,{text:r.text,...s?{prompt:s}:{}}),l=await t.call(`tasks.start`,{deviceId:i,projectDir:a.dir,harness:r.harness,artifact:c.artifact,...s?{prompt:s.markdown}:{}});return e.rememberHarness(a.dir,r.harness),l?.taskId&&e.recordSession(a.dir,c.artifact,{origin:`daemon`,taskId:l.taskId,sessionId:l.sessionId??null,harness:r.harness}),{...c,state:l?.state===`queued`?`queued`:`starting`}}}}}}function cM(e,t,n){let r=/* @__PURE__ */ new Map;for(let i of e){let e=t(i);r.has(e)||r.set(e,{name:e,dir:n(i)})}return[...r.values()]}async function lM(e,t,{waitMs:n=8e3,stepMs:r=400}={}){let i=()=>e.cloudLinkFor(`document`,t).catch(()=>null),a=await i();if(a)return a;await e.handleRelay(`document/${t}`,{op:`publish`},`daemon`).catch(()=>null);for(let a=0;a<n;a+=r){await new Promise(e=>setTimeout(e,r));let n=await i();if(n)return n;let a=await e.handleRelay(`document/${t}`,{op:`publication`},`daemon`).catch(()=>null);if(!a||a.phase===`failed`||a.phase===`not-ready`)return null}return null}async function uM(e,t,n,r,i){let{slug:a,xml:o}=t.prompt?aM(t.text,n):oM(t.text,n);xi(e,`document`,a);let s=p.default.join(e,`document`,a);return t.prompt&&al(s,t.prompt),d.default.writeFileSync(p.default.join(s,`doc.xml`),o,{flag:`wx`}),{artifact:`document/${a}`,url:await lM(r,a,i)}}function dM(e){let t=p.default.join(p.default.dirname(e),`host-id`),n=te(t);if(/^[\w-]{16,64}$/.test(n))return n;let r=F();return d.default.mkdirSync(p.default.dirname(t),{recursive:!0,mode:448}),d.default.writeFileSync(t,`${r}\n`,{mode:384}),r}const fM=/^(?:[^@/]+@)?[^:/]+:(?!\/)(.+)$/;function pM(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))try{let t=new URL(e);return t.protocol===`file:`?null:t.pathname}catch{return null}return fM.exec(e)?.[1]??null}function mM(e){let t=pM(e.trim());if(!t)return null;let n=t.replace(/\.git\/?$/,``).split(`/`).filter(Boolean);return n.length<2?null:n.join(`/`).toLowerCase()}function hM(e){try{return mM((0,l.execFileSync)(`git`,[`-C`,e,`remote`,`get-url`,`origin`],{encoding:`utf8`,timeout:2e3,stdio:[`ignore`,`pipe`,`ignore`],env:{...process.env,GIT_TERMINAL_PROMPT:`0`}}))??p.default.basename(e)}catch{return p.default.basename(e)}}function gM(){if(process.platform===`darwin`)try{let e=(0,l.execFileSync)(`scutil`,[`--get`,`ComputerName`],{encoding:`utf8`,timeout:1e3}).trim();if(e)return e}catch{return f.default.hostname().replace(/\.local$/,``)}return f.default.hostname().replace(/\.local$/,``)}function _M(e){let{closing:t,mountOf:n,options:r,ordered:i,refreshRelay:a,register:o,registered:s}=e,{daemonClient:c,harnessFile:u,readHarness:d,sessionRecord:f}=e.agents,m=/* @__PURE__ */ new Map,h=e=>{let t=m.get(e);if(t)return t;try{let n=(0,l.execFileSync)(`git`,[`-C`,e,`rev-parse`,`--path-format=absolute`,`--git-common-dir`],{encoding:`utf8`,timeout:2e3,stdio:[`ignore`,`pipe`,`ignore`]}).trim();t=p.default.basename(n)===`.git`?p.default.dirname(n):e}catch{t=e}return m.set(e,t),t},g=/* @__PURE__ */ new Map,_=e=>{let t=g.get(e);return t||g.set(e,t=hM(e)),t},v=r.relay&&r.cloud?sM({daemon:c,recordSession:(e,t,n)=>f.set(e,t,n),hostId:dM(r.cloud.credentialsFile),name:gM(),projects:()=>cM(i().map(e=>e.dir),_,h),lastHarness:d,rememberHarness:(e,t)=>U(u,{...d(),[e]:t}),createTask:async(e,t)=>(s(e)||await o(e),uM(pr(e),t,/* @__PURE__ */ new Date,await n(e),r.taskLinkWait))}):null,y=null,b=async()=>{v&&!t()&&(y=await v.info(),a())},x=v?setInterval(()=>void b(),r.relay?.pollMs??5e3):void 0;return x?.unref?.(),{handler:v,info:()=>y,stop:()=>clearInterval(x)}}const vM=e=>u.default.createHash(`sha256`).update(e).digest(`hex`).slice(0,16);function yM(e,t=process.platform,n=f.default.tmpdir(),r=process.getuid?.()??0){if(t===`win32`)return`\\\\.\\pipe\\ryugi-document-engine-${vM(e)}`;let i=p.default.posix.join(e,`document-engine.sock`);return Buffer.byteLength(i)<=103?i:p.default.posix.join(n,`ryugi-${r}`,`document-engine-${vM(e)}.sock`)}function bM(e){let t=d.default.lstatSync(e),n=process.getuid?.();if(!t.isDirectory()||n!==void 0&&t.uid!==n||t.mode&18)throw Error(`the document engine socket directory ${e} is not private`)}function xM(e,t){let n=Buffer.from(JSON.stringify(e),`utf8`),r=t?.length??0,i=Buffer.allocUnsafe(8+n.length+r);return i.writeUInt32BE(4+n.length+r,0),i.writeUInt32BE(n.length,4),n.copy(i,8),t?.length&&i.set(t,8+n.length),i}function SM(e,t={}){let n=t.maxFrameBytes??268435456,r=Buffer.alloc(0);return t=>{for(r=r.length?Buffer.concat([r,t]):t;r.length>=4;){let t=r.readUInt32BE(0);if(t>n)throw Error(`frame of ${t} bytes is too large`);if(r.length<4+t)return;let i=r.readUInt32BE(4);if(i>t-4)throw Error(`frame header is longer than its frame`);let a=JSON.parse(r.toString(`utf8`,8,8+i)),o=t-4-i?new Uint8Array(r.subarray(8+i,4+t)):null;r=r.subarray(4+t),e(a,o)}}}const CM=`$tail`;function wM(e,t){if(e instanceof Uint8Array){if(t.bytes)throw Error(`a message can carry one binary value`);return t.bytes=e,{[CM]:!0}}if(Array.isArray(e))return e.map(e=>wM(e,t));if(e&&typeof e==`object`){let n={};for(let[r,i]of Object.entries(e))n[r]=wM(i,t);return n}return e}function TM(e,t){if(Array.isArray(e))return e.map(e=>TM(e,t));if(e&&typeof e==`object`){if(e[CM]===!0)return t;let n={};for(let[r,i]of Object.entries(e))n[r]=TM(i,t);return n}return e}function EM(e){let t={bytes:null},n=wM(e,t);return t.bytes?{header:n,tail:t.bytes}:{header:n}}function DM(e,t){return t?TM(e,t):e}const OM=3e3,kM=(e,t)=>({...t,summary:t.summary??e.summary}),AM=e=>new Promise(t=>setTimeout(t,e));function jM(e){return new Promise(t=>{let n=m.default.connect(e);n.once(`connect`,()=>{n.removeAllListeners(`error`),t(n)}),n.once(`error`,()=>t(null))})}function MM(e){let t=null,n=null,r=0,i=0,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=e=>e.name===`OutdatedClient`?new Ol(e.message):Error(e.message),c=e=>{if(e.op===`reply`){let t=a.get(e.rid);if(!t)return;if(a.delete(e.rid),!e.ok){t.reject(s(e.error));return}if(e.mirror&&t.sid){let n=o.get(t.sid);n&&(n.mirror=kM(n.mirror,e.mirror))}t.resolve(e.mirror&&!t.sid?e.mirror:e.value);return}let t=o.get(e.sid);t&&(e.op===`log`?t.log?.(e.line):(t.mirror=kM(t.mirror,e.mirror),t.listeners.forEach(t=>t(e.event))))},u=(e,t)=>{let{header:n,tail:r}=EM(t);e.write(xM(n,r))},f=(e,t,n)=>new Promise((i,o)=>{let s=++r;a.set(s,{resolve:i,reject:o,sid:n,socket:e}),u(e,{...t,rid:s})}),m=e=>{for(let[t,n]of a)n.socket===e&&(a.delete(t),n.reject(/* @__PURE__ */ Error(`the document process stopped; reload the page`)));if(n?.socket!==e)return;n=null,t=null;let r=[...o.values()];o.clear(),r.forEach(e=>e.onLost?.())},h=e=>{let t=SM((e,t)=>c(DM(e,t)));e.on(`data`,n=>{try{t(n)}catch{e.destroy()}}),e.on(`error`,()=>void 0),e.once(`close`,()=>m(e))},g=()=>{let t=e.logFile?d.default.openSync(e.logFile,`a`):`ignore`;(0,l.spawn)(process.execPath,[e.engineFile,`--socket`,e.socketPath,`--version`,e.version,...e.engineIdleMs===void 0?[]:[`--idle-ms`,String(e.engineIdleMs)]],{detached:!0,stdio:[`ignore`,t,t],windowsHide:!0}).unref(),typeof t==`number`&&d.default.closeSync(t)},_=async(t,n)=>{let r=f(t,{op:`hello`,v:1,version:e.version}),i,a=new Promise((r,a)=>{i=setTimeout(()=>{t.destroy(),a(/* @__PURE__ */ Error(`the document engine at ${e.socketPath} did not answer`))},Math.max(0,n-Date.now()))});try{return await Promise.race([r,a])}finally{clearTimeout(i)}},v=async e=>{let t=new Promise(t=>e.once(`close`,t));await Promise.race([f(e,{op:`shutdown`}).catch(()=>void 0),t,AM(OM)]),await Promise.race([t,AM(OM)]),e.destroy()},y=async()=>{let t=Date.now()+(e.connectTimeoutMs??1e4),r=!1;for(;Date.now()<t;){let i=p.default.dirname(e.socketPath);!e.socketPath.startsWith(`\\\\`)&&d.default.existsSync(i)&&bM(i);let a=await jM(e.socketPath);if(!a){r||=(g(),!0),await AM(50);continue}h(a);let o=await _(a,t);if(o.version===e.version)return n={pid:o.pid,socket:a},n;await v(a),r=!1}throw Error(`the document engine did not start at ${e.socketPath}`)},b=()=>(t??=y().catch(e=>{throw t=null,e}),t),x,S=()=>{if(clearTimeout(x),o.size>0||!n)return;let t=n;x=setTimeout(()=>{o.size===0&&n===t&&t.socket.end()},e.idleMs??6e4),x.unref()},C=async(e,t)=>f((await b()).socket,e,t),w=(e,t,n=[])=>C({op:`call`,sid:e,method:t,args:n},e),T=(e,t,r=[])=>{n&&u(n.socket,{op:`cast`,sid:e,method:t,args:r})};return{pid:()=>n?.pid??null,checkCharts:async e=>{clearTimeout(x);try{return await C({op:`charts`,sources:e})}finally{S()}},trees:async e=>{clearTimeout(x);try{return await C({op:`trees`,xmls:e})}finally{S()}},taskPrompt:async e=>{clearTimeout(x);try{return await C({op:`taskPrompt`,input:e})}finally{S()}},read:async(e,t)=>{clearTimeout(x);try{return await C({op:`read`,file:e,root:t})}finally{S()}},open:async({log:e,onLost:t,...n})=>{clearTimeout(x);let r=String(++i),a=await C({op:`open`,sid:r,...n}),s={listeners:/* @__PURE__ */ new Set,log:e,mirror:a,onLost:t};o.set(r,s);let c=()=>o.get(r)?.mirror??s.mirror;return{summary:()=>c().summary,outcome:()=>c().outcome,streaming:()=>c().streaming,agentActiveAt:()=>c().agentActiveAt,lineage:()=>c().lineage,snapshot:async()=>await w(r,`snapshot`),importUpdate:async(e,t)=>{await w(r,`importUpdate`,t===void 0?[e]:[e,t])},changesSince:async e=>await w(r,`changesSince`,[e]),flush:async()=>{await w(r,`flush`)},settled:async()=>{await w(r,`settled`)},close:async()=>{await w(r,`close`).catch(()=>void 0),o.delete(r),S()},onFileText:e=>T(r,`onFileText`,[e]),refreshRefs:()=>T(r,`refreshRefs`),subscribe:e=>(s.listeners.add(e),()=>s.listeners.delete(e))}},close:async()=>{clearTimeout(x);let e=n;e&&(o.clear(),await v(e.socket))}}}const NM=(e,t,{publish:n=!1}={})=>{let r=oj[e.type];return(n&&r.preparePublish||r.prepare)?.(t,e.id).catch(()=>void 0)};function PM(e,t,n,r){let i=`${t.type}/${t.id}`;e.autoPublisher?.changed(i),e.runtimeWarnings.delete(i);let a=e.refreshState(t,n),o=lc(JSON.stringify({type:`change`,artifact:i,files:r}));for(let t of e.clients)t.write(o);e.relay?.emit(i,{type:`change`,artifact:i,files:r}),e.direct.emit(i,{type:`change`,artifact:i,files:r}),e.cloud?.changed(i),e.changeListeners.forEach(e=>e(t,a,r))}function FM(e,t){let n=G(t),r=n&&W(e.root,n.type,n.id);!n||!r?e.deckDeps.track(t,[]):(e.slidesComments.deckChanged(n.id),PM(e,n,r,[]),e.touch())}function IM(e,t,n,{force:r=!1}={}){let{root:i,signatures:a,clients:o}=e,s=`${t.type}/${t.id}`,c=W(i,t.type,t.id),l=oj[t.type];if(l.onChangedOrGone?.(e,t.id,n),!c){a.delete(s),e.saveSignatures(),e.deckDeps.track(s,[]),e.autoPublisher?.removed(s);let t=lc(JSON.stringify({type:`change`,artifact:s,files:n}));for(let e of o)e.write(t)}else l.onFilesChanged?.(e,t.id,c,n),(r||a.get(s)!==nr(c,t.type))&&PM(e,t,c,n)}function LM(e,t){let n=`${t.type}/${t.id}`,r=W(e.root,t.type,t.id),i=e.signatures.get(n);return!(r?i===nr(r,t.type):i===void 0)&&(IM(e,t,r&&i!==void 0?rr(r,t.type,i):[]),e.touch(),!0)}function RM(e,t){if(LM(e,t))return!0;let n=W(e.root,t.type,t.id);return n&&!e.fresh.has(`${t.type}/${t.id}`)&&e.refreshState(t,n),!1}function zM(e,t){RM(e,t);let n=W(e.root,t.type,t.id);return n?e.refreshState(t,n):null}function BM(e){let t=er(e.root),n=new Set(t.artifacts.map(e=>`${e.type}/${e.id}`));for(let n of t.artifacts)LM(e,{type:n.type,id:n.id});for(let t of[...e.signatures.keys()]){let r=n.has(t)?null:G(t);r&&LM(e,r)}return t}function VM(e,t){let n=/* @__PURE__ */ new Map;for(let e of t){let t=G(e);if(!t)continue;let r=`${t.type}/${t.id}`,i=n.get(r)??{ref:t,files:[]},a=e.slice(r.length+1);a&&i.files.push(a),n.set(r,i)}for(let{ref:t,files:r}of n.values())IM(e,t,r);e.touch()}var HM=/* @__PURE__ */ o(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),UM=/* @__PURE__ */ o(((e,t)=>{let{websocketMask:n,websocketUnmask:r}=require("http"),{EMPTY_BUFFER:i}=HM(),a=Buffer[Symbol.species];function o(e,t){if(e.length===0)return i;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),r=0;for(let t=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return r<t?new a(n.buffer,n.byteOffset,r):n}function s(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function c(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function l(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function u(e){if(u.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new a(e):ArrayBuffer.isView(e)?t=new a(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),u.readOnly=!1),t}if(t.exports={concat:o,mask:s,toArrayBuffer:l,toBuffer:u,unmask:c},n)t.exports.mask=function(e,t,r,i,a){a<24?s(e,t,r,i,a):n(e,t,r,i,a)},t.exports.unmask=function(e,t){e.length<24?c(e,t):r(e,t)};else if(!process.env.WS_NO_BUFFER_UTIL)try{let e=require("bufferutil");t.exports.mask=function(t,n,r,i,a){a<48?s(t,n,r,i,a):e.mask(t,n,r,i,a)},t.exports.unmask=function(t,n){t.length<32?c(t,n):e.unmask(t,n)}}catch{}})),WM=/* @__PURE__ */ o(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),GM=/* @__PURE__ */ o(((e,t)=>{let n=require("zlib"),r=UM(),i=WM(),{kStatusCode:a}=HM(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!p){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;p=new i(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(/* @__PURE__ */ Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&(typeof e.client_max_window_bits==`number`?t.clientMaxWindowBits>e.client_max_window_bits:!e.client_max_window_bits)));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload?this[d].push(e):(this[f]=/* @__PURE__ */ RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset())}function g(e){this[c]._inflate=null,this[f]?this[u](this[f]):(e[a]=1007,this[u](e))}})),KM=/* @__PURE__ */ o(((e,t)=>{let{isUtf8:n}=require("buffer"),{hasBlob:r}=HM(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require("utf-8-validate");t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),qM=/* @__PURE__ */ o(((e,t)=>{let{Writable:n}=require("stream"),r=GM(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=HM(),{concat:c,toArrayBuffer:l,unmask:u}=UM(),{isValidStatusCode:d,isValidUTF8:f}=KM(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0||e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks?n(this.createError(RangeError,`Too many buffered chunks`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`)):(this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n))}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName])e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));else{if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);n>2**21-1?e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`)):(this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`)):this._state=this._masked?3:4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}this._mask=void 0,this._opcode>7?this.controlMessage(t,e):this._maxFragments>0&&++this._numFragments>this._maxFragments?e(this.createError(RangeError,`Too many message fragments`,!1,1008,`WS_ERR_TOO_MANY_BUFFERED_PARTS`)):this._compressed?(this._state=5,this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e))}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0}else this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),JM=/* @__PURE__ */ o(((e,t)=>{let{Duplex:n}=require("stream"),{randomFillSync:r}=require("crypto"),{types:{isUint8Array:i}}=require("util"),a=GM(),{EMPTY_BUFFER:o,kWebSocket:s,NOOP:c}=HM(),{isBlob:l,isValidStatusCode:u}=KM(),{mask:d,toBuffer:f}=UM(),p=Symbol(`kByteLength`),m=Buffer.alloc(4),h=8192,g,_=h;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=c,this[s]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||m,t.generateMask?t.generateMask(n):(_===h&&(g===void 0&&(g=Buffer.alloc(h)),r(g,0,h),_=0),n[0]=g[_++],n[1]=g[_++],n[2]=g[_++],n[3]=g[_++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[p]!==void 0?s=t[p]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),t.mask?(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],s?o?[l,e]:i?(d(e,n,l,a,s),[l]):(d(e,n,e,0,s),[l,e]):[l]):s?[l,e]:[l]}close(t,n,r,a){let s;if(t===void 0)s=o;else if(typeof t!=`number`||!u(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);if(s=Buffer.allocUnsafe(2+e),s.writeUInt16BE(t,0),typeof n==`string`)s.write(n,2);else if(i(n))s.set(n,2);else throw TypeError(`Second argument must be a string or a Uint8Array`)}let c={[p]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(s,c),a):this.enqueue([this.dispatch,s,!1,c,a])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};l(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};l(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[a.extensionName],i=t.binary?2:1,o=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):l(e)?(s=e.size,c=!1):(e=f(e),s=e.length,c=f.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let u={[p]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};l(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[p],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=/* @__PURE__ */ Error(`The socket was closed while the blob was being read`);process.nextTick(v,this,e,i);return}this._bufferedBytes-=r[p];let a=f(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(y,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let o=this._extensions[a.extensionName];this._bufferedBytes+=r[p],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){let e=/* @__PURE__ */ Error(`The socket was closed while data was being compressed`);v(this,e,i)}else this._bufferedBytes-=r[p],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][p],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][p],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function v(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function y(e,t,n){v(e,t,n),e.onerror(t)}})),YM=/* @__PURE__ */ o(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=HM(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,"target",{enumerable:!0}),Object.defineProperty(f.prototype,"type",{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean!==void 0&&t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,"code",{enumerable:!0}),Object.defineProperty(p.prototype,"reason",{enumerable:!0}),Object.defineProperty(p.prototype,"wasClean",{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,"error",{enumerable:!0}),Object.defineProperty(m.prototype,"message",{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,"data",{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),XM=/* @__PURE__ */ o(((e,t)=>{let{tokenChars:n}=KM();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0){if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`)}else if(l===void 0){if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`)}else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s){if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`)}else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),ZM=/* @__PURE__ */ o(((e,t)=>{let n=require("events"),r=require("https"),i=require("http"),a=require("net"),o=require("querystring"),s=require("tls"),{randomBytes:c,createHash:l}=require("crypto"),{Duplex:u,Readable:d}=require("stream"),{URL:f}=require("url"),p=GM(),m=qM(),h=JM(),{isBlob:g}=KM(),{BINARY_TYPES:_,CLOSE_TIMEOUT:v,EMPTY_BUFFER:y,GUID:b,kForOnEventAttribute:x,kListener:S,kStatusCode:C,kWebSocket:w,NOOP:T}=HM(),{EventTarget:{addEventListener:E,removeEventListener:D}}=YM(),{format:O,parse:k}=XM(),{toBuffer:A}=UM(),j=Symbol(`kAborted`),ee=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=class e extends n{constructor(t,n,r){super(),this._binaryType=_[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=!r||r.protocols===void 0?[]:Array.isArray(r.protocols)?r.protocols:[r.protocols]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=r.protocols===void 0?[]:Array.isArray(r.protocols)?r.protocols:[r.protocols]):n=[n]),F(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){_.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}
501
- /* istanbul ignore next */
502
- get onclose(){return null}
503
- /* istanbul ignore next */
504
- get onerror(){return null}
505
- /* istanbul ignore next */
506
- get onopen(){return null}
507
- /* istanbul ignore next */
508
- get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new m({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new h(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[w]=this,a[w]=this,t[w]=this,i.on(`conclude`,z),i.on(`drain`,B),i.on(`error`,re),i.on(`message`,ae),i.on(`ping`,oe),i.on(`pong`,se),a.onerror=le,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,ue),t.on(`data`,de),t.on(`end`,fe),t.on(`error`,pe),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){this._socket?(this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)):(this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage))}close(t,n){this.readyState!==e.CLOSED&&(this.readyState===e.CONNECTING?R(this,this._req,`WebSocket was closed before the connection was established`):this.readyState===e.CLOSING?this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end():(this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this._readyState=e.CLOSING,V(this)))}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState===e.OPEN?(n===void 0&&(n=!this._isServer),this._sender.ping(t||y,n,r)):ne(this,t,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState===e.OPEN?(n===void 0&&(n=!this._isServer),this._sender.pong(t||y,n,r)):ne(this,t,r)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ne(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[p.extensionName]||(i.compress=!1),this._sender.send(t||y,i,r)}terminate(){this.readyState!==e.CLOSED&&(this.readyState===e.CONNECTING?R(this,this._req,`WebSocket was closed before the connection was established`):this._socket&&(this._readyState=e.CLOSING,this._socket.destroy()))}};Object.defineProperty(P,"CONNECTING",{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P,"OPEN",{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P,"CLOSING",{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P,"CLOSED",{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[x])return t[S];return null},set(t){for(let t of this.listeners(e))if(t[x]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[x]:!0})}})}),P.prototype.addEventListener=E,P.prototype.removeEventListener=D,t.exports=P;function F(e,t,n,a){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:v,protocolVersion:ee[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=s.autoPong,e._closeTimeout=s.closeTimeout,!ee.includes(s.protocolVersion))throw RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${ee.join(`, `)})`);let u;if(t instanceof f)u=t;else try{u=new f(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}(u.protocol===`http:`||u.protocol===`https:`)&&(u=new f(u),u.protocol=u.protocol===`http:`?`ws:`:`wss:`),e._url=u.href;let d=u.protocol===`wss:`,m=u.protocol===`ws+unix:`,h;if(u.protocol!==`ws:`&&!d&&!m?h=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:m&&!u.pathname?h=`The URL's pathname is empty`:u.hash&&(h=`The URL contains a fragment identifier`),h){let t=SyntaxError(h);if(e._redirects===0)throw t;I(e,t);return}let g=d?443:80,_=c(16).toString(`base64`),y=d?r.request:i.request,x=/* @__PURE__ */ new Set,S;if(s.createConnection=s.createConnection||(d?te:L),s.defaultPort=s.defaultPort||g,s.port=u.port||g,s.host=u.hostname.startsWith(`[`)?u.hostname.slice(1,-1):u.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":_,Connection:`Upgrade`,Upgrade:`websocket`},s.path=u.pathname+u.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(S=new p({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers[`Sec-WebSocket-Extensions`]=O({[p.extensionName]:S.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!N.test(e)||x.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);x.add(e)}s.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(s.origin&&(s.protocolVersion<13?s.headers[`Sec-WebSocket-Origin`]=s.origin:s.headers.Origin=s.origin),(u.username||u.password)&&(s.auth=`${o.unescape(u.username)}:${o.unescape(u.password)}`),m){let e=s.path.indexOf(`:`);e===-1?(s.socketPath=s.path,s.path=``):(s.socketPath=s.path.slice(0,e),s.path=s.path.slice(e+1))}let C;if(s.followRedirects){if(e._redirects===0){e._originalIpc=m,e._originalSecure=d,e._originalHostOrSocketPath=m?s.socketPath:u.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=m?e._originalIpc?s.socketPath===e._originalHostOrSocketPath:!1:!e._originalIpc&&u.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!d)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(s.auth).toString(`base64`)),C=e._req=y(s),e._redirects&&e.emit(`redirect`,e.url,C)}else C=e._req=y(s);s.timeout&&C.on(`timeout`,()=>{R(e,C,`Opening handshake has timed out`)}),C.on(`error`,t=>{C===null||C[j]||(C=e._req=null,I(e,t))}),C.on(`response`,r=>{let i=r.headers.location,o=r.statusCode;if(i&&s.followRedirects&&o>=300&&o<400){if(++e._redirects>s.maxRedirects){R(e,C,`Maximum redirects exceeded`);return}C.abort();let r;try{r=new f(i,t)}catch{I(e,/* @__PURE__ */ SyntaxError(`Invalid URL: ${i}`));return}F(e,r,n,a)}else e.emit(`unexpected-response`,C,r)||R(e,C,`Unexpected server response: ${r.statusCode}`)}),C.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==P.CONNECTING)return;C=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){R(e,n,`Invalid Upgrade header`);return}let a=l(`sha1`).update(_+b).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){R(e,n,`Invalid Sec-WebSocket-Accept header`);return}let o=t.headers[`sec-websocket-protocol`],c;if(o===void 0?x.size&&(c=`Server sent no subprotocol`):x.size?x.has(o)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){R(e,n,c);return}o&&(e._protocol=o);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!S){R(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=k(u)}catch{R(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==p.extensionName){R(e,n,`Server indicated an extension that was not requested`);return}try{S.accept(t[p.extensionName])}catch{R(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[p.extensionName]=S}e.setSocket(n,r,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(C,e):C.end()}function I(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function L(e){return e.path=e.socketPath,a.connect(e)}function te(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),s.connect(e)}function R(e,t,n){e._readyState=P.CLOSING;let r=Error(n);Error.captureStackTrace(r,R),t.setHeader?(t[j]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(I,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ne(e,t,n){if(t){let n=g(t)?t.size:A(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=/* @__PURE__ */ Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function z(e,t){let n=this[w];n._closeFrameReceived=!0,n._closeCode=e,t.length===0?n._closeMessage=y:(n._closeMessage=Buffer.allocUnsafeSlow(t.length),n._closeMessage.set(t)),n._socket[w]!==void 0&&(n._socket.removeListener(`data`,de),process.nextTick(ce,n._socket),e===1005?n.close():n.close(e,t))}function B(){let e=this[w];e.isPaused||e._socket.resume()}function re(e){let t=this[w];t._socket[w]!==void 0&&(t._socket.removeListener(`data`,de),process.nextTick(ce,t._socket),t.close(e[C])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function ie(){this[w].emitClose()}function ae(e,t){this[w].emit(`message`,e,t)}function oe(e){let t=this[w];t._autoPong&&t.pong(e,!this._isServer,T),t.emit(`ping`,e)}function se(e){this[w].emit(`pong`,e)}function ce(e){e.resume()}function le(e){let t=this[w];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,V(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function V(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function ue(){let e=this[w];if(this.removeListener(`close`,ue),this.removeListener(`data`,de),this.removeListener(`end`,fe),e._readyState=P.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[w]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,ie),e._receiver.on(`finish`,ie))}function de(e){this[w]._receiver.write(e)||this.pause()}function fe(){let e=this[w];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function pe(){let e=this[w];this.removeListener(`error`,pe),this.on(`error`,T),e&&(e._readyState=P.CLOSING,this.destroy())}})),QM=/* @__PURE__ */ o(((e,t)=>{ZM();let{Duplex:n}=require("stream");function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){e.readyState===e.CONNECTING?e.once(`open`,function(){s._final(t)}):e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){e.readyState===e.CONNECTING?e.once(`open`,function(){s._write(t,n,r)}):e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),$M=/* @__PURE__ */ o(((e,t)=>{let{tokenChars:n}=KM();function r(e){let t=/* @__PURE__ */ new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),eN=/* @__PURE__ */ o(((e,t)=>{let n=require("events"),r=require("http"),{Duplex:i}=require("stream"),{createHash:a}=require("crypto"),o=XM(),s=GM(),c=$M(),l=ZM(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=HM(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=/* @__PURE__ */ new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2)e&&this.once(`close`,()=>{e(/* @__PURE__ */ Error(`The server is not running`))}),process.nextTick(h,this);else if(e&&this.once(`close`,e),this._state!==1){if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=/* @__PURE__ */ new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
509
- `).join(`\r
510
- `)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
511
- `)+`\r
512
- \r
513
- `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));QM(),XM(),GM(),qM(),JM(),$M();var tN=/* @__PURE__ */ c(ZM(),1);eN();var nN=tN.default;const rN=/(^|\n)(document|artboard)\/[^\n]+$/,iN=e=>u.default.createHash(`sha256`).update(e).digest(`hex`);function aN(e){if(!e)return null;try{let{token:t}=JSON.parse(d.default.readFileSync(e,`utf8`));return typeof t==`string`?t:null}catch{return null}}function oN(e,t){if(!e)return!1;try{let{url:n,features:r}=JSON.parse(d.default.readFileSync(e,`utf8`));return n===t&&Array.isArray(r)&&r.includes(`ask`)}catch{return!1}}function sN(e){let t=new URL(e.url);t.searchParams.set(`reject`,`close`);let n=null,r=``,i=`null`,a=()=>JSON.stringify(e.machine?.info()??null),o=/* @__PURE__ */ new Set,s=1e3,c,l=aN(e.refusedFile),u=0,d=null,f,p,m=!1,h=oN(e.featuresFile,e.url),g=t=>{h=t,e.featuresFile&&U(e.featuresFile,{url:e.url,features:t?[`ask`]:[]})},_=async t=>{let n=e.waiting?await e.waiting().catch(()=>null):null;for(let[r,i]of t)rN.test(i)&&(!n||n.has(r))&&e.handle(i,{op:`inbox`},`host`).catch(()=>{})},v=!1,y=/* @__PURE__ */ new Set,b,x=e=>{n?.readyState===nN.OPEN&&n.send(JSON.stringify(e))},S=e=>[...e.keys()].sort(),C=()=>{clearInterval(f),clearTimeout(b),v=!1,clearTimeout(p),p=void 0,n?.removeAllListeners(),n?.on(`error`,()=>{}),n?.terminate(),n=null,r=``,i=`null`,o=/* @__PURE__ */ new Set,e.onWatch?.(/* @__PURE__ */ new Set)},w=(e,t,n)=>x({t:`reply`,conn:e,rid:t,body:n}),T=async t=>{if(typeof t.conn!=`string`||typeof t.id!=`string`||typeof t.rid!=`number`&&typeof t.rid!=`string`)return;let n=t.rid;e.onActivity();let r=e.served().get(t.id);if(!r)return w(t.conn,n,{ok:!1,error:`not served here`});try{w(t.conn,n,{ok:!0,data:await e.handle(r,t.body,t.conn,typeof t.device==`string`?t.device:void 0)})}catch(e){w(t.conn,n,{ok:!1,error:e.message})}},E=async t=>{if(!e.machine||typeof t.conn!=`string`||typeof t.rid!=`number`&&typeof t.rid!=`string`)return;let{conn:n,rid:r}=t,i=e=>x({t:`machine-reply`,conn:n,rid:r,body:e}),a=rl(t.body);if(!a)return i({ok:!1,error:`not a machine request`});try{i({ok:!0,data:await e.machine.handle(a)})}catch(e){i({ok:!1,error:e.message})}},D=(l,d)=>{let m=new nN(t,{headers:{Authorization:`Bearer ${l}`,"X-Ryugi-Version":e.version},handshakeTimeout:e.handshakeTimeoutMs??1e4}),w;n=m,m.on(`open`,()=>{w=Date.now(),c=void 0,r=S(d).join(`
514
- `),y=new Set(d.keys()),i=a();let t=e.machine?.info()??null,n=n=>x({t:`hello`,version:e.version,...n?{ids:S(d)}:{onDemand:!0},...e.local?{local:e.local()}:{},...t?{machine:t}:{}});h?(n(!1),b=setTimeout(()=>{g(!1),n(!0)},e.featuresWaitMs??5e3)):n(!0),_(d),f=setInterval(()=>{o.size>0&&e.onActivity(),m.send(`ping`),p??=setTimeout(()=>D(),1e4)},e.heartbeatMs??25e3)}),m.on(`message`,t=>{let n=t.toString();if(n===`pong`){clearTimeout(p),p=void 0;return}let r;try{r=JSON.parse(n)}catch{return}if(r.t===`relay`&&Array.isArray(r.features)&&r.features.includes(`ask`))h||g(!0),v=!0,clearTimeout(b);else if(r.t===`ask`&&typeof r.rid==`number`&&Array.isArray(r.ids)){let t=e.served();x({t:`answer`,rid:r.rid,ids:r.ids.filter(e=>typeof e==`string`&&t.has(e))})}else if(r.t===`watch`&&Array.isArray(r.ids)){o=new Set(r.ids.filter(e=>typeof e==`string`));let t=e.served();e.onWatch?.(new Set([...o].flatMap(e=>t.has(e)?[t.get(e)]:[])))}else r.t===`request`?T(r):r.t===`machine`&&E(r)});let D=(e,t)=>{if(n===m){if(w!==void 0&&Date.now()-w>=3e4&&e!==1013&&(s=1e3),C(),e===4429){if(t===`subscription required`)return O(l);if(t===`daily limit`){let e=/* @__PURE__ */ new Date;e.setUTCHours(24,0,0,0),u=e.getTime()}else u=Date.now()+3e5}else u=Date.now()+s+Math.floor(Math.random()*s),s=Math.min(s*2,3e4)}};m.on(`close`,(e,t)=>D(e,t.toString())),m.on(`error`,()=>D())},O=t=>{c=`subscription`,l=iN(t),e.refusedFile&&U(e.refusedFile,{token:l})},k=()=>{if(m)return;let t=e.token();t!==d&&(d=t,c=t&&iN(t)===l?`subscription`:void 0,n&&C(),u=0,s=1e3);let o=e.served();if(!t||o.size===0&&!e.machine?.info()){n&&C();return}if(!n){!c&&Date.now()>=u&&D(t,o);return}let f=S(o).join(`
515
- `);if(n.readyState===nN.OPEN&&f!==r){if(r=f,v){let e=new Set(o.keys()),t=[...e].filter(e=>!y.has(e)).sort(),n=[...y].filter(t=>!e.has(t)).sort();y=e,x({t:`served`,add:t,remove:n})}else x({t:`ids`,ids:S(o)})}let p=a();n.readyState===nN.OPEN&&p!==i&&(i=p,x({t:`machine-info`,machine:JSON.parse(p)}))},A=setInterval(k,e.pollMs??5e3);return k(),{emit(t,n){for(let[r,i]of e.served())i===t&&o.has(r)&&x({t:`event`,id:r,body:n})},refresh:k,state:()=>({connected:n?.readyState===nN.OPEN,announced:r?r.split(`
516
- `).length:0,watched:o.size,...c?{refused:c}:{}}),close(){m=!0,clearInterval(A),C()}}}function cN(e,t,n,r,i=1/0,a){if(!tt(e,n))return null;let o=oj[t],s=e=>r.replace(/ryugi-ui\.js$/,e),c=o.ownPage?.(e,p.default.basename(e),n,s);if(c!==void 0){if(c===null)return null;if(Buffer.byteLength(c)>i)throw RangeError(`too large`);return{contentType:`text/html; charset=utf-8`,data:Buffer.from(c)}}let l=o.compiledPage?.(e,n,`cloud`)??null,u,f=n;if(l!==null){if(u=Buffer.from(l),u.byteLength>i)throw RangeError(`too large`)}else{let t=a??o.resolveFile(e,n);if(!t)return null;f=t;try{if(d.default.statSync(t).size>i)throw RangeError(`too large`);u=d.default.readFileSync(t)}catch(e){if(e instanceof RangeError)throw e;return null}}if(!o.isPage(n))return{contentType:P(f),data:u};let m=rh(u.toString(`utf8`),{uiRuntimeUrl:r,...o.pageRuntime?.(n,s)});return{contentType:`text/html; charset=utf-8`,data:Buffer.from(m)}}function lN(e,t,n){let r;try{r=JSON.parse(n)}catch{return}if(typeof r!=`object`||!r)return;if(r.type===`selection`){e.selections.accept(t,r);return}let i=pj.get(r.type);i?i(e,t,r):uN(e,r)}function uN(e,t){let n=fj.get(t.type);n?n(e,t):dN(e,t)}function dN(e,{type:t,artifact:n,message:r,version:i,file:a,board:o}){let{root:s,runtimeWarnings:c,ranVersions:l,clients:u}=e;if(typeof n!=`string`)return;let d=G(n);if(!d||n!==`${d.type}/${d.id}`)return;let f=W(s,d.type,d.id);if(!f)return;let p=oj[d.type];if(p.acceptReport){p.acceptReport(e,d.id,f,{type:t,message:r,version:i,file:a,board:o});return}if(t===`loaded`){let t=p.read(f,d.id);if(!(`version`in t)||typeof i!=`number`||i!==t.version)return;l.set(n,i),e.writeState(d,f);return}if(t!==`runtime-error`||typeof r!=`string`||r.length===0||r.length>2048)return;let m=c.get(n)??[];if(m.includes(r)||m.length>=20)return;c.set(n,[...m,r]),e.writeState(d,f);let h=lc(JSON.stringify({type:`change`,artifact:n,files:[]}));for(let e of u)e.write(h)}const fN=`Forbidden: agent calls need ?key=`,pN={public:{gated:!1,denied:`Forbidden`,allow:()=>!0},key:{gated:!1,denied:fN,allow:(e,t,n)=>t.isAuthorized(e,n)},viewer:{gated:!0,denied:`Forbidden`,allow:()=>!0},navigation:{gated:!0,denied:`Forbidden`,allow:(e,t)=>!t.loopback||dn(e.headers[`sec-fetch-site`])},agent:{gated:!0,denied:fN,allow:(e,t,n)=>t.agentOk(e,n)},"same-origin":{gated:!0,denied:`Forbidden`,allow:(e,t)=>t.sameOrigin(e)},cloud:{gated:!0,denied:`Forbidden`,allow:(e,t,n)=>e.method===`GET`||t.keyOk(n)||t.sameOrigin(e)}},mN={"direct-relay":(e,t,n)=>{let r=t.options.cloud!==void 0&&e.headers.origin===t.options.cloud.origin;return t.keyOk(n)&&(r||t.sameOrigin(e))},socket:(e,t,n)=>t.isAuthorized(e,n)&&t.sameOrigin(e)};function hN(e,t,n){return typeof e==`string`?e===t?[t]:null:e instanceof RegExp?e.exec(t):e(t,n)}function gN({auth:e,methods:t},n,r,i){let a=pN[e];if(a.gated){if(r.loopback&&!un(r.policy,n.headers.origin))return`Forbidden origin`;if(!r.isAuthorized(n,i))return`Forbidden: open the full artifact link including ?key=`}return t&&!t.includes(n.method??``)?a.denied:a.allow(n,r,i)?null:a.denied}function _N(e,t,n,r){if(n.setHeader(`X-Robots-Tag`,`noindex, nofollow`),!ln(r.policy,t.headers.host)){z(n,403,`Forbidden host`);return}let i=new URL(t.url??`/`,`http://artifacts.local`),a=i.searchParams.get(`key`),o=(e,o)=>{for(let s of e){let e=hN(s.path,o,r);if(!e)continue;let c=gN(s,t,r,a);if(c!==null)return z(n,403,c),!0;let l=s.handle(t,n,r,{key:a,match:e,pathname:o,url:i});return l instanceof Promise&&l.catch(e=>{n.headersSent||z(n,500,`Artifacts error: ${e.message}`)}),!0}return!1};if(o(e.filter(e=>e.raw),i.pathname))return;r.touch();let s;try{s=decodeURIComponent(i.pathname)}catch{z(n,400,`Bad request`);return}o(e.filter(e=>!e.raw),s)||z(n,404,`Not found`)}function vN(e,t,n,r){if(!ln(r.policy,t.headers.host)){dc(n,403,`Forbidden`);return}let i=new URL(t.url??`/`,`http://artifacts.local`),a=t.headers[`sec-websocket-key`],o=i.searchParams.get(`key`);if(typeof a!=`string`)dc(n,400,`Bad Request`);else{for(let s of e){let e=hN(s.path,i.pathname,r);if(e){if(!mN[s.auth](t,r,o)){dc(n,403,`Forbidden`);return}s.handle(t,n,r,{key:o,match:e,pathname:i.pathname,url:i,clientKey:a});return}}dc(n,400,`Bad Request`)}}const yN=/* @__PURE__ */ new Set([`viewer`,`same-origin`]),bN=/* @__PURE__ */ new Set([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]);function xN(e,t,n){let r=new URL(n,`http://relay.local`),i=/^\/api\/([^/]+)\/([^/]+)(\/.*)?$/.exec(r.pathname);if(!i||i[1]!==t.type)return null;let a=i[2];return a!==t.id&&e.servedArtifacts().get(a)!==`${t.type}/${t.id}`?null:(r.pathname=`/api/${t.type}/${t.id}${i[3]??``}`,r)}const SN=e=>{try{return JSON.parse(e)}catch{return e}};var CN=class{statusCode=200;headersSent=!1;headers=/* @__PURE__ */ new Map;chunks=[];done;finish=()=>{};constructor(){this.done=new Promise(e=>this.finish=e)}setHeader(e,t){this.headers.set(e.toLowerCase(),String(t))}getHeader(e){return this.headers.get(e.toLowerCase())}writeHead(e,t={}){this.statusCode=e;for(let[e,n]of Object.entries(t))this.setHeader(e,n);return this.headersSent=!0,this}write(e){return this.headersSent=!0,this.chunks.push(Buffer.from(e)),!0}end(e){return e!==void 0&&this.write(e),this.headersSent=!0,this.finish(),this}reply(){let e=Buffer.concat(this.chunks);if(e.length>8388608)throw Error(`too large`);let t=e.toString(`utf8`),n=this.getHeader(`content-type`)?.includes(`json`);return{status:this.statusCode,body:n?SN(t):t}}};function wN(e,t,n){let r=n===void 0?``:typeof n==`string`?n:JSON.stringify(n),i=_.Readable.from(r?[Buffer.from(r)]:[]);return Object.assign(i,{method:e,url:t.pathname+t.search,headers:{"content-type":`application/json`},socket:{remoteAddress:void 0}}),{req:Jp(i),size:Buffer.byteLength(r)}}async function TN(e,t,n){let r=typeof n.method==`string`?n.method.toUpperCase():`GET`;if(!bN.has(r))throw Error(`refused: method`);let i=typeof n.path==`string`?xN(e,t,n.path):null;if(!i)throw Error(`refused: not this artifact`);let a;try{a=decodeURIComponent(i.pathname)}catch{throw Error(`refused: path`)}let o=oj[t.type].routes??[];for(let t of o){let o=hN(t.path,a,e);if(!o)continue;if(t.raw||t.relay===`deny`||!yN.has(t.auth))throw Error(`refused: not relayed`);if(t.methods&&!t.methods.includes(r))throw Error(`refused: method`);let{req:s,size:c}=wN(r,i,n.body);if(c>8388608)throw Error(`too large`);let l=new CN,u=t.handle(s,l,e,{key:null,match:o,pathname:a,url:i});return t.relay===`background`?(u instanceof Promise&&u.catch(()=>void 0),{status:202,body:{started:!0}}):(u instanceof Promise&&await u,await l.done,l.reply())}throw Error(`refused: no route`)}const EN=[`api`];function DN(e,t){let n=e.relayViewers.get(t);n&&(e.selections.drop(n.tab),e.relayViewers.delete(t))}function ON(e,t){for(let n of t)e.relayWatched.has(n)||e.viewed.viewerJoined(n);for(let n of[...e.relayWatched])t.has(n)||(e.relayWatched.delete(n),e.viewed.viewerLeft(n));for(let n of t)e.relayWatched.add(n);for(let[n,r]of e.relayViewers)t.has(r.key)||n.startsWith(`direct:`)||(e.selections.drop(r.tab),e.relayViewers.delete(n))}async function kN(e,t,n,r,i=``){let{root:a,selections:o,relayViewers:s}=e,c=G(t),l=W(a,c.type,c.id);if(!l)throw Error(`${t} not found`);let u=oj[c.type],d=typeof n==`object`&&n?n:{};if(d.op===`publication`&&e.cloud)return e.cloud.publication(t);if(d.op===`publish`&&e.cloud)return e.cloud.publishNow(t);if(d.op===`refs`&&e.cloud)return e.cloud.cascade(t,d.visibility===`public`||d.visibility===`private`?d.visibility:void 0);if(d.op===`publish-referrers`&&e.cloud){let n=e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):[];return e.cloud.publishReferrersNow(t,n(d.publish),n(d.makePublic))}if(d.op===`publish-refs`&&e.cloud){let n=e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):[];return e.cloud.publishRefsNow(t,n(d.refs),n(d.makePublic),d.visibility===`public`||d.visibility===`private`?d.visibility:void 0)}if(d.op===`inbox`)return{applied:await mc(e,c,u.mergeRemote)};if(d.op===`meta`)return await NM(c,l),RM(e,c),{...e.artifactMeta(c,l,i),features:EN};if(d.op===`thread-activity`)return{threads:e.threadActivity.derive(t,Date.now())};if(d.op===`file`){let t=typeof d.path==`string`?cN(l,c.type,d.path,nh,8388608,u.standIn?.(e,c.id,d.path)??null):null;if(!t)throw Error(`not found`);if(t.data.length>8388608)throw Error(`too large`);return{contentType:t.contentType,data:t.data.toString(`base64`)}}if(d.op===`api`)return TN(e,c,d);if(d.op===`client`){if(typeof d.message==`object`&&d.message!==null){let n={...d.message,artifact:t};uN(e,n.type===`slides-report`?{...n,sheet:!1}:n)}return null}let f=typeof d.op==`string`&&u.relayOps&&Object.hasOwn(u.relayOps,d.op)?u.relayOps[d.op]:void 0;if(f)return f(e,c.id,d);if(d.op===`state`||d.op===`update`||d.op===`comment`)throw Error(`${t} is not a document`);if(d.op===`selection`){if(typeof d.selection!=`object`||d.selection===null)throw Error(`not a selection`);let e=s.get(r)??{key:t,tab:{}};return s.set(r,e),o.accept(e.tab,{...d.selection,artifact:t}),null}throw Error(`unknown request`)}const AN=e=>e.messages.filter(e=>!e.deleted&&e.author===`human`).at(-1)?.id??null,jN={thinking:`working`,running:`working`,"needs-approval":`approval`};function MN({lookup:e,threads:t}){let n=/* @__PURE__ */ new Map,r=(t,n)=>{let r=e(t.host,t.session),i=n-t.at>=18e5;if(!r)return t.known||i?`drop`:null;if(t.turn>r.turn)return i?`drop`:null;let a=t.turn===r.turn?jN[r.state]??`seen`:`seen`;return{agent:r.agent,state:a}};return{deliver(r,i,a,o,s){let c=e(i,a),l=!c||c.state===`your-turn`?(c?.turn??0)+1:c.turn,u=new Map(t(r).map(e=>[e.id,e]));for(let t of o){let o=u.get(t);if(!o||ro(o)!==`agent`)continue;let d=n.get(r)??/* @__PURE__ */ new Map,f=d.get(t);!c&&f&&e(f.host,f.session)||(d.set(t,{at:s,host:i,known:!!c,lastHuman:AN(o),session:a,turn:l}),n.set(r,d))}},derive(e,i){let a=n.get(e);if(!a)return{};let o=new Map(t(e).map(e=>[e.id,e])),s={};for(let[e,t]of a){let n=o.get(e);if(!n||ro(n)!==`agent`){a.delete(e);continue}if(AN(n)!==t.lastHuman)continue;let c=r(t,i);c===`drop`?a.delete(e):c&&(s[e]=c)}return a.size===0&&n.delete(e),s},keys:()=>[...n.keys()]}}const NN=/* @__PURE__ */ new Set([`doc-comments`,`board-comments`,`whiteboard-comments`,`storyboard-comments`,`slides-comments`,ke]);function PN({agentDaemon:e,agentDirectory:t,agentStatus:n,broadcast:r,clients:i,ctx:a,root:o}){let s=()=>lc(JSON.stringify({type:`agent-status`,artifact:`*`,sessions:n.sessions(),daemon:e?.entries()??[]})),c=()=>{let e=s();for(let t of i)t.write(e);t.changed()},l=MN({lookup:(e,n)=>t.lookup(e,n),threads:e=>{let t=G(e);if(!t||!W(o,t.type,t.id))return[];try{return oj[t.type].threads?.(a(),t.id)??[]}catch{return[]}}}),u=/* @__PURE__ */ new Map,d=e=>{let t=Date.now();for(let n of e??/* @__PURE__ */ new Set([...l.keys(),...u.keys()])){let e=l.derive(n,t),i=JSON.stringify(e);(u.get(n)??`{}`)!==i&&(i===`{}`?u.delete(n):u.set(n,i),r({type:`thread-activity`,artifact:n,threads:e}))}};return{afterBroadcast:e=>{NN.has(e.type)&&queueMicrotask(()=>d([e.artifact]))},agentStatusFrame:s,deliverThreads:(e,t,n,r)=>{l.deliver(e,t,n,r,Date.now()),d([e])},leaveDirectoryUpdates:t.subscribe(()=>d()),publishAgentStatus:c,publishThreadActivity:d,threadActivity:l,threadActivityFrames:()=>[...u].map(([e,t])=>lc(JSON.stringify({type:`thread-activity`,artifact:e,threads:JSON.parse(t)})))}}function FN({backlinksOf:e,contentPrefix:t,ctx:n,names:r,recordings:i,runtimeSession:a,runtimeWarnings:o,stateDir:s}){let c=(e,t)=>oj[e.type].runtimeWarnings?.(n(),e.id,t)??o.get(`${e.type}/${e.id}`)??[],l=(e,t,n=[])=>{let r=RR(e,t,n);return oj[t.type].readLive?.(e,t.id,r,{recordings:i,runtimeSession:a})??r},u=(i,a,o=``)=>{let s=oj[i.type];return{...l(a,i,c(i,a)),...s.noAgent?{}:{agent:r.agent(`${i.type}/${i.id}`)},...s.meta?.(n(),i.id,a),...s.backlinksAs?{backlinks:e(i.id,s.backlinksAs)}:{},contentBase:`${o}${t}${i.type}/${i.id}/`}},f=/* @__PURE__ */ new Map,m=p.default.join(s,`signatures.json`),h=()=>{try{let e=JSON.parse(d.default.readFileSync(m,`utf8`));return new Map(Object.entries(e).filter(e=>typeof e[1]==`string`))}catch{return null}},g=!1,_=()=>{g||(g=!0,setImmediate(()=>{g=!1;try{U(m,Object.fromEntries(f))}catch{}}))},v=(t,r)=>{let i=l(r,t,c(t,r)),a=oj[t.type],o=a.state?.(n(),t.id,r,i);try{gt(s,t,i,o?.extra);let n=p.default.join(s,t.type,t.id);for(let[e,t]of Object.entries(o?.files??{}))U(p.default.join(n,e),{checkedAt:(/* @__PURE__ */ new Date()).toISOString(),...t});a.backlinksAs&&U(p.default.join(n,`backlinks.json`),e(t.id,a.backlinksAs))}catch(e){console.error(JSON.stringify({type:`state-write-error`,error:e.message}))}return i},y=/* @__PURE__ */ new Set;return{artifactMeta:u,fresh:y,readArtifact:l,refreshState:(e,t)=>(y.add(`${e.type}/${e.id}`),f.set(`${e.type}/${e.id}`,nr(t,e.type)),_(),v(e,t)),runtimeOf:c,saveSignatures:_,signatureBaseline:h,signatures:f,writeState:v}}const IN=/^\/api\/avatar\/([a-z]+)\/([^/]+)$/,LN={github:{valid:/^[A-Z0-9][A-Z0-9-]{0,38}$/i,url:e=>`https://avatars.githubusercontent.com/${e}?s=64`},gravatar:{valid:/^[0-9a-f]{64}$/,url:e=>`https://gravatar.com/avatar/${e}?s=64&d=404`}},RN=e=>`/api/avatar/github/${e}`,zN=e=>`/api/avatar/gravatar/${(0,u.createHash)(`sha256`).update(e.trim().toLowerCase()).digest(`hex`)}`;function BN(e=fetch){let t=/* @__PURE__ */ new Map,n=async t=>{try{let n=await e(t,{signal:AbortSignal.timeout(5e3)}),r=n.headers.get(`content-type`)??``;if(!n.ok||!r.startsWith(`image/`))return{status:404};let i=Buffer.from(await n.arrayBuffer());return i.length>524288?{status:404}:{status:200,type:r,body:i}}catch{return{status:502}}};return{load(e,r){let i=LN[e];if(!i||!i.valid.test(r))return Promise.resolve({status:404});let a=`${e}/${r}`,o=t.get(a);if(o)return o;let s=n(i.url(r)).then(e=>(e.status===502&&t.delete(a),e));return t.set(a,s),s}}}function VN(e){let t=/* @__PURE__ */ new Map,n=0,r=(e,t)=>console.info(JSON.stringify({type:`direct-relay`,event:e,at:(/* @__PURE__ */ new Date()).toISOString(),...t})),i=(e,t)=>e.write(lc(JSON.stringify(t))),a=async(t,n,r,a)=>{let o;try{o=JSON.parse(a)}catch{return}if(!(o.t!==`request`||typeof o.rid!=`number`&&typeof o.rid!=`string`)){e.onActivity();try{i(t,{t:`reply`,rid:o.rid,body:{ok:!0,data:await e.handle(n,o.body,r)}})}catch(e){i(t,{t:`reply`,rid:o.rid,body:{ok:!1,error:e.message}})}}};return{accept(o,s,c){uc(o,s);let l=`direct:${++n}`;t.set(o,{key:c,conn:l}),e.onOpen(c);let u=Date.now();r(`open`,{conn:l,key:c,viewers:t.size}),i(o,{t:`presence`,online:!0,version:e.version,...e.daemon?.()?{daemon:!0}:{}}),fc(o,e=>void a(o,c,l,e));let d=(n,i)=>{t.delete(o)&&(r(`close`,{conn:l,key:c,how:n,aliveMs:Date.now()-u,...i?{error:i.message}:{}}),e.onClose(l,c))};o.on(`end`,()=>{d(`end`),o.end()}),o.on(`close`,()=>d(`close`)),o.on(`error`,e=>d(`error`,e)),e.onActivity()},size:()=>t.size,drop:e=>{for(let[n,r]of t)r.key===e&&n.destroy()},viewing:e=>[...t.values()].some(t=>t.key===e),emit(e,n){for(let[r,a]of t)a.key===e&&i(r,{t:`event`,body:n})},close(){for(let e of t.keys())e.destroy()}}}function HN(e,t,n,r,i=Ba(),a,o){return oj[e.type].publish(t,e.id,n,r,{comments:i,rows:a,measured:o})}function UN(e,t){let{cloudPage:n}=oj[e];return t.map(e=>{let t=n?.(e.path);return t?{path:e.path,data:Buffer.from(rh(e.data.toString(`utf8`),{uiRuntimeUrl:nh,...t}))}:e})}async function WN(e,t,n){let{root:r,signatures:i,recordings:a}=e,o=W(r,n.type,n.id);if(!o)return null;let s=oj[n.type],c=s.publishSession?await s.publishSession(e,n.id):null;if(c){let t=`${n.type}/${n.id}`,r=i.get(t)===nr(o,n.type);await c.flush(),r&&(i.set(t,nr(o,n.type)),e.saveSignatures())}s.flushForPublish?.(e,n.id),await NM(n,o,{publish:!0});let l=e.readArtifact(o,n,e.runtimeOf(n,o)),u=s.publishBlockers?.(l)??[...l.warnings];`sourceIssues`in l&&u.push(...Rg([],null,l.sourceIssues??[]).map(e=>e.message)),`pending`in l&&u.push(...l.pending.map(e=>`board ${e} is still being written`)),`canvas`in l&&l.canvas?.writing&&!l.pending.includes(l.canvas.writing)&&u.push(`board ${l.canvas.writing} is still being written`),c?.streaming()&&u.push(`the document is still being written`);let d=zR(l),f=null;if(u.length===0)try{let r=s.publishExtras?.(e,n.id,t)??{};f=HN(n,o,d,l,r.comments,r.rows,r.measured)}catch(e){u.push(e.message)}let p=s.publishFiles?.(o,n.id);return{dir:o,title:d,reasons:u,payload:f,...`canvas`in l?{fileOverrides:a.overrides(n.id,l)}:{},...p?{fileOverrides:p}:{},...s.publishPlan?{plan:s.publishPlan.plan(o)}:{}}}function GN(e,t){let n=G(t),r=n&&W(e,n.type,n.id),i=n&&jy[n.type];return!r||!i?[]:[...new Set(i(r))].filter(t=>{let n=G(t);return!!n&&W(e,n.type,n.id)!==null})}function KN(e,t){let n=[];for(let r of er(e).artifacts){let e=jy[r.type],i=`${r.type}/${r.id}`;if(!e||i===t)continue;let a=e(r.dir).filter(e=>e===t).length;a>0&&n.push({key:i,uses:a})}return n.sort((e,t)=>e.key.localeCompare(t.key))}const qN=[`unpublished`,`stale`,`private`,`withdrawn`],JN=[`unpublished`,`stale`];function YN(e,t){let n=e.published?t===`public`&&e.visibility===`private`?`private`:e.stale?`stale`:`ready`:e.withdrawn?`withdrawn`:`unpublished`;return e.blocked&&n!==`private`&&n!==`ready`?`blocked`:n}const XN=(e,t)=>e.published&&(t===`private`||e.visibility===`public`);async function ZN(e,t,n){let r=/* @__PURE__ */ new Map,i=[e];for(let a=0;a<i.length;a++){let o=i[a];for(let a of new Set(await n.referencesOf(o))){if(a===e)continue;let s=r.get(a);if(s){s.parents.includes(o)||s.parents.push(o);continue}let c=await n.statusOf(a);if(!c)continue;let l=YN(c,t);r.set(a,{artifact:a,title:c.title,via:o===e?null:o,parents:[o],state:l,open:XN(c,t),checked:JN.includes(l),selectable:qN.includes(l),...l===`blocked`&&c.blocked?{blocked:c.blocked}:{},...c.stale&&!c.blocked?{changed:!0}:{}}),i.push(a)}}return QN([...r.values()],{},e)}function QN(e,t,n){let r=new Map(e.map(e=>[e.artifact,e])),i=e=>qN.includes(e.state)&&(t[e.artifact]??JN.includes(e.state)),a=e=>n?e===n:!r.has(e),o=/* @__PURE__ */ new Set,s=e=>{if(a(e))return!0;let t=r.get(e);return!!t&&o.has(e)&&(t.open||i(t))};for(let t=!0;t;){t=!1;for(let n of e)!o.has(n.artifact)&&n.parents.some(s)&&(o.add(n.artifact),t=!0)}return e.map(e=>{let{reason:t,upstream:n,...r}=e,a=e.state===`blocked`?e.blocked:void 0;return o.has(e.artifact)?{...r,checked:i(e),selectable:qN.includes(e.state),...a?{reason:a}:{}}:{...r,checked:!1,selectable:!1,reason:`upstream`,upstream:e.via??e.parents[0]}})}const $N=[`private`,`unpublished`,`unlinked`],eP=e=>({...e,selectable:$N.includes(e.state),checked:!1});function tP(e,t){if(!e.published)return e.withdrawn?{state:`withdrawn`}:e.blocked?{state:`blocked`,reason:e.blocked}:{state:`unpublished`};let n=e.visibility===`private`;return t?n?{state:`private`,needsUpdate:!0}:{state:`unlinked`}:{state:n?`private`:`ready`}}function nP({cloud:e,local:t}){let n=new Map(t.filter(e=>e.cloudId).map(e=>[e.cloudId,e])),r=(e??[]).map(e=>{let t=n.get(e.cloudId);return eP({artifact:t?.key??`cloud:${e.cloudId}`,cloudId:e.cloudId,title:t?.status.title??e.title,uses:e.uses,state:e.visibility===`private`?`private`:`ready`})}),i=new Set((e??[]).map(e=>e.cloudId)),a=t.filter(e=>!e.cloudId||!i.has(e.cloudId)).map(t=>eP({artifact:t.key,cloudId:t.cloudId,title:t.status.title,uses:t.uses,...tP(t.status,e!==null)}));return[...r,...a]}function rP(e){if(!e||typeof e!=`object`)return{};let t=e,n={};if(typeof t.code==`string`&&(n.code=t.code),(t.plan===`free`||t.plan===`pro`||t.plan===`max`)&&(n.plan=t.plan),typeof t.upgradeUrl==`string`&&(n.upgradeUrl=t.upgradeUrl),t.limit&&typeof t.limit==`object`){let e=t.limit;typeof e.kind==`string`&&typeof e.used==`number`&&Number.isFinite(e.used)&&e.used>=0&&typeof e.max==`number`&&Number.isFinite(e.max)&&e.max>=0&&(n.limit={kind:e.kind,used:e.used,max:e.max},typeof e.requested==`number`&&Number.isFinite(e.requested)&&e.requested>=0&&(n.limit.requested=e.requested))}return n}var iP=class extends Error{},X=class extends Error{status;details;constructor(e,t,n={}){super(t),this.status=e,this.details=n}},aP=class extends Error{},oP=class extends X{upgradeUrl;constructor(e,t,n){super(402,e,n),this.upgradeUrl=t}},sP=class extends X{constructor(e){super(409,e,{code:`publish_behind`})}};function cP(e,t){let n=t.publishedBy??`Someone`,r=t.sourceCommit?` from commit ${t.sourceCommit.slice(0,7)}`:``,i=e.split(`/`)[1],a=t.sourceCommit?`Run git pull, then publish again.`:`Run ryugi pull --artifact ${e} --as ${i}-cloud to get it beside yours, merge the two, then publish again.`;return`${n} published version ${t.version??`?`}${r} after the copy you are publishing from. ${a}`}var lP=class extends X{detail;constructor(e){super(403,`cloud refused (403): ${e}`),this.detail=e}};async function uP(e){let t=await e.text().catch(()=>``),n={};try{let e=JSON.parse(t);e&&typeof e==`object`&&(n=e)}catch{}let r=rP(n),i=typeof n.error==`string`?n.error:t||e.statusText;throw e.status===402&&r.code===`plan_limit`&&r.upgradeUrl?new oP(i,r.upgradeUrl,r):new X(e.status,`cloud refused (${e.status}): ${i}`,r)}async function dP(e){let t=await e.text().catch(()=>``);try{let e=JSON.parse(t);return typeof e.error==`string`?e.error:t}catch{return t||e.statusText}}function fP(e,t,n,r,i,a){let{configFile:o}=e,{cloudFetch:s}=t,{artifactEntry:c,expectOk:l,serialized:u}=n,d=async t=>{let n=G(t),i=n&&await e.inspect(n);if(!n||!i)return null;let a=c(t),o=!!a.cloud?.publishedAt,s=null,l=null;try{let e=await r(n);e.ready?l=e.fingerprint:s=e.reasons.join(`; `)}catch(e){if(e instanceof iP)throw e;s=e.message.replace(/^cloud refused \(\d+\): /,``)}return{title:i.title,published:o,withdrawn:!a.cloud&&a.autoPublish===!1,stale:o&&l!==null&&l!==a.cloud?.fingerprint,visibility:o?a.cloud?.visibility??Rr(a).visibility:null,blocked:s}},f=(t,n)=>ZN(`${t.type}/${t.id}`,n,{referencesOf:t=>{let n=G(t);return n?e.references?.(n)??[]:[]},statusOf:d}),p=async e=>{try{let t=await s(`GET`,`/api/a/${e}/refs`);if(!t.ok)return null;let n=await t.json();return Array.isArray(n.referrers)?n.referrers:null}catch{return null}},m=async t=>{let n=[];for(let{key:r,uses:i}of e.referrers?.(t)??[]){let e=await d(r);e&&n.push({key:r,uses:i,status:e,cloudId:c(r).cloud?.id??null})}let r=c(`${t.type}/${t.id}`).cloud,i=r?.publishedAt?await p(r.id):null,a=!!r?.publishedAt&&i===null;return{referrers:nP({cloud:i,local:n}),...a?{cloudUnavailable:!0}:{}}};return{cascadeOf:f,publishReferrers:async(e,t,n)=>{let r=`${e.type}/${e.id}`,d=c(r);if(!d.cloud?.publishedAt||Rr(d).visibility!==`public`)throw new X(400,`${r} is not public`);let{referrers:f}=await m(e),p=new Map(f.map(e=>[e.artifact,e]));for(let e of n)if(p.get(e)?.state!==`private`)throw new X(400,`${e} is not a private document that references ${r}`);for(let e of t){let t=p.get(e)?.state;if(t!==`unpublished`&&t!==`unlinked`)throw new X(400,`${e} is not a document ${r} can publish`)}let h=[];for(let e of[...n,...t]){let t=p.get(e),r=n.includes(e)?`make-public`:t.state===`unlinked`?`update`:`publish`;try{G(e)?await u(e,async()=>{let n=G(e);if(r===`make-public`&&(await a(n,`public`),!t.needsUpdate))return;let s=await i(n,`public`);if(s.status!==200)throw new X(409,(s.body.reasons??[]).join(`; `)||`not ready to publish`);Yr(o,e,{autoPublish:null})}):await l(await s(`PATCH`,`/api/artifacts/${t.cloudId}`,{visibility:`public`})),h.push({artifact:e,action:r,status:`published`})}catch(t){if(t instanceof iP)throw t;let n=t instanceof X?t.status:void 0;h.push({artifact:e,action:r,status:n!==void 0&&n<500?`failed`:`unknown`,error:{error:t.message.replace(/^cloud refused \(\d+\): /,``),...n===void 0?{}:{httpStatus:n}}})}}return{results:h}},publishRefs:async(e,t,n,r)=>{let s=`${e.type}/${e.id}`,l=r??Rr(c(s)).visibility,d=await f(e,l),p=Object.fromEntries(d.map(e=>[e.artifact,!1]));for(let e of[...t,...n])p[e]=!0;let m=QN(d,p),h=new Map(m.map(e=>[e.artifact,e]));for(let e of[...t,...n]){let t=h.get(e);if(!t?.selectable)throw new X(400,`${e} is not a reference ${s} can publish`);if(n.includes(e)!==(t.state===`private`))throw new X(400,t.state===`private`?`${e} is private: list it in makePublic`:`${e} is not private: list it in refs`)}let g=[],_=!1;for(let e of m.filter(e=>e.checked)){let t=e.state===`private`?`make-public`:e.state===`stale`?`update`:`publish`;if(_){g.push({artifact:e.artifact,action:t,status:`not_attempted`});continue}let n=G(e.artifact);try{await u(e.artifact,async()=>{if(t===`make-public`&&(await a(n,`public`),!e.changed))return;let r=await i(n,t===`publish`?l:void 0,{skipUnchanged:!0});if(r.status!==200)throw new X(409,(r.body.reasons??[]).join(`; `)||`not ready to publish`);Yr(o,e.artifact,{autoPublish:null})}),g.push({artifact:e.artifact,action:t,status:`published`})}catch(n){if(n instanceof iP)throw n;let r=n instanceof X?n.status:void 0;g.push({artifact:e.artifact,action:t,status:r!==void 0&&r<500?`failed`:`unknown`,error:{error:n.message.replace(/^cloud refused \(\d+\): /,``),...n instanceof X?n.details:{},...r===void 0?{}:{httpStatus:r}}}),_=!0}}return{status:_?`partial`:`published`,results:g}},referrersOf:m}}const pP=/* @__PURE__ */ new Set([400,404]),mP=e=>Jn(e)&&e.length<=64?e:void 0;function hP({cloudFetch:e,configFile:t,projectOf:n,serialized:r,sourceHashOf:i}){let a=()=>Gr(t).config.artifacts,o=async r=>{let o=a()[r]?.cloud;if(!o||o.identitySynced)return;let s=r.slice(r.indexOf(`/`)+1),c=o.sourceHash??await i(r).catch(()=>void 0),l=await e(`PATCH`,`/api/artifacts/${o.id}`,{...mP(s)?{slug:s}:{},project:n(r),...c?{sourceHash:c}:{}}),u=a()[r]?.cloud;(l.ok||pP.has(l.status))&&u?.id===o.id&&Yr(t,r,{cloud:{...u,identitySynced:!0,...c?{sourceHash:c}:{}}})};return async()=>{for(let[e,{cloud:t}]of Object.entries(a()))t&&!t.identitySynced&&await r(e,()=>o(e)).catch(()=>void 0)}}const gP=`modules.json`,_P=/^[a-z0-9-]{1,40}$/,vP=`1 to 40 lowercase letters, digits and dashes`,yP=e=>e===void 0?[]:Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:null;function bP(e,t){if(typeof e!=`object`||!e)return`module ${t+1} must be an object`;let{id:n,name:r,description:i=``,paths:a,aliases:o}=e;if(typeof n!=`string`||!_P.test(n))return`module id ${JSON.stringify(n)} must be ${vP}`;if(typeof r!=`string`||r.trim()===``)return`${n} needs a name`;if(r.length>60)return`${n}: a name is at most 60 characters`;if(typeof i!=`string`)return`${n}: description must be text`;if(i.length>200)return`${n}: a description is at most 200 characters`;let s=yP(a);if(!s)return`${n}: paths must be a list of globs`;let c=yP(o);if(!c)return`${n}: aliases must be a list of retired ids`;if(c.length>20)return`${n} has more than 20 aliases`;let l=c.find(e=>!_P.test(e));return l===void 0?{id:n,name:r,description:i,paths:s,aliases:c}:`alias ${JSON.stringify(l)} of ${n} must be ${vP}`}function xP(e){let t;try{t=JSON.parse(e)}catch(e){return{state:`invalid`,reason:`modules.json is not valid JSON: ${e.message}`}}let n=t?.modules;if(!Array.isArray(n))return{state:`invalid`,reason:`"modules" must be a list`};if(n.length>100)return{state:`invalid`,reason:`a vocabulary has at most 100 modules`};let r=[],i=/* @__PURE__ */ new Set;for(let[e,t]of n.entries()){let n=bP(t,e);if(typeof n==`string`)return{state:`invalid`,reason:n};if(i.has(n.id))return{state:`invalid`,reason:`duplicate module id: ${n.id}`};i.add(n.id),r.push(n)}for(let{id:e,aliases:t}of r){let n=t.find(e=>i.has(e));if(n!==void 0)return{state:`invalid`,reason:`alias ${JSON.stringify(n)} of ${e} is a live module id`}}return{state:`ok`,modules:r}}function SP(e){let t;try{t=d.default.readFileSync(p.default.join(e,gP),`utf8`)}catch{return{state:`missing`}}return xP(t)}function CP(e,t){let n=/* @__PURE__ */ new Set,r=[];for(let i of t){let t=e.some(e=>e.id===i)?[i]:e.filter(e=>e.aliases.includes(i)).map(e=>e.id);t.length===0&&r.push(i);for(let e of t)n.add(e)}return r.length?{unknown:r}:{ids:[...n].sort()}}function wP(e,t){let n=SP(e),{artifacts:r}=Gr(p.default.join(e,`config.json`)).config;if(n.state===`missing`)return Object.values(r).some(({cloud:e})=>e)?[`no vocabulary: create .ryugi/${gP}`]:[];if(n.state===`invalid`)return[`.ryugi/${gP} is invalid: ${n.reason}`];let i=`run ryugi modules --artifact ${t} --set <id>`,a=r[t]?.modules;if(!a)return[`no module: ${i}`];let o=CP(n.modules,a);return`unknown`in o?[`module no longer in the vocabulary: ${o.unknown.join(`, `)}; ${i}`]:[]}const TP=e=>e.map(({id:e,name:t,description:n,aliases:r})=>({id:e,name:t,description:n,aliases:r})),EP=e=>(0,u.createHash)(`sha256`).update(JSON.stringify(TP(e))).digest(`hex`);var DP=class extends Error{};function OP(e,...t){try{return(0,l.execFileSync)(`git`,[`-C`,e,...t],{encoding:`utf8`,timeout:2e3,stdio:[`ignore`,`pipe`,`ignore`],env:{...process.env,GIT_TERMINAL_PROMPT:`0`}}).trim()}catch(e){if(typeof e.status!=`number`)throw new DP;return null}}function kP(e){let t=OP(e,`symbolic-ref`,`--short`,`-q`,`refs/remotes/origin/HEAD`);return t?t.replace(/^origin\//,``):[`main`,`master`].find(t=>OP(e,`show-ref`,`--verify`,`-q`,`refs/heads/${t}`)!==null)??null}function AP(e){if(!OP(e,`remote`))return`replace`;let t=OP(e,`symbolic-ref`,`--short`,`-q`,`HEAD`);if(!t)return`add`;let n=kP(e);return n===null||n===t?`replace`:`add`}function jP(e){try{return Math.floor(d.default.statSync(e).mtimeMs)}catch{return 0}}function MP(e){if(d.default.existsSync(p.default.join(e,`.git`)))return!0;let t=p.default.dirname(e);return t!==e&&MP(t)}function NP(e,t){let n=p.default.relative(e,t);if(OP(e,`status`,`--porcelain`,`--`,n)!==``)return jP(t);let r=Number(OP(e,`log`,`-1`,`--format=%ct`,`--`,n));return r>0?r*1e3:jP(t)}function PP(e,t=p.default.join(e,`.ryugi`,gP)){try{return{mode:AP(e),revisedAt:NP(e,t)}}catch(n){if(!(n instanceof DP))throw n;return{mode:MP(e)?`add`:`replace`,revisedAt:jP(t)}}}const FP=(e,t)=>!!e&&e.length===t.length&&e.every((e,n)=>e===t[n]);function IP({cloudFetch:e,configFile:t,project:n}){let r=p.default.dirname(t),i=()=>Gr(t).config.artifacts;return{published:()=>Object.values(i()).some(({cloud:e})=>e),tagsOf:e=>{let t=i()[e]?.modules;return t?{modules:t}:{}},syncVocabulary:async()=>{let i=SP(r);if(i.state!==`ok`)return;let{mode:a,revisedAt:o}=PP(p.default.dirname(r),p.default.join(r,gP)),s=`${a}:${EP(i.modules)}`;Gr(t).config.modulesSynced!==s&&(await e(`PUT`,`/api/projects/modules`,{project:n,mode:a,revisedAt:o,modules:TP(i.modules)})).ok&&Xr(t,s)},syncTags:async()=>{for(let[n,{cloud:r,modules:a}]of Object.entries(i())){if(!r||!a||FP(r.modulesSynced,a))continue;let o=await e(`PUT`,`/api/artifacts/${r.id}/modules`,{modules:a}),s=i()[n]?.cloud;o.ok&&s?.id===r.id&&Yr(t,n,{cloud:{...s,modulesSynced:a}})}}}}var LP=class extends Error{};const RP=(e,t,n)=>{if(t!==`whiteboard`)return[];if(n?.has(`pages.json`))return Xe(n.get(`pages.json`)?.toString(`utf8`)??null).pages;try{return Xe(d.default.readFileSync(p.default.join(e,He),`utf8`)).pages}catch{return[]}},zP=e=>!!e.deleted&&e.id!==`main`;function BP(e,t,{maxBytes:n=Mr,overrides:r,uncounted:i}={}){let a=d.default.realpathSync(e),o=RP(e,t,r),s=new Set(o.filter(e=>zP(e)&&Ge(e.id)).map(e=>Ke(e.id))),c=o.some(zP)?new Map([...r??[],[He,Buffer.from(et(o.filter(e=>!zP(e))))]]):r,l=[],u=/* @__PURE__ */ new Set([a]),f=0,m=n=>{for(let r of d.default.readdirSync(n,{withFileTypes:!0})){if(r.name.startsWith(`.`))continue;let o=p.default.join(n,r.name),h;try{h=d.default.realpathSync(o)}catch{continue}if(!h.startsWith(a+p.default.sep))continue;let g=d.default.statSync(h);if(g.isDirectory()){if(u.has(h))continue;u.add(h),m(o);continue}if(!g.isFile())continue;let _=p.default.relative(e,o).split(p.default.sep).join(`/`);oj[t].keepsLocal(_)||s.has(_)||(!c?.has(_)&&!i?.has(_)&&(f+=g.size),l.push({path:_,real:h}))}};m(e);for(let e of c?.values()??[])e&&(f+=e.length);if(f>n)throw new LP(`artifact is ${oO(f)}; the limit is ${oO(n)}`);let h=e=>e===H[t]?Te[t]:e;return[...l.filter(e=>!c?.has(e.path)).map(e=>({path:h(e.path),data:d.default.readFileSync(e.real)})),...[...c??[]].flatMap(([e,t])=>t?[{path:h(e),data:t}]:[])]}const VP=(e,t)=>{let n=e.onProfile??t?.onProfile,r=e.shareKey===void 0?t?.keyed:e.shareKey!==null;return{...n===void 0?{}:{onProfile:n},...r?{keyed:!0}:{}}};function HP(e){let t=e.versions;return t?{...e,versions:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t>0]))}:Array.isArray(e.outline)?{...e,outline:e.outline.map(({overflow:e,...t})=>t)}:e}function UP(e,t){let{cloudFetch:n}=t,r=async()=>{let e={artifactBytes:Mr,cutBytes:Mr,fileBytes:Mr},t=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?e:Mr;try{let r=await n(`GET`,`/api/billing`);if(!r.ok)return e;let i=(await r.json()).limits,a=t(i?.artifactBytes);return{artifactBytes:a,cutBytes:t(i?.cutBytes),fileBytes:i?.fileBytes===void 0?a:t(i.fileBytes)}}catch(t){if(t instanceof iP)throw t;return e}};return async t=>{let n=await e.inspect(t);if(!n)throw new X(404,`${t.type}/${t.id} not found`);if(n.reasons.length>0||!n.payload)return{ready:!1,reasons:n.reasons};let i=oj[t.type],a=n.plan,o=a?.cut&&a.cut.bytes>20971520&&i.publishPlan?i.publishPlan.allowCut(a,(await r()).cutBytes):a,s=o?.overrides??n.fileOverrides,c=o?.uncounted,l=o&&!o.cut?{...n.payload,cuts:[]}:n.payload,f=(e=Mr)=>BP(n.dir,t.type,{overrides:s,uncounted:c,maxBytes:e}),m;try{m=f()}catch(e){if(!(e instanceof LP))throw new X(413,e.message);let t=await r();if(t.artifactBytes<=20971520)throw new X(413,e.message);try{m=f(t.artifactBytes)}catch(e){throw new X(413,e.message)}let n=m.find(e=>e.data.length>t.fileBytes&&!c?.has(e.path));if(n)throw new X(413,`${n.path} is ${oO(n.data.length)}; each file can be at most ${oO(t.fileBytes)}`)}let h=e=>u.default.createHash(`sha256`).update(e).digest(`hex`),g=UN(t.type,m).map(e=>({...e,hash:h(e.data)})),_={title:n.title,payload:l,files:g.map(({path:e,hash:t})=>({path:e,hash:t}))},v=m.map(e=>({path:e.path,hash:h(e.data)})),y=h(JSON.stringify({title:n.title,payload:HP(l),files:v})),b=e=>e===H[t.type]?Te[t.type]:e,x=new Set([...s??[]].flatMap(([e,t])=>t&&!d.default.existsSync(p.default.join(n.dir,e))?[b(e)]:[])),S=v.filter(e=>!x.has(e.path)),{comments:C,...w}=l,T=Object.fromEntries(Object.entries(w).filter(([e])=>!i.payloadNotFromSource?.includes(e)));return{ready:!0,hashed:g,content:_,fingerprint:y,sourceHash:h(JSON.stringify({title:n.title,payload:HP(T),files:S})),localFiles:S.map(e=>e.path===Te[t.type]?H[t.type]:e.path),cutHashes:new Set(g.filter(e=>c?.has(e.path)).map(e=>e.hash)),notes:o?.notes??[]}}}const WP=/^[0-9a-f]{7,64}$/;function GP(e,t){return(0,l.execFileSync)(`git`,t,{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:5e3}).trim()}function KP(e){try{let t=GP(e,[`rev-parse`,`HEAD`]);return WP.test(t)?t:null}catch{return null}}function qP(e,t){if(!WP.test(t))return!1;try{return GP(e,[`merge-base`,`--is-ancestor`,t,`HEAD`]),!0}catch{return!1}}function JP(e){try{let t=GP(e,[`remote`,`get-url`,`origin`]);return/[:/]([^/:]+)\/[^/]+?(?:\.git)?\/?$/.exec(t)?.[1]??null}catch{return null}}function YP(e){return async()=>{let t=Gr(e.configFile).config.space;if(t===`personal`)return{};let n=e.gitDir?JP(e.gitDir):null;if(!t&&!n)return{};let r=await e.cloudFetch(`GET`,`/api/spaces`);if(!r.ok){if(t)throw e.refuse(r.status,`Ryugi Cloud could not list your teams to publish to "${t}".`);return{}}let{spaces:i=[]}=await r.json(),a=i.filter(e=>e.kind===`team`&&e.slug);if(t){let n=a.find(e=>e.slug===t);if(!n)throw e.refuse(404,`This project publishes to team "${t}", which you are not in. Choose another with publish --space <team|personal>.`);return{id:n.id}}let o=n?a.find(e=>e.slug===n.toLowerCase()):void 0;return Qr(e.configFile,o?.slug??`personal`),o?{id:o.id,note:`Published to team ${o.slug}, because the git remote belongs to ${n}. Change it with publish --space <team|personal>.`}:{}}}async function XP(e){let{spaces:t=[]}=await(await e.expectOk(await e.cloudFetch(`GET`,`/api/spaces`))).json(),n=t.find(t=>t.kind===`team`&&t.slug===e.slug);if(!n)throw e.refuse(404,`You are not in a team named "${e.slug}".`);let{moved:r}=await(await e.expectOk(await e.cloudFetch(`POST`,`/api/projects/transfer`,{project:e.project,space:n.id}))).json();return Qr(e.configFile,e.slug),{id:e.slug,space:e.slug,moved:r}}const ZP=()=>{let e=/* @__PURE__ */ new Date;return e.setUTCHours(24,0,0,0),e.getTime()};function QP(e,t,n,r,i){let{configFile:a}=e,{autoPublishState:o,cloudFetch:s}=t,{artifactEntry:c,changedDuringPublish:l,expectOk:u,projectOf:d,publications:f,serialized:p,setPublication:m,snapshot:h}=n,g=e.root??null,_=YP({cloudFetch:(e,t)=>s(e,t),configFile:a,gitDir:g,refuse:(e,t)=>new X(e,t)}),v=/* @__PURE__ */ new Map,y=async(t,n,i)=>{let o=r.tagsOf(`${t.type}/${t.id}`),c={type:t.type,visibility:n,project:d(`${t.type}/${t.id}`),...mP(t.id)?{slug:t.id}:{},...o,...i===void 0?{}:{onProfile:i}},l=await _();l.note&&v.set(`${t.type}/${t.id}`,l.note);let f=l.id?{...c,space:l.id}:c,p=e.address?.(t),m=await s(`POST`,`/api/artifacts`,p&&qn(p)?{...f,id:p}:f);if(m.status===409&&(m=await s(`POST`,`/api/artifacts`,f)),m.status===403)throw new lP(await dP(m));let h=await(await u(m)).json();return Yr(a,`${t.type}/${t.id}`,{visibility:h.visibility,cloud:{id:h.id,url:h.url,publishedAt:null,visibility:h.visibility,identitySynced:!0,...VP(h),...o.modules?{modulesSynced:o.modules}:{}}}),h.id},b=async e=>{let t=`${e.type}/${e.id}`,n=c(t);if(n.cloud)return{url:n.cloud.url};if(n.autoPublish===!1||!o().enabled)return{url:null};try{await y(e,n.visibility??`private`)}catch(e){return e instanceof oP?{url:null,limit:{message:e.message,upgradeUrl:e.upgradeUrl}}:{url:null}}return{url:c(t).cloud?.url??null}},x=async t=>{let n=c(`${t.type}/${t.id}`).cloud;if(!n?.publishedAt){if(!await e.inspect(t))throw new X(404,`${t.type}/${t.id} not found`);return null}let r=await i(t);return r.ready?r.fingerprint===n.fingerprint:null},S=async e=>{let t=f.get(e);if(t&&t.phase!==`waiting`&&t.phase!==`published`)return h(e);let n=G(e);if(!n)throw new X(404,`artifact not found`);try{let r=await i(n);if(f.get(e)!==t)return h(e);let a=c(e).cloud;return{...h(e),...r.ready?{phase:a?.publishedAt&&a.fingerprint===r.fingerprint?`published`:`waiting`}:{phase:`not-ready`,reasons:r.reasons}}}catch(t){return{...h(e),phase:`failed`,message:t.message}}},C=async(e,t,{recreate:n=!0,skipUnchanged:o=!1,onProfile:l}={})=>{let f=await i(e);if(!f.ready)return{status:409,body:{error:`fix these before publishing`,code:`publish_not_ready`,reasons:f.reasons}};let{hashed:p,content:h,fingerprint:_,sourceHash:b,cutHashes:x,notes:S}=f,C=`${e.type}/${e.id}`,w=c(C),T=w.cloud;if(o&&T?.publishedAt&&T.fingerprint===_)return{status:200,body:{id:T.id,url:T.url,visibility:T.visibility,publishedAt:T.publishedAt,onProfile:T.onProfile===!0,keyed:T.keyed===!0}};let E=new Map(p.map(e=>[e.hash,e.data]));await r.syncVocabulary().catch(()=>void 0);let D=r.tagsOf(C),O=g?KP(g):null,k=T?.publishedAt?T.sourceHash:void 0,A=t=>({...h,project:d(C),...mP(e.id)?{slug:e.id}:{},sourceHash:b,...k?{baseSourceHash:k}:{},...O?{sourceCommit:O}:{},...D,...t?{visibility:t}:{},...l===void 0?{}:{onProfile:l}}),j=()=>y(e,t??w.visibility??`private`,l),ee=async(e,t)=>{let n=E.get(t);if(!n)throw new X(502,`cloud asked for a file this artifact does not have (${t})`);let r=x.has(t)?`?cut=1`:``;await u(await s(`PUT`,`/api/artifacts/${e}/blobs/${t}${r}`,new Uint8Array(n)))},M=async(e,t)=>{let n=t.filter(e=>!x.has(e));for(let t=0;t<n.length;t+=6)await Promise.all(n.slice(t,t+6).map(t=>ee(e,t)));for(let n of t)x.has(n)&&await ee(e,n)},N=!1,P=async(e,t)=>{m(C,{phase:`preparing`});let n=await s(`POST`,`/api/artifacts/${e}/versions`,A(t));if(n.status!==409)return n;let{missing:r,code:i,current:a}=await n.clone().json().catch(()=>({}));if(i===`publish_behind`){if(!N&&a?.sourceHash&&a.sourceCommit&&g&&qP(g,a.sourceCommit))return N=!0,k=a.sourceHash,P(e,t);throw new sP(cP(C,a??{}))}return Array.isArray(r)?(m(C,{phase:`uploading`}),await M(e,r),m(C,{phase:`publishing`}),s(`POST`,`/api/artifacts/${e}/versions`,A(t))):n},F=w.cloud?await P(w.cloud.id,t):await P(await j(),void 0);if(F.status===404&&w.cloud){if(!n&&w.cloud.publishedAt)throw new aP;F=await P(await j(),void 0)}let I=await(await u(F)).json();Yr(a,C,{visibility:I.visibility,cloud:{id:I.id,url:I.url,publishedAt:I.updatedAt,visibility:I.visibility,fingerprint:_,sourceHash:b,identitySynced:!0,...VP(I,c(C).cloud),...D.modules?{modulesSynced:D.modules}:{}}});let L=VP(I,c(C).cloud),te=v.get(C);return v.delete(C),te&&S.push(te),{status:200,body:{id:I.id,url:I.url,visibility:I.visibility,publishedAt:I.updatedAt,onProfile:L.onProfile===!0,keyed:L.keyed===!0,...S.length>0?{notes:S}:{}}}},w=async(e,t,n)=>{let r=`${e.type}/${e.id}`;l.delete(r),m(r,{phase:`preparing`});try{let i=await C(e,t,n);return m(r,i.status===200?{phase:l.has(r)?`waiting`:`published`,...Array.isArray(i.body.notes)?{message:i.body.notes.join(` `)}:{}}:{phase:`not-ready`,reasons:i.body.reasons}),i}catch(e){throw m(r,{phase:`failed`,message:e instanceof iP?`Sign in to Ryugi Cloud on this computer to publish.`:e.message.replace(/^cloud refused \(\d+\): /,``),autoPublish:!(e instanceof iP||e instanceof oP||e instanceof sP||e instanceof lP||e instanceof X&&e.status===413)}),e}},T=e=>p(e,()=>E(e)),E=async e=>{let t=G(e);if(!t)return{kind:`gone`};let n=c(e);if(n.autoPublish===!1)return{kind:`opted-out`};try{let e=await w(t,void 0,{recreate:!1,skipUnchanged:!0});if(e.status!==200){let t=e.body.reasons,n=Array.isArray(t)?t.find(e=>typeof e==`string`&&e.startsWith(`publish scan: `)):void 0;return n?{kind:`not-ready`,blocked:n}:{kind:`not-ready`}}return{kind:`published`,created:e.body.id!==n.cloud?.id}}catch(t){return t instanceof aP?(Yr(a,e,{cloud:null,autoPublish:!1}),{kind:`opted-out`}):t instanceof iP?{kind:`signed-out`}:t instanceof oP?{kind:`cannot-create`,message:t.message,upgradeUrl:t.upgradeUrl,...t.details.limit?.kind===`publishes`?{until:ZP()}:{}}:t instanceof lP?{kind:`cannot-create`,message:t.detail}:t instanceof X&&t.status===404?{kind:`gone`}:t instanceof X&&t.status===413?{kind:`cannot-create`,message:t.message,oversize:!0}:t instanceof X&&t.status===402?{kind:`cannot-create`,message:t.message.replace(/^cloud refused \(\d+\): /,``),...t.details.upgradeUrl?{upgradeUrl:t.details.upgradeUrl}:{}}:{kind:`failed`,message:t.message}}};return{autoPublish:T,publication:S,publish:w,reserve:b,upToDate:x}}async function $P(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>4096)throw new X(413,`request body too large`);t.push(r)}return Buffer.concat(t).toString(`utf8`)}async function eF(e){try{return JSON.parse(await $P(e)||`null`)}catch{return null}}const tF=/^[\w-]{1,64}$/,nF=/^\/api\/cloud\/(status|login|logout|artifacts|publish|publish-refs|publish-referrers|publication|refs|reserve|visibility|profile|share-key|auto-publish|sync|pull|transfer)(?:\/([^/]+)(?:\/([^/]+))?)?$/;function rF(e){let{pull:t}=e,{origin:n,credentialsFile:r,configFile:i,project:a}=e.options,{activeCredentials:o,autoPublishState:s,cloudFetch:c,deviceLogin:l,loginUrl:u,settingsFile:d,startLogin:f,withToken:p}=e.session,{artifactEntry:m,expectOk:h,keyOfCloudId:g,serialized:_}=e.store,{publication:v,publish:y,reserve:b,upToDate:x}=e.publisher,{adoptCloudVisibility:S,deleteCloud:C,setOnProfile:w,setShareKey:T,setVisibility:E,shareKeyCall:D}=e.sharing,{cascadeOf:O,publishReferrers:k,publishRefs:A,referrersOf:j}=e.cascade,ee=!1,M=async(e,p,M)=>{let[,N,P,F]=M,I=e.method??`GET`,L=P&&F?G(`${P}/${F}`):null;if(N===`status`&&I===`GET`&&!P){let e=o(),{config:t,warning:a}=Gr(i);B(p,200,{signedIn:!!e,login:e?.login??null,source:e?.source??null,origin:n,hostId:dM(r),artifacts:t.artifacts,autoPublish:{...s(),postponed:ee},pendingLogin:l.pending(),warning:a??null})}else if(N===`login`&&I===`POST`&&!P){let t=await eF(e);if(typeof t?.token==`string`){let e=t.token.trim();if(!e)throw new X(400,`token is required`);let i;try{i=await fetch(`${n}/api/me`,{headers:{...Er,Authorization:`Bearer ${e}`}})}catch(e){throw new X(502,`could not reach ${n}: ${e.message}`)}if(i.status===401)throw new X(401,`invalid or expired access token`);i.ok||await uP(i);let a=await i.json();if(typeof a.login!=`string`||!a.login)throw new X(502,`unexpected /api/me response from Ryugi Cloud`);xt(r,{origin:n,token:e,login:a.login}),B(p,200,{signedIn:!0,login:a.login,id:a.login});return}if(t?.source===`viewer`){B(p,200,{url:u(t.source)});return}let i;try{i=await f(t?.source)}catch(e){throw new X(502,`could not reach ${n}: ${e.message}`)}B(p,200,{signedIn:!1,pending:i,autoPublish:ti(d)===!0})}else if(N===`logout`&&I===`POST`&&!P){let e=o();if(e?.source===`env`){B(p,200,{signedIn:!0,source:`env`,remoteRevoked:!1});return}let t=!1;if(e){let r=await fetch(`${n}/api/logout`,{method:`POST`,headers:{...Er,Authorization:`Bearer ${e.token}`}}).catch(()=>null);t=!!r&&(r.ok||r.status===401)}St(r),B(p,200,{signedIn:!1,remoteRevoked:t})}else if(N===`artifacts`&&I===`GET`&&!P){let t=new URL(e.url??`/`,`http://localhost`).searchParams;t.delete(`key`);let n=await(await h(await c(`GET`,`/api/artifacts${t.size?`?${t}`:``}`))).json();S(n.artifacts),B(p,200,n)}else if(N===`pull`&&I===`POST`&&!P&&t){let n=await eF(e)??{},r=e=>typeof e==`string`&&e?e:void 0,i={target:r(n.target),project:r(n.project),as:r(n.as),dryRun:n.dryRun===!0,force:n.force===!0};B(p,200,await t(i))}else if(N===`artifacts`&&I===`DELETE`&&P&&!F){if(!tF.test(P))throw new X(400,`not a cloud artifact id`);await _(g(P),()=>C(P)),B(p,200,{deleted:P})}else if(N===`publish`&&L&&I===`POST`){let t=await eF(e);if(t?.visibility!==void 0&&!Lr(t.visibility))throw new X(400,`visibility must be "public" or "private"`);if(t?.onProfile!==void 0&&typeof t.onProfile!=`boolean`)throw new X(400,`onProfile must be true or false`);let n=`${L.type}/${L.id}`,r=t?.visibility,a=t?.onProfile,o=await _(n,async()=>{let e=await y(L,r,{onProfile:a});return e.status===200&&Yr(i,n,{autoPublish:null}),e});B(p,o.status,o.body)}else if(N===`refs`&&L&&I===`GET`){let t=new URL(e.url??`/`,`http://hub`).searchParams,n=t.get(`visibility`);if(n!==null&&!Lr(n))throw new X(400,`visibility must be "public" or "private"`);let r=n??Rr(m(`${L.type}/${L.id}`)).visibility;B(p,200,{visibility:r,items:await O(L,r),...t.get(`referrers`)===`0`?{}:await j(L)})}else if(N===`publish-referrers`&&L&&I===`POST`){let t=await eF(e),n=e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):[];B(p,200,await k(L,n(t?.publish),n(t?.makePublic)))}else if(N===`publish-refs`&&L&&I===`POST`){let t=await eF(e);if(t?.visibility!==void 0&&!Lr(t.visibility))throw new X(400,`visibility must be "public" or "private"`);let n=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:null,r=n(t?.refs??[]),i=n(t?.makePublic??[]);if(!r||!i)throw new X(400,`refs and makePublic must be lists of <type>/<id>`);B(p,200,await A(L,r,i,t?.visibility))}else if(N===`sync`&&L&&I===`GET`)B(p,200,{upToDate:await _(`${L.type}/${L.id}`,()=>x(L))});else if(N===`publication`&&L&&I===`GET`)B(p,200,await v(`${L.type}/${L.id}`));else if(N===`reserve`&&L&&I===`POST`)B(p,200,await _(`${L.type}/${L.id}`,()=>b(L)));else if(N===`publish`&&L&&I===`DELETE`){let e=`${L.type}/${L.id}`;await _(e,async()=>{let t=m(e);t.cloud&&await C(t.cloud.id),Yr(i,e,{autoPublish:!1})}),B(p,200,{unpublished:`${L.type}/${L.id}`})}else if(N===`visibility`&&L&&I===`POST`){let t=(await eF(e))?.visibility;if(!Lr(t))throw new X(400,`visibility must be "public" or "private"`);B(p,200,await E(L,t))}else if(N===`profile`&&L&&I===`POST`){let t=(await eF(e))?.shown;if(typeof t!=`boolean`)throw new X(400,`shown must be true or false`);B(p,200,await _(`${L.type}/${L.id}`,()=>w(L,t)))}else if(N===`share-key`&&L&&I===`GET`)B(p,200,await D(L,`GET`));else if(N===`share-key`&&L&&I===`DELETE`)B(p,200,await _(`${L.type}/${L.id}`,()=>D(L,`DELETE`)));else if(N===`share-key`&&L&&I===`PUT`){let t=await eF(e)??{};if(t.expires!==void 0&&!Fr(t.expires))throw new X(400,`expires must be 1d, 7d, 30d or never`);if(t.regenerate!==void 0&&typeof t.regenerate!=`boolean`)throw new X(400,`regenerate must be true or false`);let n={...t.expires?{expires:t.expires}:{},...t.regenerate?{regenerate:!0}:{}},r=await _(`${L.type}/${L.id}`,()=>T(L,n));B(p,r.status,r.body)}else if(N===`transfer`&&I===`POST`&&!P){let t=await eF(e);if(typeof t?.space!=`string`||!t.space)throw new X(400,`send {"space":"<team-slug>"}`);B(p,200,await XP({cloudFetch:c,configFile:i,expectOk:h,project:a,refuse:(e,t)=>new X(e,t),slug:t.space}))}else if(N===`auto-publish`&&I===`POST`&&P===`later`&&!F)ee=ri(d)===`postponed`,B(p,200,{...s(),postponed:ee});else if(N===`auto-publish`&&I===`POST`&&!P){let t=await eF(e),n=t?.value;if(t?.scope===`global`&&typeof n==`boolean`)ni(d,n);else if(t?.scope===`project`&&(typeof n==`boolean`||n===null))Zr(i,n);else throw new X(400,`send {"scope":"global","value":true|false} or {"scope":"project","value":true|false|null}`);B(p,200,s())}else z(p,404,`Not found`)};return{match:e=>nF.exec(e),async handle(e,t,n){let r=e.headers[`x-ryugi-cloud-token`],i=typeof r==`string`&&r.trim()?r.trim():void 0;await p(i,async()=>{try{await M(e,t,n)}catch(n){if(t.headersSent)return;if(n instanceof iP&&e.headers[`x-ryugi-client`]===`cli`){let e=await f(`publish-signed-out`).catch(()=>null);B(t,401,{error:`not signed in to the Ryugi cloud`,...e?{login:e}:{}})}else n instanceof iP?B(t,401,{error:`not signed in to the Ryugi cloud`,loginUrl:u(`publish-signed-out`)}):n instanceof oP?B(t,402,{error:n.message,...n.details}):n instanceof X?B(t,n.status,{error:n.message,...n.details}):B(t,500,{error:n.message})}})}}}const iF={viewBox:`0 -8.1 114.8 42.7`,width:114.8,height:42.7,markTransform:`translate(0 -8.1) scale(0.08340)`,wordTransform:`translate(46.6 0)`,strokeWidth:3.6,butt:[`M1.8 6.4V22.3`,`M29.18 6.4V15.65C29.18 18.52 31.51 20.85 34.38 20.85C37.25 20.85 39.58 18.52 39.58 15.65`,`M39.58 6.4V22.3`,`M52.08 7.85C55.56 7.85 58.38 10.76 58.38 14.35C58.38 17.94 55.56 20.85 52.08 20.85C48.6 20.85 45.78 17.94 45.78 14.35C45.78 10.76 48.6 7.85 52.08 7.85Z`,`M58.38 6.4V22.9`,`M65.38 6.4V22.3`],round:[`M1.8 14.05C1.8 10.2 4.32 7.85 6.8 7.85`,`M17.5 22.3L15.77 27.5`,`M58.38 22.9C58.38 25.74 55.56 28.05 52.08 28.05L50.68 28.05`],clipped:[`M11.2 3.4L17.5 22.3`,`M23.8 3.4L17.5 22.3`],clipRect:{x:-5,y:6.4,width:77.18,height:26.1},seal:{x:63.04,y:.02,size:4.68,rx:1.03},mask:{x:-20,y:-18.1,width:194.8,height:62.7},band:{x:-82,y:-18.1,width:62,height:62.7},bandStops:[{offset:0,color:`#c65d3b`,opacity:0},{offset:.3,color:`#c65d3b`,opacity:1},{offset:.52,color:`#f3b866`,opacity:1},{offset:.74,color:`#c65d3b`,opacity:1},{offset:1,color:`#c65d3b`,opacity:0}],sweep:{from:`translateX(0) skewX(-12deg)`,to:`translateX(220px) skewX(-12deg)`,duration:1200,easing:`cubic-bezier(.3,.6,.2,1)`}},aF={viewBox:`46.6 0 67.72 29.85`,x:46.6,y:0,width:67.72,height:29.85,baseline:22.3},oF={light:`#c65d3b`,dark:`#e0714c`},sF=e=>`rw${e.replaceAll(/[^\w-]/g,``)}`,cF=(e,t,n,r,i)=>{let a=iF,o=(e,t)=>e.map(e=>`<path d="${e}" stroke-linecap="${t}"/>`).join(``);return(r?`<g fill="${e}" transform="${a.markTransform}"><g transform="translate(82 136.317460) scale(0.613756614)"><g transform="translate(0.000000,390.000000) scale(0.100000,-0.100000)" stroke="none"><path d="M4945 3889 c-339 -44 -682 -239 -905 -517 -139 -172 -232 -355 -365 -717 -136 -368 -285 -735 -360 -890 -219 -449 -524 -768 -849 -887 -121 -44 -215 -60 -356 -60 -162 0 -244 18 -450 97 -291 111 -420 144 -650 166 -257 24 -637 -19 -772 -87 -148 -75 -249 -247 -235 -399 19 -197 186 -344 392 -346 40 -1 127 11 205 27 115 23 160 28 300 28 242 1 372 -29 671 -155 226 -95 467 -149 662 -149 252 0 548 74 789 197 394 201 708 521 988 1008 83 144 271 529 405 830 220 493 300 632 436 759 121 112 226 162 424 201 44 9 108 29 143 45 165 77 274 285 244 467 -31 188 -168 334 -354 378 -70 16 -249 18 -363 4z M765 3139 c-202 -11 -415 -48 -497 -86 -91 -44 -151 -101 -193 -186 -123 -248 31 -525 307 -554 38 -4 99 3 204 23 137 27 167 29 384 29 205 0 249 -3 347 -23 225 -45 387 -106 658 -247 182 -94 308 -144 463 -182 138 -35 350 -39 447 -9 174 53 275 152 305 299 26 130 -40 267 -158 323 -52 25 -72 28 -227 35 -248 11 -328 37 -576 187 -232 140 -384 213 -585 281 -283 95 -541 127 -879 110z M620 2104 c-273 -32 -384 -65 -471 -143 -235 -208 -136 -589 172 -660 68 -16 129 -13 272 14 400 73 702 31 1167 -163 239 -99 350 -125 535 -125 193 0 338 51 448 157 117 113 139 261 56 375 -50 69 -99 85 -294 92 -245 10 -332 35 -563 163 -224 123 -456 211 -693 262 -111 23 -149 26 -359 29 -129 2 -251 1 -270 -1z"/></g></g></g>`:``)+`<g transform="${a.wordTransform}" fill="none" stroke="${e}" stroke-width="${a.strokeWidth}" stroke-linejoin="round">`+o(a.butt,`butt`)+o(a.round,`round`)+`<g clip-path="url(#${n})">${o(a.clipped,`butt`)}</g><rect${i?` id="${i}"`:``} x="${a.seal.x}" y="${a.seal.y}" width="${a.seal.size}" height="${a.seal.size}" rx="${a.seal.rx}" fill="${t}" stroke="none"/></g>`};function lF({height:e=22,mark:t=!0,ink:n=`currentColor`,seal:r=oF.light,sealDark:i,idPrefix:a,hover:o=!1,title:s}){let c=iF,l=t?c:aF,u=Math.round(e*l.width/l.height*100)/100,d=sF(a),f=`${d}-clip`,p=s?`role="img" aria-label="${s.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`).replaceAll(`<`,`&lt;`)}"`:`aria-hidden="true"`,{x:m,y:h,width:g,height:_}=c.clipRect,v=`<clipPath id="${f}"><rect x="${m}" y="${h}" width="${g}" height="${_}"/></clipPath>`,y=i?`@media (prefers-color-scheme: dark){#${d}-seal{fill:${i}}}`:``,b=``;if(o){let{mask:e,band:n,sweep:r}=c,i=c.bandStops.map(e=>`<stop offset="${e.offset}" stop-color="${e.color}" stop-opacity="${e.opacity}"/>`).join(``);v+=`<linearGradient id="${d}-ember">${i}</linearGradient><mask id="${d}-mask" maskUnits="userSpaceOnUse" x="${e.x}" y="${e.y}" width="${e.width}" height="${e.height}">${cF(`#fff`,`#fff`,f,t)}</mask>`;let a=`#${d}-band`;y+=`@media (prefers-reduced-motion: no-preference){#${d}:hover ${a},:is(a,button):is(:hover,:focus-visible) ${a}{animation:${d}-sweep ${r.duration}ms ${r.easing}}}@keyframes ${d}-sweep{from{transform:${r.from}}to{transform:${r.to}}}`,b=`<g mask="url(#${d}-mask)"><rect id="${d}-band" x="${n.x}" y="${n.y}" width="${n.width}" height="${n.height}" fill="url(#${d}-ember)"/></g>`}return`<svg xmlns="http://www.w3.org/2000/svg" id="${d}" width="${u}" height="${e}" viewBox="${l.viewBox}" ${p}>${y?`<style>${y}</style>`:``}<defs>${v}</defs>${cF(n,r,f,t,i?`${d}-seal`:void 0)}${b}</svg>`}const uF={en:`en`,zh:`zh-CN`};function dF(e){for(let t of e){let e=t.split(`-`)[0]?.trim().toLowerCase();if(e===`zh`)return`zh`;if(e===`en`)return`en`}return`en`}function fF(e){return e?e.split(`,`).map((e,t)=>{let[n=``,...r]=e.trim().split(`;`),i=r.map(e=>e.trim()).find(e=>e.startsWith(`q=`));return{tag:n.trim(),q:i?Number(i.slice(2)):1,index:t}}).filter(e=>e.tag&&!Number.isNaN(e.q)&&e.q>0).sort((e,t)=>t.q-e.q||e.index-t.index).map(e=>e.tag):[]}function pF(e,t){let n=e;for(let e of t.split(`.`))n=typeof n==`object`?n[e]:void 0;return typeof n==`string`?n:void 0}function mF(e,t,n,r){if(typeof r==`number`){let i=pF(e,`${t}_${new Intl.PluralRules(n).select(r)}`)??pF(e,`${t}_other`);if(i!==void 0)return i}return pF(e,t)}function hF(e,t){return(n,r={})=>(mF(e[t],n,t,r.count)??mF(e.en,n,`en`,r.count)??n).replaceAll(/\{\{(\w+)\}\}/g,(e,t)=>t in r?String(r[t]):e)}var gF={callback:{titleOk:`Signed in to Ryugi Cloud`,titleFailed:`Sign-in didn't finish`,connected:`Connected to Ryugi Cloud`,signedIn:`Signed in as`,lead:`Ryugi on this computer can publish artifacts now.`,fromPage:`Published from a Ryugi page?`,fromPageDetail:`Go back to Ryugi; the share panel refreshes on its own.`,fromAgent:`Asked the agent to publish?`,fromAgentDetail:`Have it run the publish command again.`,autoPublishOn:`Auto-publish is on`,autoPublishOff:`Auto-publish is off`,autoPublishDetail:`After each agent turn, changed artifacts sync privately to Ryugi Cloud, so you can open them on another device. Only you can see them.`,autoPublishTurnOn:`Turn on auto-publish`,autoPublishTurnOff:`Turn off auto-publish`,autoPublishWhere:`Change it any time in Settings, from your avatar at the top right of the artifact list.`,notConnected:`Not connected`,description:`Result of signing in to Ryugi Cloud on this computer. Once connected, go back to Ryugi to publish and share artifacts.`,closeOk:`You can close this page`,closeFailed:`You can close this page and try again`,whatNext:`What next`,toTryAgain:`To try again`,stepBack:`Go back to Ryugi`,stepBackDetail:`The page or terminal where you started signing in.`,stepSignIn:`Click Sign in in the share panel again`,stepSignInDetail:`Each sign-in link works once, for a few minutes.`,otherReasons:`Other reasons this page shows`,reasonUnreachable:`Couldn't reach Ryugi Cloud: check your network, then sign in again.`,reasonRefused:`Ryugi Cloud didn't accept this sign-in: the reason shows in place of the text above.`,terms:`Terms of Service`,privacy:`Privacy Policy`},login:{expired:`This sign-in link has expired or was already used. Go back to Ryugi and sign in again.`,unreachable:`Couldn't reach {{origin}} ({{message}}). Check your network, then go back to Ryugi and sign in again.`,refused:`Ryugi Cloud didn't accept this sign-in ({{reason}}). Go back to Ryugi and sign in again.`},meta:{artifact:`View {{title}} in the {{project}} project. This is a {{type}} artifact.`,library:`Browse every artboard, document and HTML artifact in the {{project}} project, preview their content, and find them by type, name or update time.`}},_F={callback:{titleOk:`已登录 Ryugi Cloud`,titleFailed:`登录没有完成`,connected:`已连接 Ryugi Cloud`,signedIn:`已登录`,lead:`这台电脑上的 Ryugi 现在可以发布 artifact 了。`,fromPage:`在 Ryugi 页面里发布的?`,fromPageDetail:`回到 Ryugi,分享面板会自动刷新。`,fromAgent:`让 agent 发布的?`,fromAgentDetail:`让它再运行一次发布命令。`,autoPublishOn:`自动发布已打开`,autoPublishOff:`自动发布已关闭`,autoPublishDetail:`agent 每轮结束后,改过的 artifact 会以私密方式同步到 Ryugi Cloud,换台设备也能打开。只有你能看到。`,autoPublishTurnOn:`打开自动发布`,autoPublishTurnOff:`关闭自动发布`,autoPublishWhere:`以后在 Artifacts 列表右上角头像 › 设置 里随时修改。`,notConnected:`未连接`,description:`Ryugi Cloud 本地登录结果。完成连接后,返回 Ryugi 继续发布和分享 Artifact。`,closeOk:`可以关闭这个页面`,closeFailed:`可以关闭这个页面后重试`,whatNext:`接下来`,toTryAgain:`重新登录`,stepBack:`回到 Ryugi`,stepBackDetail:`就是你发起登录的那个页面或终端。`,stepSignIn:`在分享面板里再点一次「登录」`,stepSignInDetail:`每个登录链接只能用一次,几分钟内有效。`,otherReasons:`出现这个页面的其他原因`,reasonUnreachable:`连不上 Ryugi Cloud:检查网络后重新登录。`,reasonRefused:`Ryugi Cloud 没有接受这次登录:原因会显示在上面的说明里。`,terms:`服务条款`,privacy:`隐私政策`},login:{expired:`这个登录链接已过期或已经用过。回到 Ryugi 重新发起一次登录。`,unreachable:`连不上 {{origin}}({{message}})。检查网络后回到 Ryugi 重新发起登录。`,refused:`Ryugi Cloud 没有接受这次登录({{reason}})。回到 Ryugi 重新发起登录。`},meta:{artifact:`在 {{project}} 项目中查看 {{title}},这是一个 {{type}} Artifact。`,library:`浏览 {{project}} 项目的全部 Artboard、Document 和 HTML Artifact,预览真实内容,按类型、名称和更新时间查找作品。`}};const vF=e=>hF({en:gF,zh:_F},e),yF=e=>e.replaceAll(/[&<>"']/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`})[e]),bF=(e,t=14)=>`<svg width="${t}" height="${t}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${e}</svg>`,xF=bF(`<circle cx="12" cy="12" r="10"/><path d="m16 9-5.5 5.5L8 12"/>`),SF=bF(`<circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/>`),CF=bF(`<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M3 9h18"/>`,15),wF=bF(`<path d="m4 17 6-6-6-6"/><path d="M12 19h8"/>`,15),TF=bF(`<path d="M20 6 9 17l-5-5"/>`),EF=lF({idPrefix:`callback-mark`,sealDark:oF.dark,title:`ryugi`}),DF=(e,t,n)=>`<li>${e}<div><b>${t}</b><span>${n}</span></div></li>`,OF=(e,t,n)=>`<section class="card auto"><form method="post" action="/api/cloud/callback/auto-publish">
517
- <input type="hidden" name="ticket" value="${yF(n)}">
518
- <span class="text"><b>${e(t?`callback.autoPublishOn`:`callback.autoPublishOff`)}</b><span>${e(`callback.autoPublishDetail`)}</span></span>
519
- <button class="switch" type="submit" name="value" value="${t?`off`:`on`}" role="switch" aria-checked="${t}" aria-label="${e(t?`callback.autoPublishTurnOff`:`callback.autoPublishTurnOn`)}"><i></i></button>
520
- </form><p class="where">${e(`callback.autoPublishWhere`)}</p></section>`,kF=(e,t)=>`<p class="pill">${xF}${e(`callback.connected`)}</p>
521
- <h1><span>${e(`callback.signedIn`)}</span> ${yF(t.login)}</h1>
522
- <p class="lead">${e(`callback.lead`)}</p>
523
- ${OF(e,t.autoPublish,t.ticket)}
524
- <p class="label">${e(`callback.whatNext`)}</p>
525
- <ul class="card">${DF(`<span class="icon">${CF}</span>`,e(`callback.fromPage`),e(`callback.fromPageDetail`))}${DF(`<span class="icon">${wF}</span>`,e(`callback.fromAgent`),e(`callback.fromAgentDetail`))}</ul>
526
- <footer>${TF}<span>${e(`callback.closeOk`)}</span></footer>`,AF=(e,t)=>`<p class="pill">${SF}${e(`callback.notConnected`)}</p>
527
- <h1>${e(`callback.titleFailed`)}</h1>
528
- <p class="lead">${yF(t.detail)}</p>
529
- <p class="label">${e(`callback.toTryAgain`)}</p>
530
- <ol class="card">${DF(`<span class="step">1</span>`,e(`callback.stepBack`),e(`callback.stepBackDetail`))}${DF(`<span class="step">2</span>`,e(`callback.stepSignIn`),e(`callback.stepSignInDetail`))}</ol>
531
- <details><summary>${e(`callback.otherReasons`)}</summary><ul><li>${e(`callback.reasonUnreachable`)}</li><li>${e(`callback.reasonRefused`)}</li></ul></details>
532
- <footer><span>${e(`callback.closeFailed`)}</span></footer>`;function jF(e,t=`en`){let n=vF(t),r=e.origin.replace(/\/+$/,``),i=yF(new URL(r).host),a=t===`zh`?`/zh`:``,o=`<div class="legal-links"><a href="${yF(`${r}${a}/terms`)}" target="_blank" rel="noopener noreferrer">${n(`callback.terms`)}</a><span aria-hidden="true">·</span><a href="${yF(`${r}${a}/privacy`)}" target="_blank" rel="noopener noreferrer">${n(`callback.privacy`)}</a></div>`,s=e.ok?n(`callback.titleOk`):n(`callback.titleFailed`);return`<!doctype html>
533
- <html lang="${uF[t]}">
534
- <head>
535
- <meta charset="utf-8">
536
- <meta name="viewport" content="width=device-width, initial-scale=1">
537
- <meta name="referrer" content="no-referrer">
538
- <meta name="robots" content="noindex, nofollow">
539
- <meta name="description" content="${n(`callback.description`)}">
540
- <title>${s}</title>
541
- <style>
542
- :root {
543
- color-scheme: light dark;
544
- --bg: #fafafa;
545
- --card: #ffffff;
546
- --ink: #0a0a0a;
547
- --soft: #525252;
548
- --faint: #6b6b6b;
549
- --quiet: #737373;
550
- --rule: #e5e5e5;
551
- --hair: #f0f0f0;
552
- --tile: #f5f5f5;
553
- --tile-ink: #404040;
554
- --knob: #ffffff;
555
- --ok: #15803d;
556
- --ok-bg: #f0fdf4;
557
- --ok-rule: #bbf7d0;
558
- --bad: #b91c1c;
559
- --bad-bg: #fef2f2;
560
- --bad-rule: #fecaca;
561
- --focus: #2563eb;
562
- --sans: Figtree, Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Noto Sans CJK SC", system-ui, sans-serif;
563
- --mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;
564
- }
565
- @media (prefers-color-scheme: dark) {
566
- :root {
567
- --bg: #0a0a0a;
568
- --card: #111111;
569
- --ink: #ededed;
570
- --soft: #a1a1a1;
571
- --faint: #8f8f8f;
572
- --quiet: #8f8f8f;
573
- --rule: #2e2e2e;
574
- --hair: #1f1f1f;
575
- --tile: #1c1c1c;
576
- --tile-ink: #d4d4d4;
577
- --knob: #a1a1a1;
578
- --ok: #4ade80;
579
- --ok-bg: #052e16;
580
- --ok-rule: #14532d;
581
- --bad: #f87171;
582
- --bad-bg: #2a0a0a;
583
- --bad-rule: #5c1a1a;
584
- --focus: #60a5fa;
585
- }
586
- }
587
- * { box-sizing: border-box; }
588
- html, body { margin: 0; }
589
- body {
590
- min-height: 100vh;
591
- display: flex;
592
- flex-direction: column;
593
- background: var(--bg);
594
- color: var(--ink);
595
- font-family: var(--sans);
596
- -webkit-font-smoothing: antialiased;
597
- }
598
- :focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
599
- header { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 20px 24px; }
600
- .mark { display: flex; align-items: center; }
601
- .host { font: 12px var(--mono); color: var(--faint); }
602
- main { flex: 1; display: flex; align-items: center; justify-content: center; padding: 40px 20px 64px; }
603
- .column { width: 100%; max-width: 460px; }
604
- .pill { display: inline-flex; align-items: center; gap: 6px; margin: 0; padding: 4px 10px 4px 8px; border: 1px solid; border-radius: 999px; font-size: 12px; font-weight: 500; }
605
- .signed-in .pill { color: var(--ok); background: var(--ok-bg); border-color: var(--ok-rule); }
606
- .failed .pill { color: var(--bad); background: var(--bad-bg); border-color: var(--bad-rule); }
607
- h1 { margin: 20px 0 8px; font-size: 30px; line-height: 1.2; font-weight: 600; letter-spacing: -0.025em; overflow-wrap: anywhere; }
608
- h1 span { color: var(--quiet); }
609
- .lead { margin: 0; font-size: 15px; line-height: 1.6; color: var(--soft); }
610
- .card { margin: 0; padding: 0; list-style: none; border: 1px solid var(--rule); border-radius: 12px; background: var(--card); }
611
- .auto { margin-top: 28px; }
612
- .auto form { display: flex; align-items: flex-start; gap: 16px; margin: 0; padding: 16px; }
613
- .auto .text { flex: 1; min-width: 0; }
614
- .auto b { display: block; margin-bottom: 4px; font-size: 14px; font-weight: 500; }
615
- .auto .text span { display: block; font-size: 13px; line-height: 1.55; color: var(--soft); }
616
- .auto .where { margin: 0; padding: 12px 16px; border-top: 1px solid var(--hair); font-size: 12px; line-height: 1.5; color: var(--faint); }
617
- .switch { flex: none; display: flex; width: 44px; height: 26px; margin-top: 2px; padding: 3px; border: 0; border-radius: 999px; background: var(--rule); cursor: pointer; }
618
- .switch[aria-checked="true"] { justify-content: flex-end; background: var(--ink); }
619
- .switch[aria-checked="true"] i { background: var(--bg); }
620
- .switch i { width: 20px; height: 20px; border-radius: 999px; background: var(--knob); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); }
621
- .label { margin: 32px 0 10px; font: 500 11px var(--mono); letter-spacing: 0.06em; text-transform: uppercase; color: var(--faint); }
622
- .card li { display: flex; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--hair); }
623
- .card li:last-child { border-bottom: 0; }
624
- .icon { flex: none; display: flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 8px; background: var(--tile); color: var(--tile-ink); }
625
- .step { flex: none; display: flex; align-items: center; justify-content: center; width: 24px; height: 24px; border: 1px solid var(--rule); border-radius: 999px; font: 12px var(--mono); color: var(--tile-ink); }
626
- .card b { display: block; margin-bottom: 2px; font-size: 14px; font-weight: 500; }
627
- .card li span:not(.icon):not(.step) { font-size: 13px; line-height: 1.5; color: var(--soft); }
628
- details { margin-top: 16px; border: 1px solid var(--rule); border-radius: 12px; background: var(--card); }
629
- summary { padding: 12px 16px; font-size: 13px; color: var(--tile-ink); cursor: pointer; }
630
- details ul { margin: 0; padding: 0 16px 14px 32px; font-size: 13px; line-height: 1.7; color: var(--soft); }
631
- footer { display: flex; align-items: center; gap: 8px; margin-top: 28px; font-size: 13px; color: var(--faint); }
632
- .legal-links { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; font-size: 12px; color: var(--faint); }
633
- .legal-links a { color: var(--soft); text-decoration: none; }
634
- .legal-links a:hover { color: var(--ink); text-decoration: underline; }
635
- @media (max-width: 640px) {
636
- header { padding: 14px 20px; border-bottom: 1px solid var(--rule); }
637
- main { align-items: flex-start; padding: 28px 20px 40px; }
638
- h1 { margin-top: 16px; font-size: 26px; line-height: 1.22; }
639
- }
640
- </style>
641
- </head>
642
- <body>
643
- <header><span class="mark">${EF}</span><span class="host">${i}</span></header>
644
- <main class="${e.ok?`signed-in`:`failed`}">
645
- <div class="column">
646
- ${e.ok?kF(n,e):AF(n,e)}
647
- ${o}
648
- </div>
649
- </main>
650
- </body>
651
- </html>
652
- `}const MF=/* @__PURE__ */ new Map,NF=/^[a-z0-9-]{1,40}$/,PF=/* @__PURE__ */ new Map;function FF(e){let{origin:t,credentialsFile:n,configFile:r}=e,i=$r(n),a=new v.AsyncLocalStorage,o=()=>vt(n,t,process.env,a.getStore()),s=()=>({global:ti(i)??null,project:Gr(r).config.autoPublish??null,enabled:!!o()&&ai({globalFile:i,projectFile:r})}),c=Ar(t,n,y),l=e=>c.start(typeof e==`string`&&NF.test(e)?e:void 0),d=e=>{let t=Date.now();for(let[e,n]of PF)n.expires<t&&PF.delete(e);let n=F();return PF.set(n,{expires:t+18e5,login:e}),n},f=(e,n,r,i)=>z(e,n,jF({...r,origin:t},i),{"Content-Type":`text/html; charset=utf-8`,"Content-Security-Policy":`default-src 'none'; style-src 'unsafe-inline'; img-src data:; script-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'`}),p=(e,t,n,r)=>f(e,200,{ok:!0,login:n,ticket:t,autoPublish:ti(i)??!1},r);return{activeCredentials:o,autoPublishState:s,cloudFetch:async(e,n,r)=>{let i=o();if(!i)throw new iP;let a={...Er,Authorization:`Bearer ${i.token}`},s;r instanceof Uint8Array?(a[`Content-Type`]=`application/octet-stream`,s=r):r&&(a[`Content-Type`]=`application/json`,s=JSON.stringify(r));let c;try{c=await fetch(`${t}${n}`,{method:e,headers:a,body:s})}catch(e){throw new X(502,`could not reach ${t}: ${e.message}`)}if(c.status===401)throw new iP;return c},deviceLogin:c,loginUrl:n=>{let r=Date.now();for(let[e,t]of MF)t.expires<r&&MF.delete(e);let i=F(),a=F();MF.set(i,{expires:r+6e5,verifier:a});let o=u.default.createHash(`sha256`).update(a).digest(`base64url`),s=typeof n==`string`&&NF.test(n)?`&src=${n}`:``;return`${t}/auth/cli?port=${e.port()}&state=${i}&challenge=${o}${s}`},settingsFile:i,startLogin:l,withToken:(e,t)=>a.run(e,t),async handleCallback(e,r,a=`en`){let o=vF(a),s=(e,t)=>f(r,e,t,a),c=e.searchParams.get(`state`)??``,l=MF.get(c);MF.delete(c);let u=e.searchParams.get(`code`);if(!l||l.expires<Date.now()||!u){s(400,{ok:!1,detail:o(`login.expired`)});return}let m;try{m=await fetch(`${t}/auth/cli/token`,{method:`POST`,headers:{...Er,"Content-Type":`application/json`},body:JSON.stringify({code:u,verifier:l.verifier})})}catch(e){s(502,{ok:!1,detail:o(`login.unreachable`,{origin:t,message:e.message})});return}let h=await m.json().catch(()=>({}));!m.ok||typeof h.token!=`string`||typeof h.login!=`string`?s(400,{ok:!1,detail:o(`login.refused`,{reason:typeof h.error==`string`?h.error:`HTTP ${m.status}`})}):(xt(n,{origin:t,token:h.token,login:h.login}),ii(i),p(r,d(h.login),h.login,a))},async handleCallbackAutoPublish(e,t,n=`en`){if(e.method!==`POST`){z(t,405,`Method not allowed`);return}let r=new URLSearchParams(await $P(e)),a=r.get(`ticket`)??``,o=PF.get(a),s=r.get(`value`);!o||o.expires<Date.now()?z(t,403,`Forbidden`):s!==`on`&&s!==`off`?z(t,400,`value must be on or off`):(ni(i,s===`on`),p(t,a,o.login,n))}}}function IF(e,t,n,r){let{configFile:i,origin:a}=e,{cloudFetch:o}=t,{artifactEntry:s,expectOk:c,setPublication:l}=n,u=async(t,n)=>{if(!await e.inspect(t))throw new X(404,`${t.type}/${t.id} not found`);let r=`${t.type}/${t.id}`,a=s(r);if(a.cloud){let e=await o(`PATCH`,`/api/artifacts/${a.cloud.id}`,{visibility:n});if(e.status===404)Yr(i,r,{cloud:null});else{let t=await(await c(e)).json(),{keyed:n,...o}=a.cloud;Yr(i,r,{cloud:{...o,visibility:t.visibility,...VP(t,a.cloud)}})}}return Yr(i,r,{visibility:n})},d=e=>{let t=s(`${e.type}/${e.id}`).cloud;if(!t?.publishedAt)throw new X(409,`Publish it first.`);return t},f=async(e,t)=>{let n=`${e.type}/${e.id}`,r=d(e),a=await(await c(await o(`PATCH`,`/api/artifacts/${r.id}`,{onProfile:t}))).json();return Yr(i,n,{cloud:{...r,onProfile:a.onProfile??t}})},p=(e,t)=>{let n=`${e.type}/${e.id}`,r=s(n).cloud;if(!r)return;let{keyed:a,...o}=r;Yr(i,n,{cloud:t?{...o,keyed:!0}:o})},m=async(e,t,n)=>{let r=d(e),{shareKey:i}=await(await c(await o(t,`/api/artifacts/${r.id}/share-key`,n))).json();return t!==`GET`&&p(e,i!==null),{shareKey:i}};return{adoptCloudVisibility:e=>{let t=new Map(e.map(e=>[e.id,e.visibility])),n=new Map(e.map(e=>[e.id,e]));for(let[e,r]of Object.entries(Gr(i).config.artifacts)){let a=r.cloud&&t.get(r.cloud.id);if(!r.cloud||!a)continue;let{keyed:o,...s}=r.cloud,c={...s,visibility:a,...VP(n.get(r.cloud.id),r.cloud)};(r.visibility!==a||r.cloud.visibility!==a||c.onProfile!==r.cloud.onProfile||c.keyed!==r.cloud.keyed)&&Yr(i,e,{visibility:a,cloud:c})}},deleteCloud:async e=>{let t=await o(`DELETE`,`/api/artifacts/${e}`);t.status!==404&&await c(t);for(let[t,n]of Object.entries(Gr(i).config.artifacts))n.cloud?.id===e&&(Yr(i,t,{cloud:null,autoPublish:!1}),l(t,{phase:`waiting`}))},setOnProfile:f,setShareKey:async(e,t)=>{let n=`${e.type}/${e.id}`;if(!s(n).cloud?.publishedAt){let t=await o(`GET`,`/api/billing`);if((t.ok?(await t.json()).plan:null)===`free`)throw new X(402,`Links with a key need a subscription.`,{code:`plan_required`,upgradeUrl:`${a}/billing`});let n=await r(e,`private`);if(n.status!==200)return n}try{return{status:200,body:await m(e,`PUT`,t)}}catch(e){if(!(e instanceof X)||e.details.code!==`share_key_needs_private`)throw e}return await u(e,`private`),{status:200,body:await m(e,`PUT`,t)}},setVisibility:u,shareKeyCall:m}}function LF(e,t){let{configFile:n,project:r}=e,{autoPublishState:i}=t,a=async e=>(e.ok||await uP(e),e),o=e=>Gr(n).config.artifacts[e]??{},s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Set,l=e=>({phase:o(e).cloud?.publishedAt?`published`:`waiting`,...s.get(e),publishedAt:o(e).cloud?.publishedAt??null,autoPublish:i().enabled&&o(e).autoPublish!==!1&&s.get(e)?.autoPublish!==!1}),u=(t,n)=>{s.set(t,n),e.onPublication?.(t,l(t))},d=/* @__PURE__ */ new Map;return{artifactEntry:o,changedDuringPublish:c,expectOk:a,keyOfCloudId:e=>Object.entries(Gr(n).config.artifacts).find(([,t])=>t.cloud?.id===e)?.[0]??`cloud:${e}`,projectOf:e=>o(e).project??r,publications:s,serialized:(e,t)=>{let n=(d.get(e)??Promise.resolve()).then(t,t),r=n.catch(()=>void 0);return d.set(e,r),r.then(()=>{d.get(e)===r&&d.delete(e)}),n},setPublication:u,snapshot:l}}const RF=/\.(?:webm|mp4|mov|m4v)$/i,zF=e=>e.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`).replaceAll(/^-+|-+$/g,``);function BF(e,t,n){return zF(t??``).slice(0,64).replace(/-+$/,``)||`${e}-${zF(n)}`}const VF=(e,t)=>t??(e.slug||BF(e.type,e.title,e.id));function HF({cloud:e,local:t,force:n=!1}){if(!t.exists)return`created`;let{record:r}=t,i=!!e.sourceHash&&t.sourceHash===e.sourceHash;if(r&&r.id!==e.id)return`name_clash`;if(!r)return i?`bound`:n?`updated`:`name_clash`;if(i)return`up_to_date`;let a=r.sourceHash?t.sourceHash!==r.sourceHash:!r.fingerprint||t.fingerprint!==r.fingerprint,o=e.sourceHash&&r.sourceHash?e.sourceHash!==r.sourceHash:!r.publishedAt||!!e.publishedAt&&e.publishedAt>r.publishedAt;return a?o?n?`updated`:`conflict`:`local_ahead`:o?`updated`:`up_to_date`}function UF(e,t){let n=/* @__PURE__ */ new Map,r=Te[e];for(let[i,a]of t){let t=i===r?H[e]:i;n.set(t,i.endsWith(`.html`)?Buffer.from(Xm(a.toString(`utf8`))):a)}let{pull:i}=oj[e];for(let e of i?.generated?.(n)??[])n.delete(e);return{files:n,notes:i?.publishedRecordings&&[...n.keys()].some(e=>RF.test(e))?[`recordings are the published versions`]:[]}}const WF=(e,t)=>oj[e].pull?.keeps?.(t)??!1,GF=/\/a\/([\w-]{1,64})(?:[/?#]|$)/,KF=/^[\w-]{1,64}$/,qF=e=>!e.includes(`\\`)&&e.split(`/`).every(e=>!!e&&e!==`.`&&e!==`..`),JF=e=>e===`comments.json`||e.startsWith(`marks/`)||e.split(`/`).some(e=>e.startsWith(`.`));function YF(e,t=``){let n=[];for(let r of d.default.readdirSync(p.default.join(e,t),{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...YF(e,i)):r.isFile()&&n.push(i)}return n}const XF=e=>{try{return d.default.readdirSync(e).some(e=>!e.startsWith(`.`))}catch{return!1}};function ZF(e,t){let n=t.split(`/`),r=e;for(let e of n.slice(0,-1)){r=p.default.join(r,e);try{if(d.default.lstatSync(r).isSymbolicLink())return!0}catch{return!1}}return!1}const QF=e=>(e??[]).flatMap(e=>typeof e==`string`?[e]:e&&typeof e==`object`&&typeof e.id==`string`?[e.id]:[]);function $F(e){let{cloudFetch:t,configFile:n,expectOk:r,root:i,refuse:a}=e,o=async e=>{let n=[],i=null;do{let a=new URLSearchParams({semantic:`1`,limit:`100`});e&&a.set(`project`,e),i&&a.set(`cursor`,i);let o=await(await r(await t(`GET`,`/api/artifacts?${a}`))).json();n.push(...o.artifacts),i=o.page?.nextCursor??null}while(i);return n},s=e=>{let t=GF.exec(e)?.[1]??(KF.test(e)?e:null);if(!t)throw a(400,`target must be <type>/<id>, a Cloud link or a Cloud id`);return t},c=async e=>{let n=new URLSearchParams({semantic:`1`,download:`1`});oj[e.type].pull?.threads&&n.set(`detail`,`1`);let i=await(await r(await t(`GET`,`/api/a/${encodeURIComponent(e.id)}?${n}`))).json();if(!i.contentBase||!Array.isArray(i.files))throw Error(`the server did not return a complete download manifest`);let a=i.files.find(e=>!qF(e));if(a)throw Error(`the manifest has an unsafe file path: ${a}`);let o=/* @__PURE__ */ new Map,s=[...i.files];return await Promise.all(Array.from({length:6},async()=>{for(let e=s.shift();e;e=s.shift()){let t=await fetch(`${i.contentBase}${e.split(`/`).map(encodeURIComponent).join(`/`)}`,{headers:Er});if(!t.ok)throw Error(`could not download ${e}: HTTP ${t.status}`);o.set(e,Buffer.from(await t.arrayBuffer()))}})),{files:o,threads:i.comments?.threads??[]}},l=(e,t,n,r)=>{for(let t of n.keys())if(ZF(e,t))throw Error(`${t} would be written through a symlink`);let a=d.default.mkdtempSync(p.default.join(i,`.state`,`pull-`));try{for(let[e,t]of n){let n=p.default.join(a,...e.split(`/`));d.default.mkdirSync(p.default.dirname(n),{recursive:!0}),d.default.writeFileSync(n,t)}d.default.mkdirSync(e,{recursive:!0});for(let i of YF(e))r.has(i)&&!JF(i)&&!WF(t,i)&&!n.has(i)&&d.default.rmSync(p.default.join(e,...i.split(`/`)));for(let t of n.keys()){if(t===`comments.json`&&d.default.existsSync(p.default.join(e,t)))continue;let n=p.default.join(e,...t.split(`/`));d.default.mkdirSync(p.default.dirname(n),{recursive:!0}),d.default.renameSync(p.default.join(a,...t.split(`/`)),n)}}finally{d.default.rmSync(a,{recursive:!0,force:!0})}},u=async(t,r,a)=>{let o=`${t.type}/${t.id}`,s=p.default.join(i,t.type,t.id);Yn(r.id)&&d.default.writeFileSync(p.default.join(s,`.artifact-id`),`${r.id}\n`);let c=await e.prepare(t).catch(()=>({})),l=QF(r.modules);Yr(n,o,{visibility:r.visibility,cloud:{id:r.id,url:r.url,publishedAt:r.updatedAt,visibility:r.visibility,identitySynced:!0,...r.onProfile===void 0?{}:{onProfile:r.onProfile},...c.fingerprint?{fingerprint:c.fingerprint}:{},...c.sourceHash??r.sourceHash?{sourceHash:c.sourceHash??r.sourceHash}:{},...l.length?{modulesSynced:l}:{}},...l.length?{modules:l}:{},...a===e.project?{}:{project:a}})},f=e=>Object.entries(Gr(n).config.artifacts).find(([t,n])=>n.cloud?.id===e.id&&t.startsWith(`${e.type}/`))?.[0].slice(e.type.length+1),m=async(t,r,a,o)=>{let s=o??f(t)??VF(t),d=`${t.type}/${s}`,m=p.default.join(i,t.type,s),h={key:d,cloudId:t.id,url:t.url,dir:m};if(!Jn(s))return{...h,outcome:`failed`,message:`${s} is not a usable local id`};let g={type:t.type,id:s};return e.serialized(d,async()=>{let i=XF(m),o=Gr(n).config.artifacts[d]?.cloud,s=i?await e.prepare(g).catch(()=>({})):{},f=HF({cloud:t,force:r.force,local:{exists:i,record:o,...s}});if(r.dryRun||![`created`,`updated`,`bound`].includes(f))return{...h,outcome:f};try{let e=[];if(f!==`bound`){let{files:n,threads:r}=await c(t),i=UF(t.type,n);e=i.notes;let a=oj[t.type].pull;a?.threads&&r.length>0&&!i.files.has(`comments.json`)&&i.files.set(`comments.json`,Buffer.from(`${JSON.stringify({version:1,threads:r},null,2)}\n`)),l(m,t.type,a?.restore?.(m,i.files)??i.files,new Set(s.localFiles))}return await u(g,t,a),{...h,outcome:f,...e.length?{notes:e}:{}}}catch(e){return{...h,outcome:`failed`,message:e.message}}})};return async t=>{if(t.as!==void 0&&!t.target)throw a(400,`--as needs a single target`);if(t.as!==void 0&&!Jn(t.as))throw a(400,`--as must be lowercase letters, digits and hyphens`);let r=t.project||e.project,i=[],c=t.target?G(t.target):null;if(c){let e=Gr(n).config.artifacts[t.target]?.cloud?.id,s=e?(await o(void 0)).find(t=>t.id===e):(await o(r)).find(e=>e.type===c.type&&VF(e)===c.id);if(!s)throw a(404,`no Cloud copy of ${t.target} in ${r}`);i.push({item:s,name:t.as??c.id})}else if(t.target){let e=s(t.target),n=(await o(void 0)).find(t=>t.id===e);if(!n)throw a(404,`no Cloud artifact ${e} in your account`);i.push({item:n,name:t.as})}else i.push(...(await o(r)).map(e=>({item:e})));let l=[];for(let{item:n,name:r}of i.filter(e=>e.item.version!==null))l.push(await m(n,t,t.project||(t.target?n.project:null)||e.project,r));return{project:r,results:l}}}function eI(e){let{configFile:t,project:n}=e,r=FF(e),{activeCredentials:i,autoPublishState:a,cloudFetch:o}=r,s=LF(e,r),{artifactEntry:c,changedDuringPublish:l,expectOk:u,projectOf:d,serialized:f,setPublication:p,snapshot:m}=s,h=IP({cloudFetch:o,configFile:t,project:n}),g=UP(e,r),_=QP(e,r,s,h,g),{autoPublish:v,publication:y,publish:b,reserve:x}=_,S=hP({cloudFetch:o,configFile:t,projectOf:d,serialized:f,sourceHashOf:async e=>{let t=G(e),n=c(e).cloud;if(!t||!n?.fingerprint||!n.publishedAt)return;let r=await o(`GET`,`/api/a/${encodeURIComponent(n.id)}?semantic=1`);if(!r.ok||(await r.json()).updatedAt!==n.publishedAt)return;let i=n.fingerprint,a=await g(t);return a.ready&&a.fingerprint===i?a.sourceHash:void 0}}),C=e.root?$F({cloudFetch:o,configFile:t,expectOk:u,project:n,root:e.root,serialized:f,refuse:(e,t)=>new X(e,t),prepare:async e=>{let t=await g(e);return t.ready?{fingerprint:t.fingerprint,sourceHash:t.sourceHash,localFiles:t.localFiles}:{}}}):null,w=IF(e,r,s,b),T=fP(e,r,s,g,b,w.setVisibility),{cascadeOf:E,publishReferrers:D,publishRefs:O,referrersOf:k}=T,A=rF({cascade:T,options:e,publisher:_,pull:C,session:r,sharing:w,store:s});return{handleCallback:r.handleCallback,handleCallbackAutoPublish:r.handleCallbackAutoPublish,match:A.match,autoPublish:v,async syncModules(){h.published()&&(await h.syncVocabulary().catch(()=>void 0),await h.syncTags().catch(()=>void 0),await S().catch(()=>void 0))},reserve:e=>f(`${e.type}/${e.id}`,()=>x(e)),publication:y,changed(e){l.add(e),Nr(m(e).phase)||p(e,{phase:`waiting`})},publishNow(e){let n=G(e);if(!n)throw new X(404,`artifact not found`);return Nr(m(e).phase)||(p(e,{phase:`preparing`}),f(e,async()=>{(await b(n,void 0,{recreate:!1})).status===200&&Yr(t,e,{autoPublish:null})}).catch(()=>{})),m(e)},async cascade(e,t){let n=G(e);if(!n)throw new X(404,`artifact not found`);let r=t??Rr(c(e)).visibility;return{visibility:r,items:await E(n,r),...await k(n)}},publishRefsNow(e,t,n,r){let i=G(e);if(!i)throw new X(404,`artifact not found`);return O(i,t,n,r)},publishReferrersNow(e,t,n){let r=G(e);if(!r)throw new X(404,`artifact not found`);return D(r,t,n)},autoPublishEnabled:()=>a().enabled,token:()=>i()?.token??null,async inbox(e){let t=c(e).cloud?.id;if(!t||!i())return[];let n=await o(`GET`,`/api/artifacts/${encodeURIComponent(t)}/inbox`);if(!n.ok)return[];let r=(await n.json()).entries;return Array.isArray(r)?r:[]},async delivered(e,t){let n=c(e).cloud?.id;n&&t.length!==0&&await o(`POST`,`/api/artifacts/${encodeURIComponent(n)}/inbox/delivered`,{ids:t})},handle:A.handle}}function tI({broadcast:e,clients:t,inspect:n,options:r,port:i,root:a,stateDir:o}){let s=r.cloud&&r.configFile?eI({...r.cloud,configFile:r.configFile,project:hM(p.default.resolve(a,`../..`)),root:a,address:e=>xi(a,e.type,e.id).split(`/`).pop(),references:e=>GN(a,`${e.type}/${e.id}`),referrers:e=>KN(a,`${e.type}/${e.id}`),port:i,inspect:n,onPublication:(t,n)=>{e({type:`cloud-publication`,artifact:t,publication:n})}}):null,c=s?Tr({stateFile:p.default.join(o,`auto-publish.json`),enabled:s.autoPublishEnabled,token:s.token,signatureOf:e=>{let t=G(e),n=t&&W(a,t.type,t.id);return t&&n?nr(n,t.type):null},publish:async e=>{let n=await s.autoPublish(e);if(n.kind===`published`){let n=lc(JSON.stringify({type:`cloud-published`,artifact:e}));for(let e of t)e.write(n)}return n}}):null,l=()=>{let e=/* @__PURE__ */ new Map;if(!r.configFile)return e;for(let[t,n]of Object.entries(Gr(r.configFile).config.artifacts)){let r=G(t);n.cloud&&r&&W(a,r.type,r.id)&&e.set(n.cloud.id,t)}return e};return{autoPublisher:c,cloud:s,embedTarget:(e,t)=>{if(Xn(t)&&Si(a,e,t))return{type:e,id:t};let n=G(l().get(t)??``);return n?.type===e?n:null},servedArtifacts:l}}function nI(){let e=/* @__PURE__ */ new Set,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map;return{record(e){let t=`${e.host}:${e.session}`,r=n.get(t);if(r&&e.at<r.lastAt)return;if(e.event===`SessionEnd`){n.delete(t);return}let i=r?e.event===`UserPromptSubmit`?r.turn+1:r.turn:1;n.set(t,{lastAt:e.at,turn:i})},register(t){return e.add(t),()=>{e.delete(t)}},lookup(t,r){let i=null;for(let n of e){let e=n.lookup(t,r);e&&(!i||e.lastAt>i.lastAt)&&(i=e)}let a=n.get(`${t}:${r}`);return i&&a?{...i,turn:a.turn}:i},subscribe(e){return t.add(e),()=>{t.delete(e)}},changed(){for(let e of t)e()}}}const rI=/* @__PURE__ */ new Set([...we,`preview`]),iI=/^[a-z0-9][a-z0-9-]*$/,aI=/* @__PURE__ */ new Set([`AskUserQuestion`,`ExitPlanMode`,`ask_question`]),oI={UserPromptSubmit:{state:`thinking`,endTurn:!0},PreToolUse:{state:`running`},PostToolUse:{state:`thinking`},PostToolUseFailure:{state:`thinking`},PermissionRequest:{state:`needs-approval`},PermissionDenied:{state:`thinking`},Stop:{state:`your-turn`,endTurn:!0},Interrupt:{state:`your-turn`,endTurn:!0},SessionEnd:`end`},sI=/\.\d+\.tmp$/,cI=/* @__PURE__ */ new Set([`doc.xml`,`comments.json`,`scene.excalidraw`,`pages.json`]),lI=/^pages\/[a-z0-9-]+\.excalidraw$/,uI=e=>e.filter(e=>{let t=e.replace(sI,``);return!cI.has(t)&&!lI.test(t)});function dI(e){try{return d.default.realpathSync(e)}catch{return p.default.resolve(e)}}function fI(e){let t=p.default.resolve(e),n=[];for(;t!==p.default.dirname(t);)try{return p.default.join(d.default.realpathSync(t),...n)}catch{n.unshift(p.default.basename(t)),t=p.default.dirname(t)}return p.default.resolve(e)}function pI(e){let t=[.../* @__PURE__ */ new Set([p.default.resolve(e),dI(e)])],n=/* @__PURE__ */ new Map,r=e=>{if(!p.default.isAbsolute(e))return null;let n=[.../* @__PURE__ */ new Set([p.default.resolve(e),fI(e)])];for(let e of t)for(let t of n){let n=p.default.relative(e,t).split(p.default.sep);if(n.length<3||n[0]===`..`)continue;let[r,i]=n;if(rI.has(r)&&iI.test(i))return`${r}/${i}`}return null},i=(e,t)=>[.../* @__PURE__ */ new Set([...e,...t])];return{apply(e){let t=oI[e.event];if(!t)return!1;let a=`${e.host}:${e.session}`,o=n.get(a);if(o&&e.at<o.lastAt)return!1;if(t===`end`)return n.delete(a);if(e.event===`PreToolUse`&&o?.session.state===`needs-approval`)return o.lastAt=e.at,!1;let s=(e.paths??[]).flatMap(e=>r(e)??[]),c=o?.session,l=t.endTurn?[]:c?.turnArtifacts??[],u=e.event===`PreToolUse`&&aI.has(e.tool??``),d={id:e.session,host:e.host,agent:Oj[e.host],state:u?`needs-approval`:t.state,since:c?.state===t.state&&!u?c.since:e.at,artifacts:i(c?.artifacts??[],s),turnArtifacts:i(l,s)},f=e.event===`UserPromptSubmit`?(o?.turn??0)+1:o?.turn??1,p=d.state===`running`&&(e.paths?.length??0)===0;return n.set(a,{session:d,lastAt:e.at,turn:f,opaqueRun:p}),!0},touched(e){let t=[...n.values()].filter(e=>e.session.state===`running`);if(t.length===0)return!1;if(t.some(t=>t.session.artifacts.includes(e))){let n=!1;for(let r of t)r.session.artifacts.includes(e)&&!r.session.turnArtifacts.includes(e)&&(r.session={...r.session,turnArtifacts:i(r.session.turnArtifacts,[e])},n=!0);return n}for(let t of n.values()){let{state:n,turnArtifacts:r}=t.session;if((n===`thinking`||n===`running`)&&r.includes(e))return!1}let r=t.filter(e=>e.opaqueRun);if(r.length!==1)return!1;let a=r[0];return a.session={...a.session,artifacts:i(a.session.artifacts,[e]),turnArtifacts:i(a.session.turnArtifacts,[e])},!0},expire(e){let t=!1;for(let[r,i]of n){let a=i.session.state===`your-turn`||i.session.state===`needs-approval`?288e5:18e5;e-i.lastAt>=a&&(t=n.delete(r)||t)}return t},lookup(e,t){let r=n.get(`${e}:${t}`);return r?{agent:r.session.agent,state:r.session.state,turn:r.turn,lastAt:r.lastAt}:null},sessions(){return[...n.values()].map(e=>e.session)},turnArtifacts(e,t){return n.get(`${e}:${t}`)?.session.turnArtifacts??[]}}}const mI={id:200,board:100,file:500,tag:80,path:4e3,name:100,text:200,html:2e3,from:2e3,value:300},hI={elements:200,id:200,type:40,text:200},gI={quote:2e3,heading:200,blockId:100,blockIds:200},_I=e=>!!e&&typeof e==`object`&&!Array.isArray(e),vI=(e,t)=>typeof e==`string`&&e.length<=t,yI=(e,t)=>Array.isArray(e)&&e.length<=t,bI=e=>Am.includes(e);function xI(e){return!_I(e)||!vI(e.id,mI.id)||!vI(e.board,mI.board)||!vI(e.file,mI.file)||!vI(e.tag,mI.tag)||!vI(e.path,mI.path)||!vI(e.name,mI.name)?null:{id:e.id,board:e.board,file:e.file,tag:e.tag,path:e.path,name:e.name}}function SI(e){return!_I(e)||!bI(e.property)||!vI(e.from,mI.from)||!vI(e.value,mI.value)?null:{property:e.property,from:e.from,value:e.value}}function CI(e,t){let n=[];for(let r of e){let e=t(r);if(!e)return null;n.push(e)}return n}function wI(e){if(!_I(e)||e.type!==`selection`||!vI(e.artifact,200)||!vI(e.tab,64)||!e.tab||typeof e.human!=`boolean`)return null;let t=e.artifact.startsWith(`artboard/`)?e.artifact.slice(9):``;if(!Jn(t)||!Number.isSafeInteger(e.more)||e.more<0||!yI(e.selected,20)||!yI(e.tweaks,25e3)||!yI(e.nodes,25e3))return null;let n=CI(e.selected,e=>{let t=xI(e);if(!t||!_I(e)||!vI(e.text,mI.text)||!vI(e.html,mI.html)||!yI(e.tweaks,Am.length))return null;let n=CI(e.tweaks,SI);return n&&{...t,text:e.text,html:e.html,tweaks:n}}),r=CI(e.tweaks,e=>{let t=xI(e),n=SI(e);return t&&n&&{...t,...n}}),i=CI(e.nodes,xI),a=e.removed===void 0?[]:yI(e.removed,25e3)?CI(e.removed,xI):null;if(!n||!r||!i||!a)return null;let o=e=>e===void 0?[]:yI(e,2e3)&&e.every(e=>vI(e,mI.board)&&e)?e:null,s=o(e.boards),c=o(e.notes);return!s||!c?null:{id:t,tab:e.tab,human:e.human,state:{selected:n,more:e.more,tweaks:r,...a.length?{removed:a}:{},nodes:i,...s.length?{boards:s}:{},...c.length?{notes:c}:{}}}}function TI(e){if(!_I(e)||e.type!==`selection`||!vI(e.artifact,200)||!vI(e.tab,64)||!e.tab||typeof e.human!=`boolean`)return null;let t=e.artifact.startsWith(`document/`)?e.artifact.slice(9):``;return!Jn(t)||typeof e.quote!=`string`||typeof e.heading!=`string`||!yI(e.blockIds,gI.blockIds)||!e.blockIds.every(e=>vI(e,gI.blockId))?null:{id:t,tab:e.tab,human:e.human,state:{quote:e.quote.slice(0,gI.quote),blockIds:e.blockIds,heading:e.heading.slice(0,gI.heading)}}}function EI(e){if(!_I(e)||e.type!==`selection`||!vI(e.artifact,200)||!vI(e.tab,64)||!e.tab||typeof e.human!=`boolean`||!yI(e.selected,hI.elements))return null;let t=e.artifact.slice(11);if(!e.artifact.startsWith(`whiteboard/`)||!Jn(t))return null;let n=(e,t)=>typeof e==`string`?e.slice(0,t):null,r=[];for(let t of e.selected){if(!_I(t)||!vI(t.id,hI.id)||!t.id||!vI(t.type,hI.type))return null;r.push({id:t.id,type:t.type,text:n(t.text,hI.text),frameId:n(t.frameId,hI.id),author:t.author===`human`||t.author===`agent`?t.author:null})}let i=Ge(e.page)?{page:e.page}:{};return{id:t,tab:e.tab,human:e.human,state:{...i,selected:r}}}function DI(e){let t=_I(e)&&typeof e.artifact==`string`?e.artifact:``;if(t.startsWith(`whiteboard/`)){let t=EI(e);return t&&{...t,kind:`whiteboard`,state:t.state.selected.length?t.state:null}}if(t.startsWith(`document/`)){let t=TI(e);return t&&{...t,kind:`document`,state:t.state.quote?t.state:null}}let n=wI(e);return n&&{...n,kind:`artboard`}}function OI(e,t){let n=/* @__PURE__ */ new Map,r=0,i=(t,n)=>p.default.join(e,t,n,`selection.json`),a=(e,t)=>{let r;for(let i of n.values())i.kind===e&&i.id===t&&(!r||i.humanAt>r.humanAt||i.humanAt===r.humanAt&&i.seenAt>r.seenAt)&&(r=i);r?.state?U(i(e,t),{artifact:`${e}/${t}`,updatedAt:(/* @__PURE__ */ new Date()).toISOString(),...r.state}):d.default.rmSync(i(e,t),{force:!0})};return{accept(e,i){let o=DI(i),s=n.get(e);if(!o||!t(o.kind,o.id)){s&&(n.delete(e),a(s.kind,s.id));return}let c=s?.kind===o.kind&&s.id===o.id,l=o.human?++r:c?s.humanAt:0;n.set(e,{kind:o.kind,id:o.id,state:o.state,humanAt:l,seenAt:++r}),s&&!c&&a(s.kind,s.id),a(o.kind,o.id)},drop(e){let t=n.get(e);t&&(n.delete(e),a(t.kind,t.id))},clearAll(){n.clear();for(let t of[`artboard`,`document`,`whiteboard`]){let n;try{n=d.default.readdirSync(p.default.join(e,t))}catch{continue}for(let e of n)d.default.rmSync(i(t,e),{force:!0})}}}}function kI(e,t){let n=new Set(Object.values(t.canvas?.boards??{}).flatMap(e=>Oe(e)?[]:[e.file])),r=u.default.createHash(`sha256`),i=t=>{let a;try{a=d.default.readdirSync(t,{withFileTypes:!0})}catch{return}for(let o of a.sort((e,t)=>e.name<t.name?-1:1)){if(o.name.startsWith(`.`))continue;let a=p.default.join(t,o.name),s=p.default.relative(e,a).split(p.default.sep).join(`/`);if(o.isDirectory())s!==`marks`&&i(a);else if(s!==`canvas.json`&&s!==`comments.json`&&!n.has(s)){let e;try{e=d.default.statSync(a)}catch{continue}r.update(`${s}\0${e.mtimeMs}\0${e.size}\0`)}}};return i(e),r.digest(`hex`)}function AI(){let e=/* @__PURE__ */ new Map,t=t=>{let n=e.get(t);return n||(n=/* @__PURE__ */ new Map,e.set(t,n)),n};return{accept(e,n,r,i){let{board:a,version:o,type:s,message:c}=i;if(typeof a!=`string`||!r.runtimeVersion||o!==r.runtimeVersion)return!1;let l=r.canvas?.boards[a];if(!l||Oe(l)||!r.versions[l.file]||s!==`loaded`&&s!==`runtime-error`||s===`runtime-error`&&(typeof c!=`string`||!c.length||c.length>2048))return!1;let u=t(e),d=`${r.versions[l.file]}:${kI(n,r)}`,f=u.get(a),p=f?.content===d?f:{content:d,ran:!1,errors:[]};return s===`loaded`?p.ran=!0:!p.errors.includes(c)&&p.errors.length<20&&p.errors.push(c),u.set(a,p),!0},state(e,n,r){let i=t(e),a=kI(n,r),o=[],s=/* @__PURE__ */ new Map,c=[];for(let[e,t]of Object.entries(r.canvas?.boards??{})){if(Oe(t))continue;let n=i.get(e),l=n?.content===`${r.versions[t.file]}:${a}`?n:void 0;l?.ran||(o.push(`browser_not_run:${e}`),s.set(t.page,[...s.get(t.page)??[],e]));for(let t of l?.errors??[])c.push({code:`W_BOARD_RUNTIME`,severity:`warning`,location:e,message:t})}return{ran:o.length===0,browserPending:o,diagnostics:c,...s.size?{unvisited:[...s].map(([e,t])=>({page:e,boards:t}))}:{}}}}}const jI=(e,t)=>(n,r)=>{if(r.op!==`create`||!r.anchor.verdict)return!1;let i=W(t,`artboard`,n);if(!i)return!1;let a=e(i,{type:`artboard`,id:n});return(a.canvas?.groups?.[r.anchor.group]?.boards??[]).some(e=>a.pending.includes(e))};async function MI(e,t){let n=W(e,`document`,t),r=n?ol(n):null;if(!r)return{};let i=await cl.ensure([r.xml]).then(()=>cl.tree(r.xml)).catch(()=>void 0);return i&&`state`in i?{prompt:{state:i.state,at:r.at,harness:r.harness}}:{}}async function NI(e,t,n,r){return{snapshot:Buffer.from(await r.snapshot()).toString(`base64`),lineage:r.lineage(),outcome:r.outcome(),streaming:r.streaming(),agentActiveAt:r.agentActiveAt(),now:Date.now(),comments:e.comments(n),listening:e.listening(n),...await MI(t,n)}}const PI=(e,t)=>p.default.join(e,`document`,t,`change-cursors.json`),FI=e=>typeof e==`object`&&!!e&&typeof e.peer==`string`&&Number.isInteger(e.counter);function II(e){try{let t=JSON.parse(d.default.readFileSync(e,`utf8`));return typeof t!=`object`||!t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>Array.isArray(e[1])&&e[1].every(FI)))}catch{return{}}}function LI(e){return{get:(t,n)=>II(PI(e,t))[n]??null,set:(t,n,r)=>{let i=PI(e,t);U(i,{...II(i),[n]:r})}}}const RI=(e,t)=>e.find(e=>e.id===t)?.blockId??`*`;function zI(e,t,n){if(n.op!==`create`){let e=t.find(e=>e.id===n.threadId);if(e&&Ea(e))throw Error(`an answer changes only through its question and the submit bar`);return n}if(!Ea({anchor:n}))return n;let r=n.text;if(n.note)throw Error(`only the agent writes a note on a question`);if(n.submit===!0)return{op:`create`,...Pa(e,t),text:r};if(n.submit===!1)return{op:`create`,...Fa(t),text:r};let i={ask:n.ask,choice:n.choice??null,answer:n.answer??null};return Na(e,t,i),{op:`create`,blockId:RI(e,i.ask),quote:``,...i,text:r}}function BI(e,t,n){let r,i;if(n.op===`submit`)r=n.submit?Pa(e,t):Fa(t),i=n.submit?`Submitted the answers`:`Withdrew the submit`;else if(n.op===`answer`){let t={ask:n.ask,choice:n.choice,answer:n.answer};Ma(e,t),r={blockId:RI(e,n.ask),quote:``,...t},i=`Answered ${n.ask}`}else{if(!e.some(e=>e.id===n.ask))throw Error(`no question ${n.ask} in this document`);r={blockId:RI(e,n.ask),quote:``,ask:n.ask,note:!0},i=n.text}return{op:`add`,...r,text:i}}function VI(e,t){let n=Aa(t);return{asks:ja(e,t).map(({options:e,...t})=>t),submission:n?{id:n.id,state:n.withdrawn?`withdrawn`:`submitted`,at:n.at}:null}}function HI(e,t,n,r){let i=p.default.join(e,`document`,t,`asks.json`);if(!n.length&&!d.default.existsSync(i))return;let a=Aa(r);U(i,{latest:a?{id:a.id,at:a.at,withdrawn:a.withdrawn}:null})}const UI={empty:Ba,saved:Ga,merge:Za,human:to,agent:lo};function WI(e,t,n={}){return vs(e,UI,t,n)}const GI=e=>({...e,waitingOn:ro(e),messages:e.messages.map(({avatar:e,...t})=>t)});function KI(e){return e.kind===`rejected`?[`agent edit rejected: ${e.message} (doc.xml is left as written; fix it)`]:e.kind===`failed`?[`agent edit failed: ${e.message}`]:[]}function qI(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=e.openSession??(e=>cl.open(e)),a=e.timing?.sessionIdleMs??12e4,o=i=>{let a=t.get(i);return t.delete(i),n.delete(i)&&e.onSessionChange?.(i,!1),C.delete(i),S.delete(i),r.delete(i),a},s=async e=>{await(await o(e))?.close()},c=Dy(e.root),l=/* @__PURE__ */ new Map,u=(t,n)=>{let r=JSON.stringify(n);if(l.get(t)===r)return;let i=JSON.parse(l.get(t)??`[]`);l.set(t,r);let a=[...i,...n],o=[...new Set(a.map(e=>`${lh(e)}/${uh(e)}`))];e.onRefsChange?.(t,o.map(e=>{let[t,n]=e.split(`/`);return{type:t,id:n}}))},f=e=>{let t=n.get(e);return t&&!t.streaming()?Py(t.summary().refs,c):[]},m=t=>p.default.join(e.root,`document`,t,`doc.xml`),h=e.readDocument??cl.read,g=/* @__PURE__ */ new Map,_=/* @__PURE__ */ new Map,v=n=>{let r;try{r=d.default.statSync(m(n))}catch{return g.delete(n),null}let i=`${r.mtimeMs}:${r.size}`,a=g.get(n);return a?.stamp===i||_.get(n)===i||(_.set(n,i),h(m(n),e.root).then(r=>{_.get(n)===i&&(_.delete(n),g.set(n,{stamp:i,read:r}),t.has(n)||(u(n,`summary`in r?r.summary.refs:[]),e.onWarningsChange(n)))}).catch(t=>{_.get(n)===i&&_.delete(n),e.log?.(`document ${n} could not be read: ${t.message}`)})),a??null},y=e=>{let t=n.get(e);if(t)return t.summary().refs;let r=v(e)?.read;return r&&`summary`in r?r.summary.refs:[]},b=e=>{let t=v(e)?.read;return t?`error`in t?[`agent edit rejected: ${t.error} (doc.xml is left as written; fix it)`]:[...t.summary.warnings,...Py(t.summary.refs,c)]:[]},x=()=>{try{return d.default.readdirSync(p.default.join(e.root,`document`)).filter(e=>d.default.existsSync(m(e)))}catch{return[]}},S=/* @__PURE__ */ new Map,C=/* @__PURE__ */ new Map,w=t=>p.default.join(e.root,`document`,t,`doc.xml`),T=/* @__PURE__ */ new Map,E=$o(e.stateDir),D=LI(e.stateDir),O=t=>{let n=T.get(t);return n||(n=WI(p.default.join(e.root,`document`,t,`comments.json`),e.names,{artifact:`document/${t}`,savesDir:p.default.join(e.stateDir,`document`,t,`comment-saves`)}),T.set(t,n)),n},k=t=>Es(e.stateDir,`document/${t}`),A=/* @__PURE__ */ new Map,j=(t,n=k(t))=>{A.set(t,n),e.broadcast({type:`doc-comments`,artifact:`document/${t}`,comments:O(t).current(),listening:n})},ee=async e=>{let t=await F(e);return t?t.summary().asks:[]},M=async t=>HI(e.stateDir,t,await ee(t),O(t).current().threads),N=t=>{let n=O(t),r=JSON.stringify(n.warnings());n.sync()&&(j(t),M(t),JSON.stringify(n.warnings())!==r&&e.onWarningsChange(t))},P=async t=>{if(!d.default.existsSync(w(t)))return null;let a=await i({file:w(t),snapshotFile:p.default.join(e.stateDir,`document`,t,`doc.loro`),...e.timing,log:e.log,onLost:()=>{o(t),e.onSessionLost?.(t)},root:e.root});n.set(t,a),e.onSessionChange?.(t,!0),u(t,a.summary().refs);let s=`document/${t}`,c=n=>{JSON.stringify(n)!==JSON.stringify(S.get(t)??[])&&(S.set(t,n),e.onWarningsChange(t))},l=()=>{if(a.streaming())return[];let e=a.outcome();return e.kind===`rejected`?KI(e):[...KI(e),...a.summary().warnings,...f(t)]};return c(l()),C.set(t,()=>c(l())),a.subscribe(n=>{r.set(t,Date.now()),n.type===`update`?e.broadcast({type:`doc-update`,artifact:s,bytes:Buffer.from(n.bytes).toString(`base64`)}):n.type===`saved`?(c(l()),u(t,a.summary().refs)):(e.broadcast({type:`doc-status`,artifact:s,streaming:n.streaming,outcome:n.outcome,agentActiveAt:n.agentActiveAt,now:Date.now()}),c(l()),n.streaming||u(t,a.summary().refs))}),a.refreshRefs(),a},F=n=>{r.set(n,Date.now());let i=t.get(n);return i||(i=P(n).catch(t=>(e.log?.(`document ${n} could not open: ${t.message}`),null)),t.set(n,i),i.then(e=>{e||t.delete(n)})),i};return{open:F,artboardChanged:r=>{for(let[e,t]of n)t.summary().refs.some(e=>e.artboard===r)&&(t.refreshRefs(),C.get(e)?.());for(let n of x())!t.has(n)&&y(n).some(e=>e.artboard===r)&&e.onWarningsChange(n)},fileChanged:n=>{t.has(n)?F(n).then(e=>{e&&d.default.readFile(w(n),`utf8`,(t,n)=>{t||e.onFileText(n)})}):(u(n,y(n)),e.onWarningsChange(n))},changes:async(e,t,n)=>{let r=await F(e);if(!r)return null;let{diff:i,empty:a,to:o}=await r.changesSince(n?null:D.get(e,t));return n||D.set(e,t,o),{diff:i,empty:a}},comments:e=>O(e).current(),commentsChanged:N,mergeRemote:(e,t)=>{let n=[];return O(e).update(e=>{let r=ho(e,t,Ha.read);return n=r.applied,r.file}),j(e),n},applyCommentOp:async(t,n)=>{let r=await ee(t),i=O(t);i.sync();let a=i.apply(zI(r,i.current().threads,n));return j(t),HI(e.stateDir,t,r,a.threads),a},agentAsk:async(t,n,r)=>{let i=await ee(t),a=O(t);a.sync();let{file:o,threadId:s}=a.applyAgent(BI(i,a.current().threads,n),r);return j(t),HI(e.stateDir,t,i,o.threads),{threadId:s}},asks:async e=>(N(e),VI(await ee(e),O(e).current().threads)),listening:k,refreshListening:(t=Ts(e.stateDir))=>{for(let e of T.keys()){let n=t(`document/${e}`);n!==A.get(e)&&j(e,n)}},applyAgentCommentOp:(e,t,n)=>{let{threadId:r,messageId:i}=O(e).applyAgent(t,n);return j(e),{threadId:r,...i?{messageId:i}:{}}},listComments:(e,t,n)=>{N(e);let r=O(e).current(),i=e=>!Ea(e);if(n)return r.threads.filter(e=>i(e)&&!e.messages.every(e=>e.deleted)).map(GI);let{threads:a,newest:o}=co(r,E.get(e,t));return o&&E.set(e,t,o),a.filter(i).map(GI)},ids:x,openIds:()=>[...n.keys()],opening:async()=>{await Promise.all(t.values())},sweepIdle:async t=>{let i=[...n].filter(([n,i])=>!e.viewed?.(n)&&!i.streaming()&&t-(r.get(n)??0)>=a);await Promise.all(i.map(([e])=>s(e)))},flushAll:async()=>{let e=await Promise.all(t.values());await Promise.all(e.map(e=>e?.flush()))},refs:y,warnings:e=>[...t.has(e)?S.get(e)??[]:b(e),...O(e).warnings()],close:async()=>{let r=await Promise.all(t.values());await Promise.all(r.map(e=>e?.close())),t.clear();for(let t of n.keys())e.onSessionChange?.(t,!1);n.clear(),C.clear()}}}const JI=/<(\/?)([a-z][\w-]*)\b[^>]*?(\/?)>/gi,YI=[[`<![CDATA[`,`]]>`],[`<!--`,`-->`]];function XI(e){let t=``,n=0;for(;n<e.length;){let r=YI.map(([t,r])=>({close:r,index:e.indexOf(t,n)})).filter(({index:e})=>e!==-1).sort((e,t)=>e.index-t.index)[0];if(!r)return t+e.slice(n);t+=e.slice(n,r.index);let i=e.indexOf(r.close,r.index);if(i===-1)return t;n=i+r.close.length}return t}const ZI=/^assets\/[\w-][\w.-]*\.html$/,QI=/\surl\s*=\s*(?:"([^"]*)"|'([^']*)')/i;function $I(e){let t=/* @__PURE__ */ new Set;for(let n of XI(e).matchAll(JI)){if(n[1]||n[2].toLowerCase()!==`dynamic`)continue;let e=QI.exec(n[0]),r=e?.[1]??e?.[2]??``;ZI.test(r)&&t.add(r)}return[...t]}const eL=e=>{try{return d.default.statSync(e).mtimeMs}catch{return-1}},tL={accepts:e=>ZI.test(e),missingWarnings:!0,urls:e=>{try{return $I(d.default.readFileSync(p.default.join(e,`doc.xml`),`utf8`))}catch{return null}}};function nL(e,t=tL){let n=/* @__PURE__ */ new Map,r=e=>{let t=n.get(e);return t||(t=/* @__PURE__ */ new Map,n.set(e,t)),t},i=(e,t,n)=>{let i=r(e),a=eL(p.default.join(t,n)),o=i.get(n);return o&&o.mtime===a||(o={mtime:a,errors:[],ran:!1},i.set(n,o)),o};return{accepts:e=>typeof e==`string`&&t.accepts(e),report(t,n,r,a){let o=i(t,n,r);return o.errors.includes(a)||o.errors.length>=e.maxErrors?!1:(o.errors.push(a),!0)},loaded(e,t,n){let r=i(e,t,n);return!r.ran&&(r.ran=!0,!0)},state(e,n){let i=t.urls(n);if(!i)return{warnings:[],dynamic:{}};let a=r(e);for(let[e,t]of a)i.includes(e)&&t.mtime===eL(p.default.join(n,e))||a.delete(e);let o=[],s={};for(let e of i){t.missingWarnings&&!d.default.existsSync(p.default.join(n,e))&&o.push(`${e} not found`);let r=a.get(e);for(let t of r?.errors??[])o.push(`runtime: ${e}: ${t}`);s[e]={ran:r?.ran??!1}}return{warnings:o,dynamic:s}}}}const rL=/* @__PURE__ */ new Set([`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`te`,`trailers`,`transfer-encoding`,`upgrade`]),iL=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`);function aL(e,t){let n=`<script src="${iL(t.bridgeScriptUrl)}" data-ryugi-preview="${iL(t.id)}" data-ryugi-viewer="${iL(t.viewerOrigin)}"><\/script>`,r=Ym(e);return`${e.slice(0,r)}${n}${e.slice(r)}`}function oL(e,t,n){let r=e.split(`;`).map(e=>e.trim()).filter(Boolean),i=!1,a=r.map(e=>{let r=e.toLowerCase();return r.startsWith(`frame-ancestors `)?(i=!0,`frame-ancestors 'self' ${t}`):r.startsWith(`script-src `)||r.startsWith(`default-src `)?`${e} ${n}`:e});return i||a.push(`frame-ancestors 'self' ${t}`),a.join(`; `)}function sL(e,t){let n=iL(e),r=JSON.stringify(t);return`<!doctype html><html lang="zh"><head><meta charset="utf-8"><title>Waiting for ${n}</title><style>
653
- html,body{margin:0;height:100%;font:-apple-system,BlinkMacSystemFont,"Inter",sans-serif;background:#fafafa;color:#18181b;display:grid;place-items:center}
654
- .card{width:420px;background:#fff;border:1px solid #e7e7e9;border-radius:12px;padding:24px;box-shadow:0 6px 20px rgba(0,0,0,.04)}
655
- h1{margin:0 0 8px;font-size:16px}
656
- p{margin:0 0 14px;font-size:13px;color:#52525b;line-height:1.5}
657
- code{font:12px ui-monospace,SFMono-Regular,Menlo,monospace;background:#f4f4f5;padding:1px 5px;border-radius:4px}
658
- .hint{font-size:12px;color:#8b8b93}
659
- </style></head><body><div class="card">
660
- <h1>等待本机服务启动</h1>
661
- <p>暂时连不上 <code>${n}</code>(<code>ECONNREFUSED</code>)。请确认本地 dev server 正在运行,启动后会自动恢复。</p>
662
- <div class="hint">每 2 秒自动探测重连…</div>
663
- </div><script>
664
- try { parent.postMessage({ type: 'ryugi-preview:offline', target: ${JSON.stringify(e)} }, ${r}); } catch {}
665
- setTimeout(() => location.reload(), 2000);
666
- <\/script></body></html>`}function cL(e,t,n){let r={};for(let[i,a]of Object.entries(e.headers)){if(a===void 0)continue;let e=i.toLowerCase();rL.has(e)||(e===`host`?r.host=t.target.host:e===`origin`&&typeof a==`string`?r.origin=a===t.origin?t.target.origin:a:e===`referer`&&typeof a==`string`&&a.startsWith(t.origin)?r.referer=`${t.target.origin}${a.slice(t.origin.length)}`:e===`accept-encoding`&&n?r[`accept-encoding`]=`identity`:r[i]=a)}return r.host=t.target.host,n&&(r[`accept-encoding`]=`identity`),r}function lL(e,t,n){let r=(()=>{try{return new URL(t.bridgeScriptUrl).origin}catch{return t.viewerOrigin}})(),i={};for(let[a,o]of Object.entries(e)){if(o===void 0)continue;let e=a.toLowerCase();rL.has(e)||e!==`x-frame-options`&&(!n||e!==`content-length`&&e!==`content-encoding`)&&(e===`location`&&typeof o==`string`?i.location=o.startsWith(t.target.origin)?`${t.origin}${o.slice(t.target.origin.length)}`:o:e===`content-security-policy`&&typeof o==`string`?i[`content-security-policy`]=oL(o,t.viewerOrigin,r):i[a]=o)}return i[`content-security-policy`]||=`frame-ancestors 'self' ${t.viewerOrigin}`,i}function uL(e,t,n){e.lastActivity=Date.now();let r=String(t.headers.accept??``),i=(t.method===`GET`||t.method===`HEAD`)&&r.includes(`text/html`),a=g.default.request({hostname:e.target.hostname,port:e.target.port,method:t.method,path:t.url||`/`,headers:cL(t,e,i),autoSelectFamily:!0},r=>{let i=r.statusCode??502,a=String(r.headers[`content-type`]??``),o=String(r.headers[`content-encoding`]??``).toLowerCase();if(t.method===`HEAD`||i!==200||!a.toLowerCase().includes(`text/html`)||o&&o!==`identity`){n.writeHead(i,lL(r.headers,e,!1)),r.pipe(n);return}let s=[],c=0,l=!1;r.on(`data`,e=>{c+=e.length,c>16777216?l=!0:s.push(e)}),r.on(`end`,()=>{if(l){n.writeHead(502,{"Content-Type":`text/plain; charset=utf-8`}),n.end(`Preview HTML exceeds size limit`);return}let t=aL(Buffer.concat(s).toString(`utf8`),{bridgeScriptUrl:e.bridgeScriptUrl,id:e.id,viewerOrigin:e.viewerOrigin}),a=Buffer.from(t,`utf8`),o=lL(r.headers,e,!0);o[`content-length`]=String(a.length),n.writeHead(i,o),n.end(a)}),r.on(`error`,()=>{n.headersSent||n.writeHead(502,{"Content-Type":`text/plain; charset=utf-8`}),n.end(`Upstream stream error`)})});a.on(`error`,()=>{if(n.headersSent)n.end();else if(i){let t=sL(e.target.origin,e.viewerOrigin);n.writeHead(502,{"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"Content-Security-Policy":`frame-ancestors 'self' ${e.viewerOrigin}`}),n.end(t)}else n.writeHead(502,{"Content-Type":`text/plain; charset=utf-8`}),n.end(`Preview upstream unavailable: ${e.target.origin}`)}),t.pipe(a)}function dL(e,t,n,r){e.lastActivity=Date.now();let i=m.default.connect({host:e.target.hostname,port:e.target.port,autoSelectFamily:!0},()=>{let a=[`${t.method||`GET`} ${t.url||`/`} HTTP/${t.httpVersion||`1.1`}`];for(let n=0;n<t.rawHeaders.length;n+=2){let r=t.rawHeaders[n],i=t.rawHeaders[n+1]??``,o=r.toLowerCase();o===`host`?i=e.target.host:o===`origin`&&i===e.origin&&(i=e.target.origin),a.push(`${r}: ${i}`)}a.push(``,``),i.write(a.join(`\r
667
- `)),r.length>0&&i.write(r),i.pipe(n),n.pipe(i)}),a=()=>{n.destroy(),i.destroy()};i.on(`error`,a),n.on(`error`,a)}function fL(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=t=>p.default.join(e,`preview`,t,`proxy-port`),i=(e,n)=>new Promise(r=>{t.delete(e),n.server.close(()=>r()),n.server.closeAllConnections?.()}),a=setInterval(()=>{let e=Date.now();for(let[n,r]of t)e-r.lastActivity>18e5&&i(n,r)},6e5);return a.unref(),{async ensure({id:e,targetOrigin:i,viewerOrigin:a,bridgeScriptUrl:o}){let s=mu(i);if(!s)throw Error(`Refusing to proxy non-loopback origin: ${i}`);let c=t.get(e);if(c)return c.target=s,c.viewerOrigin=a,c.bridgeScriptUrl=o,c.lastActivity=Date.now(),{port:c.port,origin:c.origin};let l=n.get(e);if(l){let e=await l;return e.target=s,e.viewerOrigin=a,e.bridgeScriptUrl=o,{port:e.port,origin:e.origin}}let u=(async()=>{let n={id:e,target:s,viewerOrigin:a,bridgeScriptUrl:o,port:0,origin:``,lastActivity:Date.now(),server:null},i=g.default.createServer((e,t)=>uL(n,e,t));i.on(`upgrade`,(e,t,r)=>dL(n,e,t,r)),n.server=i;let c=r(e),l=Number(te(c)),u;try{u=await R(i,`127.0.0.1`,Number.isInteger(l)&&l>0?l:0)}catch{u=await R(i,`127.0.0.1`,0)}n.port=u,n.origin=`http://localhost:${u}`;try{d.default.mkdirSync(p.default.dirname(c),{recursive:!0}),d.default.writeFileSync(c,`${u}\n`,{mode:384})}catch{}return t.set(e,n),n})();n.set(e,u);try{let e=await u;return{port:e.port,origin:e.origin}}finally{n.delete(e)}},get(e){let n=t.get(e);return n?{port:n.port,origin:n.origin}:null},origins(){let e=[];for(let n of t.values())e.push(`http://localhost:${n.port}`,`http://127.0.0.1:${n.port}`);return e},async close(){clearInterval(a),await Promise.all([...t.entries()].map(([e,t])=>i(e,t)))}}}var pL=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r)setTimeout(function(){r(e)},0);else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h)d[r]=void 0;else{if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends pL{};function mL(e,t){let n=0;for(;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function hL(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function gL(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function _L(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function vL(e,t){return gL(e,t,``)}function yL(e,t){return _L(e,t,``)}function bL(e,t){return t.slice(0,xL(e,t))}function xL(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function SL(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function CL(e,t){if(t)return TL(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function wL(e,t){if(t)return TL(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function TL(e,t){if(!t)return[wL(e),CL(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=SL(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}const EL=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,DL=RegExp(`[${EL}]+|\\s+|[^${EL}]`,`ug`);new class extends pL{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=SL(e,r)}else n=e.match(DL)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&OL(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&OL(n,i,r,null,t.intlSegmenter),e}};function OL(e,t,n,r,i){if(t&&n){let[a,o]=TL(t.value,i),[s,c]=TL(n.value,i);if(e){let r=mL(a,s);e.value=_L(e.value,s,r),t.value=vL(t.value,r),n.value=vL(n.value,r)}if(r){let e=hL(o,c);r.value=gL(r.value,c,e),t.value=yL(t.value,e),n.value=yL(n.value,e)}}else if(n){if(e){let e=wL(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=wL(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=wL(r.value,i),[a,o]=TL(t.value,i),s=mL(n,a);t.value=vL(t.value,s);let c=hL(vL(n,s),o);t.value=yL(t.value,c),r.value=gL(r.value,n,c),e.value=_L(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=wL(r.value,i),n=bL(CL(t.value,i),e);t.value=yL(t.value,n)}else if(e){let n=bL(CL(e.value,i),wL(t.value,i));t.value=vL(t.value,n)}}new class extends pL{tokenize(e){let t=RegExp(`(\\r?\\n)|[${EL}]+|[^\\S\\n\\r]+|[^${EL}]`,`ug`);return e.match(t)||[]}};const kL=new class extends pL{constructor(){super(...arguments),this.tokenize=jL}equals(e,t,n){return n.ignoreWhitespace?(n.newlineIsToken&&e.includes(`
668
- `)||(e=e.trim()),n.newlineIsToken&&t.includes(`
669
- `)||(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
670
- `)&&(e=e.slice(0,-1)),t.endsWith(`
671
- `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function AL(e,t,n){return kL.diff(e,t,n)}function jL(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
672
- `));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function ML(e){return e==`.`||e==`!`||e==`?`}new class extends pL{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(ML(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}},new class extends pL{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends pL{constructor(){super(...arguments),this.tokenize=jL}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(NL(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};function NL(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a=0;for(;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=NL(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)
673
- /* istanbul ignore else */
674
- Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=NL(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends pL{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};const PL=e=>e.replace(/\n$/,``).split(`
675
- `);function FL(e,t){return AL(e,t).flatMap(e=>PL(e.value).map(t=>({kind:e.added?`added`:e.removed?`removed`:`same`,text:t})))}function IL(e,t=()=>/* @__PURE__ */ new Date){let n=t=>p.default.join(e,`report`,t,`history`),r=e=>{try{return JSON.parse(d.default.readFileSync(p.default.join(n(e),`index.json`),`utf8`))}catch{return{entries:[],next:1}}},i=(e,t)=>{try{return d.default.readFileSync(p.default.join(n(e),`${t}.tsx`),`utf8`)}catch{return null}},a=(e,a)=>{let o;try{o=d.default.readFileSync(p.default.join(a,H.report),`utf8`)}catch{return}let s=r(e),c=s.entries.at(-1),l=c?i(e,c.id)??``:``;if(c&&l===o)return;let u=FL(l,o),f={id:s.next,at:t().toISOString(),bytes:Buffer.byteLength(o),added:u.filter(e=>e.kind===`added`).length,removed:u.filter(e=>e.kind===`removed`).length},m=n(e);d.default.mkdirSync(m,{recursive:!0}),d.default.writeFileSync(p.default.join(m,`${f.id}.tsx`),o);let h=[...s.entries,f];for(let e of h.splice(0,Math.max(0,h.length-50)))d.default.rmSync(p.default.join(m,`${e.id}.tsx`),{force:!0});let g=p.default.join(m,`index.json.tmp`);d.default.writeFileSync(g,JSON.stringify({entries:h,next:f.id+1})),d.default.renameSync(g,p.default.join(m,`index.json`))};return{record:a,list(e,t){return a(e,t),[...r(e).entries].reverse()},diff(e,t){let{entries:n}=r(e),a=n.findIndex(e=>e.id===t);if(a===-1)return null;let o=i(e,t);return o===null?null:FL(a>0?i(e,n[a-1].id)??``:``,o)}}}const LL=e=>{try{let t=d.default.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return`gone`}};function RL(e,t=1e3){let n=/* @__PURE__ */ new Map,r,i=()=>{for(let[t,r]of n){let n=!1;for(let[e,t]of r){let i=LL(e);i!==t&&(r.set(e,i),n=!0)}n&&e(t)}};return{track(e,a){if(a.length===0)n.delete(e);else{let t=n.get(e);n.set(e,new Map(a.map(e=>[e,t?.get(e)??LL(e)])))}n.size===0?(clearInterval(r),r=void 0):r||(r=setInterval(i,t),r.unref())},close(){clearInterval(r),r=void 0,n.clear()}}}String.raw`import { spawn, spawnSync } from 'node:child_process';
676
- import fs from 'node:fs';
677
- import os from 'node:os';
678
- import path from 'node:path';
679
-
680
- const RATE = 48000;
681
- const CHANNELS = 2;
682
- const SEEK_TIMEOUT_MS = 30000;
683
-
684
- let raw = '';
685
- for await (const chunk of process.stdin) raw += chunk;
686
- const job = JSON.parse(raw);
687
- const say = (progress, stage) => console.log(JSON.stringify({ progress, stage }));
688
- const fail = (message) => {
689
- console.error(message);
690
- process.exit(1);
691
- };
692
- const cleanups = new Set();
693
- const children = new Set();
694
- const cleanUp = () => {
695
- for (const child of children) child.kill('SIGKILL');
696
- children.clear();
697
- for (const clean of cleanups) {
698
- try {
699
- clean();
700
- } catch {
701
- continue;
702
- }
703
- }
704
- cleanups.clear();
705
- };
706
- process.on('SIGTERM', () => {
707
- cleanUp();
708
- process.exit(143);
709
- });
710
- process.on('exit', cleanUp);
711
-
712
- const onPath = (name) =>
713
- (process.env.PATH || '')
714
- .split(path.delimiter)
715
- .map((dir) => path.join(dir, name))
716
- .find((file) => fs.existsSync(file));
717
-
718
- function findChrome() {
719
- if (process.env.CHROME_PATH) return fs.existsSync(process.env.CHROME_PATH) ? process.env.CHROME_PATH : null;
720
- const known =
721
- process.platform === 'darwin'
722
- ? [
723
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
724
- '/Applications/Chromium.app/Contents/MacOS/Chromium',
725
- '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
726
- ]
727
- : process.platform === 'win32'
728
- ? [
729
- path.join(process.env.PROGRAMFILES || 'C:\\Program Files', 'Google/Chrome/Application/chrome.exe'),
730
- path.join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'Google/Chrome/Application/chrome.exe'),
731
- ]
732
- : [];
733
- return (
734
- known.find((file) => fs.existsSync(file)) ||
735
- ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser'].map(onPath).find(Boolean) ||
736
- null
737
- );
738
- }
739
-
740
- const chrome = findChrome();
741
- if (!chrome) fail('Chrome not found: install Google Chrome, or set CHROME_PATH to a Chrome or Chromium binary');
742
- if (spawnSync('ffmpeg', ['-version']).status !== 0)
743
- fail('ffmpeg not found: install it (macOS: brew install ffmpeg) and export again');
744
- if (typeof WebSocket === 'undefined') fail('this script needs Node 22 or later');
745
-
746
- const exec = (args, input) =>
747
- new Promise((resolve, reject) => {
748
- const child = spawn('ffmpeg', ['-v', 'error', '-y', ...args], { stdio: ['pipe', 'pipe', 'pipe'] });
749
- children.add(child);
750
- const out = [];
751
- let err = '';
752
- child.stdout.on('data', (chunk) => out.push(chunk));
753
- child.stderr.on('data', (chunk) => (err = (err + chunk).slice(-4000)));
754
- child.on('error', reject);
755
- child.on('close', (code) => {
756
- children.delete(child);
757
- if (code === 0) resolve(Buffer.concat(out));
758
- else reject(new Error('ffmpeg: ' + err.trim()));
759
- });
760
- if (input) input(child.stdin);
761
- else child.stdin.end();
762
- });
763
-
764
- function cdp(url) {
765
- return new Promise((resolve, reject) => {
766
- const ws = new WebSocket(url);
767
- const waiting = new Map();
768
- let id = 0;
769
- ws.onmessage = (event) => {
770
- const message = JSON.parse(event.data);
771
- const pending = message.id && waiting.get(message.id);
772
- if (!pending) return;
773
- waiting.delete(message.id);
774
- if (message.error) pending.reject(new Error(message.error.message));
775
- else pending.resolve(message.result);
776
- };
777
- ws.onerror = () => reject(new Error('could not reach Chrome'));
778
- ws.onopen = () =>
779
- resolve({
780
- send: (method, params = {}) =>
781
- new Promise((ok, no) => {
782
- id += 1;
783
- waiting.set(id, { resolve: ok, reject: no });
784
- ws.send(JSON.stringify({ id, method, params }));
785
- }),
786
- close: () => ws.close(),
787
- });
788
- });
789
- }
790
-
791
- async function launch() {
792
- const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'ryugi-render-'));
793
- const child = spawn(
794
- chrome,
795
- [
796
- '--headless=new',
797
- '--remote-debugging-port=0',
798
- '--user-data-dir=' + profile,
799
- '--no-first-run',
800
- '--no-default-browser-check',
801
- '--hide-scrollbars',
802
- '--mute-audio',
803
- '--autoplay-policy=no-user-gesture-required',
804
- 'about:blank',
805
- ],
806
- { stdio: 'ignore', detached: process.platform !== 'win32' },
807
- );
808
- const stop = () => {
809
- try {
810
- if (process.platform !== 'win32') process.kill(-child.pid, 'SIGKILL');
811
- else child.kill('SIGKILL');
812
- } catch {}
813
- fs.rmSync(profile, { recursive: true, force: true });
814
- };
815
- cleanups.add(stop);
816
- const portFile = path.join(profile, 'DevToolsActivePort');
817
- for (let tries = 0; tries < 200 && !fs.existsSync(portFile); tries += 1)
818
- await new Promise((resolve) => setTimeout(resolve, 100));
819
- if (!fs.existsSync(portFile)) fail('Chrome did not open its DevTools port');
820
- const port = fs.readFileSync(portFile, 'utf8').split('\n')[0];
821
- const target = await (await fetch('http://127.0.0.1:' + port + '/json/new?about:blank', { method: 'PUT' })).json();
822
- const page = await cdp(target.webSocketDebuggerUrl);
823
- await page.send('Page.enable');
824
- await page.send('Emulation.setDeviceMetricsOverride', {
825
- width: job.width,
826
- height: job.height,
827
- deviceScaleFactor: 1,
828
- mobile: false,
829
- });
830
- return { page, stop };
831
- }
832
-
833
- async function evaluate(page, expression) {
834
- const result = await page.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
835
- if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description || expression);
836
- return result.result.value;
837
- }
838
-
839
- async function open(page, from, to) {
840
- const url = new URL(job.renderUrl);
841
- url.searchParams.set('from', String(from));
842
- url.searchParams.set('to', String(to));
843
- if (!job.captions) url.searchParams.set('captions', '0');
844
- await page.send('Page.navigate', { url: url.toString() });
845
- const until = Date.now() + SEEK_TIMEOUT_MS;
846
- while (!(await evaluate(page, 'Boolean(window.ryugiStoryboard && window.ryugiStoryboard.duration > 0)'))) {
847
- if (Date.now() > until) throw new Error('the render page did not load: ' + url.pathname);
848
- await new Promise((resolve) => setTimeout(resolve, 100));
849
- }
850
- }
851
-
852
- const frameOf = (seconds) => Math.round(seconds * job.fps);
853
- const totalFrames = Math.max(1, frameOf(job.duration));
854
- let framesDone = 0;
855
-
856
- async function renderSegment(page, shot) {
857
- const first = frameOf(shot.start);
858
- const last = frameOf(shot.start + shot.dur);
859
- const count = last - first;
860
- const file = path.join(job.cache, shot.segment + '-' + job.fps + '.mp4');
861
- if (count <= 0) return null;
862
- if (fs.existsSync(file)) {
863
- framesDone += count;
864
- say((framesDone / totalFrames) * 0.85, 'shot ' + shot.id + ' (cached)');
865
- return file;
866
- }
867
- const from = first / job.fps;
868
- const to = last / job.fps;
869
- await open(page, from, to);
870
- const temp = file + '.' + process.pid + '.tmp.mp4';
871
- const dropTemp = () => fs.rmSync(temp, { force: true });
872
- cleanups.add(dropTemp);
873
- await exec(
874
- ['-f', 'image2pipe', '-framerate', String(job.fps), '-c:v', 'mjpeg', '-i', '-', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '16', '-pix_fmt', 'yuv420p', '-r', String(job.fps), temp],
875
- async (stdin) => {
876
- for (let frame = 0; frame < count; frame += 1) {
877
- await evaluate(page, 'window.ryugiStoryboard.seek(' + frame / job.fps + ')');
878
- const shotData = await page.send('Page.captureScreenshot', { format: 'jpeg', quality: 92, fromSurface: true });
879
- if (!stdin.write(Buffer.from(shotData.data, 'base64'))) await new Promise((resolve) => stdin.once('drain', resolve));
880
- framesDone += 1;
881
- if (frame % job.fps === 0) say((framesDone / totalFrames) * 0.85, 'shot ' + shot.id);
882
- }
883
- stdin.end();
884
- },
885
- );
886
- fs.renameSync(temp, file);
887
- cleanups.delete(dropTemp);
888
- return file;
889
- }
890
-
891
- function levelAt(envelope, time) {
892
- if (!envelope.length) return 0;
893
- if (time <= envelope[0][0]) return envelope[0][1];
894
- for (let index = 1; index < envelope.length; index += 1) {
895
- const [t1, v1] = envelope[index];
896
- if (time > t1) continue;
897
- const [t0, v0] = envelope[index - 1];
898
- return t1 > t0 ? v0 + ((v1 - v0) * (time - t0)) / (t1 - t0) : v1;
899
- }
900
- return envelope[envelope.length - 1][1];
901
- }
902
-
903
- function tempo(speed) {
904
- const parts = [];
905
- let rest = speed;
906
- while (rest < 0.5) {
907
- parts.push(0.5);
908
- rest /= 0.5;
909
- }
910
- parts.push(rest);
911
- return parts.map((each) => 'atempo=' + each).join(',');
912
- }
913
-
914
- async function mixAudio() {
915
- const samples = Math.ceil(job.duration * RATE);
916
- const mix = new Float32Array(samples * CHANNELS);
917
- const sources = [...job.audio.voice, ...job.audio.music, ...job.audio.sfx, ...(job.audio.takes || [])];
918
- for (const source of sources) {
919
- const end = Math.min(source.end, job.duration);
920
- if (end <= source.start || source.envelope.every(([, level]) => level === 0)) continue;
921
- let pcm;
922
- try {
923
- const speed = source.speed || 1;
924
- const filter = speed === 1 ? [] : ['-af', tempo(speed)];
925
- pcm = await exec(['-ss', String(source.from), '-t', String((end - source.start) * speed), '-i', path.resolve(job.dir, source.file), '-vn', ...filter, '-f', 'f32le', '-ac', String(CHANNELS), '-ar', String(RATE), '-']);
926
- } catch (error) {
927
- console.error('skipped ' + source.file + ': ' + error.message);
928
- continue;
929
- }
930
- const offset = Math.round(source.start * RATE);
931
- const frames = Math.min(pcm.length / 4 / CHANNELS, samples - offset);
932
- for (let frame = 0; frame < frames; frame += 1) {
933
- const level = levelAt(source.envelope, source.start + frame / RATE);
934
- if (level === 0) continue;
935
- for (let channel = 0; channel < CHANNELS; channel += 1) {
936
- const at = (offset + frame) * CHANNELS + channel;
937
- mix[at] += pcm.readFloatLE((frame * CHANNELS + channel) * 4) * level;
938
- }
939
- }
940
- }
941
- for (let index = 0; index < mix.length; index += 1) mix[index] = Math.max(-1, Math.min(1, mix[index]));
942
- return Buffer.from(mix.buffer);
943
- }
944
-
945
- fs.mkdirSync(job.cache, { recursive: true });
946
- fs.mkdirSync(path.dirname(job.out), { recursive: true });
947
- const browser = await launch();
948
- const segments = [];
949
- try {
950
- for (const shot of job.shots) {
951
- const file = await renderSegment(browser.page, shot);
952
- if (file) segments.push(file);
953
- }
954
- } finally {
955
- browser.page.close();
956
- browser.stop();
957
- }
958
- say(0.88, 'sound');
959
- const work = fs.mkdtempSync(path.join(os.tmpdir(), 'ryugi-mix-'));
960
- cleanups.add(() => fs.rmSync(work, { recursive: true, force: true }));
961
- const mixFile = path.join(work, 'mix.f32');
962
- fs.writeFileSync(mixFile, await mixAudio());
963
- const list = path.join(work, 'segments.txt');
964
- fs.writeFileSync(list, segments.map((file) => "file '" + file.replaceAll("'", "'\\''") + "'").join('\n') + '\n');
965
- say(0.92, 'encode');
966
- await exec([
967
- '-f', 'concat', '-safe', '0', '-i', list,
968
- '-f', 'f32le', '-ar', String(RATE), '-ac', String(CHANNELS), '-i', mixFile,
969
- '-map', '0:v', '-map', '1:a',
970
- '-c:v', 'libx264', '-preset', 'medium', '-b:v', '1500k', '-maxrate', '2000k', '-bufsize', '3000k', '-pix_fmt', 'yuv420p',
971
- '-c:a', 'aac', '-b:a', '160k', '-t', String(job.duration), '-movflags', '+faststart',
972
- job.out,
973
- ]);
974
- fs.rmSync(work, { recursive: true, force: true });
975
- say(1, 'done');
976
- `;const zL=`render/render.mjs`,BL=`voice/voice.mjs`,VL=`.ogg`,HL=`print {"duration": <seconds above 0>}`;function UL(e){let t={};for(let n of[`.env`,`.env.local`])try{Object.assign(t,mp(d.default.readFileSync(p.default.join(e,n),`utf8`)))}catch{continue}return t}function WL({env:e,input:t,node:n,project:r,script:i,timeoutMs:a}){return new Promise(o=>{let s=(0,l.spawn)(n,[...w(`storyboard voice`),i],{cwd:r,env:e,detached:process.platform!==`win32`,stdio:[`pipe`,`pipe`,`pipe`]}),c=``,u=``,d=!1,f=()=>{try{s.pid&&process.platform!==`win32`?process.kill(-s.pid,`SIGKILL`):s.kill(`SIGKILL`)}catch{s.kill(`SIGKILL`)}},p=e=>{d||(d=!0,clearTimeout(m),o(e))},m=setTimeout(()=>{f(),p({error:`timed out after ${a/1e3} s`})},a);s.stdout.on(`data`,e=>{c+=e.toString(`utf8`),c.length>65536&&(f(),p({error:`printed too much: ${HL} and nothing else`}))}),s.stderr.on(`data`,e=>{u=(u+e.toString(`utf8`)).slice(-4096)}),s.stdin.on(`error`,()=>{}),s.on(`error`,e=>p({error:`could not start: ${e.message}`})),s.on(`close`,e=>{let t=u.trim().slice(-2048);if(e!==0)p({error:`exited with code ${e}${t?`: ${t}`:``}`});else try{let e=c.trim().split(`
977
- `).pop()??``,t=JSON.parse(e).duration;p(typeof t==`number`&&Number.isFinite(t)&&t>0?{duration:t}:{error:`did not ${HL}`})}catch{p({error:`did not ${HL} as JSON`})}}),s.stdin.end(JSON.stringify(t))})}function GL(e){let t=0,n=[];return async r=>{for(;t>=e;)await new Promise(e=>n.push(e));t+=1;try{return await r()}finally{--t,n.shift()?.()}}}function KL(e){let t={node:e.node??process.execPath,env:e.env??process.env,timeoutMs:e.timeoutMs??6e4,debounceMs:e.debounceMs??1e3},n=GL(e.concurrency??2),r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=t=>p.default.join(e.stateDir,...t.split(`/`),`voice.json`),s=e=>{try{return JSON.parse(d.default.readFileSync(o(e),`utf8`))}catch{return{}}},c=(e,t,n)=>{let r=s(e);if(n===null&&!(t in r))return;let i={...r};n===null?delete i[t]:i[t]=n,U(o(e),i)},l=(e,t)=>{let n=(i.get(e)??Promise.resolve()).then(()=>{let n=XE(e);t(n),U(p.default.join(e,VE),n)});return i.set(e,n.catch(()=>{})),n},u=(e,i,a,o,s)=>{let c=`${e}:${o}`,l=r.get(c);if(l)return l;let u=p.default.join(e,BE,`${o}.partial${VL}`);d.default.mkdirSync(p.default.join(e,BE),{recursive:!0});let f=pp(e),m=JE(i,a),h=n(()=>WL({node:t.node,env:{...t.env,...UL(f)},project:f,script:p.default.join(e,BL),timeoutMs:t.timeoutMs,input:{text:qE(i,a),voice:i.voice,lang:i.lang,out:u,...m?{direction:m}:{}}})).then(t=>`error`in t?(d.default.rmSync(u,{force:!0}),t):(d.default.statSync(u,{throwIfNoEntry:!1})?.size??0)===0?(d.default.rmSync(u,{force:!0}),{error:`wrote no audio to the out path it was given`}):(d.default.renameSync(u,p.default.join(e,s)),t));return r.set(c,h),h.finally(()=>r.delete(c)),h},f=async(t,n,r,i,a)=>{let o=YE(r,i),s=XE(t),f=e=>d.default.existsSync(p.default.join(t,e)),m=s.lines[i.id];if(!a&&m?.hash===o&&f(m.file))return{id:i.id,ok:!0,cached:!0,duration:m.duration};let h=s.cache[o];if(!a&&h&&f(h.file))return await l(t,e=>{e.lines[i.id]={...h,hash:o}}),c(n,i.id,null),e.onVoiced?.(n,t),{id:i.id,ok:!0,cached:!0,duration:h.duration};let g=`${BE}/${o}${VL}`,_=await u(t,r,i,o,g);return`error`in _?(c(n,i.id,_.error),{id:i.id,ok:!1,error:_.error}):(await l(t,e=>{e.lines[i.id]={file:g,duration:_.duration,hash:o},e.cache[o]={file:g,duration:_.duration}}),c(n,i.id,null),e.onVoiced?.(n,t),{id:i.id,ok:!0,duration:_.duration})},m=async(e,t,n={})=>{let r;try{r=d.default.readFileSync(p.default.join(e,H.storyboard),`utf8`)}catch{return{error:`${H.storyboard} not found`,lines:[]}}let{model:i}=gT(r);if(!i)return{error:`${H.storyboard} does not parse; run check`,lines:[]};if(!d.default.existsSync(p.default.join(e,`voice/voice.mjs`)))return{error:`no ${BL}: run ryugi start --artifact ${t} to create it from the template`,lines:[]};let a=i.shots.flatMap(e=>e.lines).filter(e=>e.text&&(!n.line||e.id===n.line));return n.line&&a.length===0?{error:`no line ${n.line} with words in this storyboard`,lines:[]}:{lines:await Promise.all(a.map(r=>f(e,t,i,r,!!n.force)))}};return{synthesize:m,schedule:(e,n)=>{clearTimeout(a.get(n)),a.set(n,setTimeout(()=>{a.delete(n),d.default.existsSync(p.default.join(e,`voice/voice.mjs`))&&m(e,n).catch(()=>{})},t.debounceMs))},failures:s,close:()=>{for(let e of a.values())clearTimeout(e);a.clear()},active:()=>r.size>0||a.size>0}}const qL=`.state/export`,JL=(e,t)=>({ok:!1,status:e,error:t});function YL(e){let t;try{t=d.default.readFileSync(p.default.join(e,H.storyboard),`utf8`)}catch{return`${H.storyboard} not found`}let{model:n}=gT(t);return n?{source:t,model:n,hashes:vD(e,n)}:`${H.storyboard} does not parse; run check`}function XL(e){let t=new URL(e);return t.searchParams.set(`snapshot`,`1`),t.toString()}const ZL=e=>[.../* @__PURE__ */ new Set([...e.music.map(e=>e.src),...e.shots.flatMap(e=>e.sfx.map(e=>e.src))])];function QL(e,t,n){try{e&&process.platform!==`win32`?process.kill(-e,t):n()}catch{n()}}function $L(e){let t={node:e.node??process.execPath,env:e.env??process.env,timeoutMs:e.timeoutMs??18e5},n=/* @__PURE__ */ new Map,r=(t,n,r,i)=>{r.status={...r.status,...i,at:(/* @__PURE__ */ new Date()).toISOString()},e.onChange?.(t,n)},i=(e,n,i,a)=>new Promise(o=>{let s=pp(e),c=(0,l.spawn)(t.node,[...w(`storyboard render`),p.default.join(e,zL)],{cwd:s,env:{...t.env,...UL(s)},detached:process.platform!==`win32`,stdio:[`pipe`,`pipe`,`pipe`]}),u=``,f=``,m=null,h;i.stop=()=>{QL(c.pid,`SIGTERM`,()=>c.kill(`SIGTERM`)),h??=setTimeout(()=>QL(c.pid,`SIGKILL`,()=>c.kill(`SIGKILL`)),3e3)};let g=setTimeout(()=>{m=`timed out after ${t.timeoutMs/6e4} min`,i.stop?.()},t.timeoutMs);c.stdout.on(`data`,t=>{u+=t.toString(`utf8`);let a=u.split(`
978
- `);u=(a.pop()??``).slice(-4096);for(let t of a)try{let a=JSON.parse(t);r(n,e,i,{...typeof a.progress==`number`&&Number.isFinite(a.progress)?{progress:Math.min(1,Math.max(0,a.progress))}:{},...typeof a.stage==`string`?{stage:a.stage.slice(0,200)}:{}})}catch{continue}}),c.stderr.on(`data`,e=>{f=(f+e.toString(`utf8`)).slice(-4096)}),c.stdin.on(`error`,()=>{}),c.on(`error`,e=>{m=`could not start: ${e.message}`}),c.on(`close`,e=>{clearTimeout(g),clearTimeout(h),i.stop=void 0;let t=f.trim().slice(-2048);m?o(m):e===0?(d.default.statSync(a.out,{throwIfNoEntry:!1})?.size??0)===0?o(`${zL} wrote no video to the out path it was given`):o(null):o(`${zL} exited with code ${e}${t?`: ${t}`:``}`)}),c.stdin.end(JSON.stringify(a))}),a=async(t,n,a,o,s)=>{let{model:c}=o,l=(e,i)=>(d.default.rmSync(s,{force:!0}),a.snapshot=void 0,r(n,t,a,{state:e,...i?{error:i}:{}}),a.status);try{let u=c.shots.flatMap(e=>e.lines).filter(e=>e.text);if(e.voice&&u.length&&d.default.existsSync(p.default.join(t,`voice/voice.mjs`))){r(n,t,a,{stage:`voice`});let i=await e.voice.synthesize(t,n),o=i.error??i.lines.find(e=>!e.ok)?.error;if(a.cancelled)return l(`cancelled`);if(o)return l(`failed`,`voice: ${o}`)}if(a.cancelled)return l(`cancelled`);a.snapshot=tO(t,n.split(`/`)[1],o.source);let f=xD({dir:t,model:c,audio:Object.fromEntries([...ZE(t,c)].map(([e,t])=>[e,{file:t.file,duration:t.duration}])),n:a.status.n,out:s,cache:p.default.join(t,qL,`cache`),renderUrl:XL(e.renderUrl(n)),hashes:o.hashes});d.default.mkdirSync(p.default.dirname(s),{recursive:!0}),d.default.rmSync(s,{force:!0}),r(n,t,a,{stage:`render`});let m=await i(t,n,a,f);if(a.cancelled)return l(`cancelled`);if(m)return l(`failed`,m);let h=vD(t,c),g=new Set(c.shots.filter(e=>h[e.id]!==o.hashes[e.id]).map(e=>e.id));f.shots.forEach((e,t)=>{let n=f.shots[t-1],r=f.shots[t+1];(g.has(e.id)||e.transition&&n&&g.has(n.id)||r?.transition&&g.has(r.id))&&d.default.rmSync(p.default.join(f.cache,`${e.segment}-${f.fps}.mp4`),{force:!0})});let _=OT(t,{file:s,map:{shots:f.shots.map(e=>({id:e.id,start:e.start,end:e.start+e.dur}))},hashes:o.hashes,model:c});return a.status={...a.status,n:_.n,progress:1},l(`done`)}catch(e){return l(`failed`,e.message)}},o=(t,r)=>{if(n.get(r)?.status.state===`running`)return JL(409,`an export of ${r} is already running`);let i=YL(t);if(typeof i==`string`)return JL(400,i);let{model:o}=i;if(!d.default.existsSync(p.default.join(t,`render/render.mjs`)))return JL(400,`no ${zL}: run ryugi storyboard template --artifact ${r} to create it`);let s=ZL(o).filter(e=>!d.default.existsSync(p.default.join(t,e)));if(s.length)return JL(400,`missing sound files: ${s.join(`, `)}`);let c=(TT(t).at(-1)?.n??0)+1,l={cancelled:!1,status:{state:`running`,n:c,progress:0,stage:`start`,at:(/* @__PURE__ */ new Date()).toISOString()}};return n.set(r,l),e.onChange?.(r,t),{ok:!0,n:c,finished:a(t,r,l,i,p.default.join(t,qL,`${c}.mp4`))}},s=e=>{let t=n.get(e);return!t||t.status.state!==`running`?!1:(t.cancelled=!0,t.stop?.(),!0)};return{start:o,cancel:s,snapshot:e=>{let t=n.get(e);return t?.status.state===`running`?t.snapshot??null:null},status:e=>n.get(e)?.status??null,close:()=>{for(let e of n.keys())s(e)}}}function eR(e,t,n){return new Promise((r,i)=>{(0,l.execFile)(e,t,{encoding:`utf8`,maxBuffer:16777216,timeout:12e4,signal:n},(t,n,a)=>{t?i(/* @__PURE__ */ Error(t.code===`ENOENT`?`${e} is unavailable; install FFmpeg to enable automatic recording preparation`:`${e}: ${a.trim()||t.message}`)):r({stdout:n,stderr:a})})})}async function tR(e,t,n){if(e===t||d.default.existsSync(t))throw Error(`Choose a new output path; existing files are never overwritten.`);let r=JSON.parse((await eR(`ffprobe`,[`-v`,`error`,`-show_streams`,`-show_format`,`-of`,`json`,e],n)).stdout),i=r.streams.find(e=>e.codec_type===`video`);if(!i)throw Error(`The recording has no video stream`);let a=Number(i.start_time)-Number(r.format.start_time),o=Number.isFinite(a)?Math.max(0,a):0,s=await eR(`ffmpeg`,[`-hide_banner`,`-nostdin`,`-nostats`,`-i`,e,`-progress`,`pipe:1`,`-filter_complex`,`[0:v:0]setpts=PTS-STARTPTS,split=3[all][edges][stillness];[edges]mpdecimate=hi=1536:lo=640,showinfo@edges[e];[stillness]scale=iw/4:-2,gblur=sigma=1,mpdecimate=hi=1536:lo=640,showinfo@stillness[s]`,`-map`,`[all]`,`-f`,`null`,`-`,`-map`,`[e]`,`-f`,`null`,`-`,`-map`,`[s]`,`-f`,`null`,`-`],n),c=[...s.stdout.matchAll(/^out_time_us=(\d+)$/gm)].at(-1),l=Number(c?.[1])/1e6;if(!Number.isFinite(l)||l<=0)throw Error(`Cannot determine the decoded recording duration`);let u={edges:[],stillness:[]};for(let e of s.stderr.matchAll(/\[showinfo@(edges|stillness) @ [^\]]+\] n:\s*\d+ .*?pts_time:([\d.e+-]+)/g)){let t=Number(e[2]);if(!Number.isFinite(t))throw Error(`Invalid frame timestamp`);u[e[1]].push(t)}let f=0,m=l,h=`unchanged`;if(u.stillness.length<=1)h=`no-motion`;else if(u.edges.length>1){if(f=Math.max(0,u.edges[1]-1),m=Math.min(l,u.edges.at(-1)+1),m<=f)throw Error(`No safe continuous recording interval`);(f>0||m<l)&&(h=`trimmed`)}if(h===`trimmed`){let r=d.default.mkdtempSync(p.default.join(p.default.dirname(t),`.trim-`));try{let i=p.default.join(r,`clip.mp4`);await eR(`ffmpeg`,[`-hide_banner`,`-nostdin`,`-loglevel`,`error`,`-ss`,String(f+o),`-i`,e,`-t`,String(m-f),`-map`,`0:v:0`,`-map`,`0:a:0?`,`-c:v`,`libx264`,`-crf`,`18`,`-preset`,`fast`,`-pix_fmt`,`yuv420p`,`-vf`,`pad=ceil(iw/2)*2:ceil(ih/2)*2`,`-c:a`,`aac`,`-movflags`,`+faststart`,i],n),d.default.linkSync(i,t)}finally{d.default.rmSync(r,{recursive:!0,force:!0})}}return{duration:l,start:f,end:m,removed:l-(m-f),status:h}}const nR=e=>u.default.createHash(`sha256`).update(e).digest(`hex`),rR=e=>{let t=d.default.statSync(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}:${t.ctimeMs}`};function iR(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=[],i=/* @__PURE__ */ new Map,a,o=!1,s=e=>!o&&t.get(e.key)===e&&!e.controller.signal.aborted,c=t=>{s(t)&&e.onChange(t.artifact)},l=p.default.join(e.stateDir,`recordings`);async function u(n){let r;try{if(rR(n.file)!==n.stamp){t.delete(n.key),e.onChange(n.artifact);return}let a=await d.default.promises.readFile(n.file);if(!s(n))return;if(rR(n.file)!==n.stamp){t.delete(n.key),e.onChange(n.artifact);return}let o=nR(`idle-ends-v2:${nR(a)}`),u=p.default.join(l,o),f=p.default.join(u,`clip.mp4`),m=p.default.join(u,`result.json`),h;try{let e=JSON.parse(d.default.readFileSync(m,`utf8`));(e.result.status!==`trimmed`||d.default.existsSync(f)&&e.hash===nR(d.default.readFileSync(f)))&&(h=e)}catch{}if(!h){d.default.mkdirSync(l,{recursive:!0}),r=d.default.mkdtempSync(p.default.join(l,`.prepare-`));let i=p.default.join(r,`capture`),o=p.default.join(r,`clip.mp4`);d.default.writeFileSync(i,a);let c=await(e.prepare??tR)(i,o,n.controller.signal);if(!s(n))return;if(rR(n.file)!==n.stamp){t.delete(n.key),e.onChange(n.artifact);return}d.default.mkdirSync(u,{recursive:!0});let g=c.status===`trimmed`?nR(d.default.readFileSync(o)):void 0;c.status===`trimmed`&&d.default.copyFileSync(o,f),h={result:c,...g?{hash:g}:{}},U(m,h)}if(!s(n))return;if(rR(n.file)!==n.stamp){t.delete(n.key),e.onChange(n.artifact);return}n.state={...h.result,status:`ready`,outcome:h.result.status,...h.result.status===`no-motion`?{warning:`the recording shows no visible change (${Math.round(h.result.duration)}s); the capture missed the actions, so record it again, or use before/after screenshots if the only change is too small to see in a video`}:{}},h.result.status===`trimmed`&&(n.output=f,n.virtual=`pages/ryugi-recordings/${o}.mp4`,n.hash=h.hash,i.set(`${n.artifact}/${n.virtual}`,f)),c(n)}catch(e){if(!s(n))return;n.state={status:`original`,warning:`Using the original recording: ${e.message}`},c(n)}finally{r&&d.default.rmSync(r,{recursive:!0,force:!0})}}function f(){if(a||o)return;let e=r.shift();e&&(s(e)?a=u(e).finally(()=>{a=void 0,f()}):f())}let m=e=>{clearTimeout(e.timer),e.controller.abort(),t.delete(e.key)};return{active:()=>a!==void 0||r.length>0,project(i,a,s){if(!s.canvas||o)return s;let c={...s.canvas,boards:{...s.canvas.boards}},l=new Set(Object.values(c.groups??{}).filter(e=>e.verify).flatMap(e=>e.boards)),u=/* @__PURE__ */ new Set,p={},h=new Set(s.pending),g={...s.versions};for(let e of n.keys())e.startsWith(`${i}/`)&&n.delete(e);for(let[o,s]of Object.entries(c.boards)){if(s.type!==`video`||s.trim===!1||!l.has(o))continue;let _=it(a,s.file);if(!_||!g[s.file])continue;let v=`${i}/${s.file}`;u.add(v);let y=t.get(v),b=rR(_);if(y&&y.stamp!==b&&(m(y),y=void 0),!y){y={artifact:i,key:v,file:_,stamp:b,state:{status:`processing`},controller:new AbortController},t.set(v,y);let n=y;y.timer=setTimeout(()=>{r.push(n),f()},e.stableMs??750)}n.set(`${i}/${o}`,y),p[o]=y.state,y.state.status===`processing`&&h.add(o),y.virtual&&y.output&&(c.boards[o]={...s,file:y.virtual,src:y.virtual},g[y.virtual]=d.default.statSync(y.output).mtimeMs)}for(let e of t.values())e.artifact===i&&!u.has(e.key)&&m(e);return c.building=h.size>0,{...s,canvas:c,versions:g,pending:[...h].sort(),...Object.keys(p).length?{recordings:p}:{}}},resolve(e,t){return i.get(`${e}/${t}`)??null},evidenceHash(e,t,r){let i=n.get(`${e}/${t}`);return i?.state.status===`processing`?`${r}:preparing`:i?.hash?nR(`${r}:${i.hash}`):r},overrides(e,n){let r=/* @__PURE__ */ new Map;if(!n.canvas)return r;let i=new Set(Object.values(n.canvas.boards).map(e=>e.file));for(let n of t.values()){if(n.artifact!==e||!n.virtual||!n.output||!i.has(n.virtual))continue;let t=n.key.slice(e.length+1);i.has(t)||r.set(t,null),r.set(n.virtual,d.default.readFileSync(n.output))}return r.size&&r.set(`canvas.json`,Buffer.from(JSON.stringify(n.canvas))),r},async close(){o=!0;for(let e of t.values())m(e);await a}}}const aR=()=>Math.floor(Math.random()*2**31),oR=(e,t)=>{if(typeof t.version!=`number`)return!0;let n=e.version??0;return n===t.version?(e.versionNonce??0)<(t.versionNonce??0):n>t.version};function sR(e,t,n){return ly([...e.map(e=>t.get(e.id)??e),...n])}function cR(e,t,n={}){let r=new Map(e.map(e=>[e.id,e])),i=/* @__PURE__ */ new Map,a=[],o=[];for(let e of t){let t=i.get(e.id)??r.get(e.id);if(!t){let t=n.completion?`agent`:`human`;a.push(fy(e,{author:t,rev:1,lastBy:t})),o.push(e.id);continue}if(!(n.completion===!0&&ay(t))&&!oR(e,t))continue;let s=dy(t),c=s.rev??1,l=!n.completion&&iy(e)!==iy(t),u=fy({...e,customData:{...t.customData,...e.customData}},{author:s.author??`human`,rev:l?c+1:c,lastBy:l?`human`:s.lastBy??s.author??`human`});i.set(e.id,u),o.push(e.id)}return{elements:sR(e,i,a),changed:o}}function lR(e){return e.map(e=>{let t=dy(e);return fy(e,{author:t.author??`agent`,rev:t.rev??1,lastBy:t.lastBy??t.author??`agent`})})}function uR(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set;for(let r of e)(t.has(r.id)?n:t).add(r.id);return[...n]}function dR(e,t){let n=new Map(e.map(e=>[e.id,e])),r=/* @__PURE__ */ new Map,i=[],a={added:[],updated:[],deleted:[],conflicts:[]};for(let e of t){let t=n.get(e.id);if(!t){if(e.isDeleted||i.some(t=>t.id===e.id))continue;i.push(lR([e])[0]),a.added.push(e.id);continue}let o=e.isDeleted===!0&&t.isDeleted!==!0,s=t.index===void 0?e:{...e,index:t.index};if(!o&&ey(s)===ey(t))continue;let c=dy(t),l=c.rev??1;if((dy(e).rev??(c.lastBy===`human`?void 0:l))!==l){a.conflicts.push(e.id);continue}let u=Math.max(t.version??0,e.version??0)+1,d=o?{...t,isDeleted:!0}:s;r.set(e.id,fy({...d,version:u,versionNonce:aR(),customData:{...t.customData,...e.customData}},{author:c.author??`agent`,rev:l+1,lastBy:`agent`})),(o?a.deleted:a.updated).push(e.id)}for(let t of e){if(!t.containerId||t.isDeleted||r.has(t.id)||!a.deleted.includes(t.containerId))continue;let e=dy(t);r.set(t.id,fy({...t,isDeleted:!0,version:(t.version??0)+1,versionNonce:aR()},{author:e.author??`agent`,rev:(e.rev??1)+1,lastBy:`agent`})),a.deleted.push(t.id)}return{elements:sR(e,r,i),...a}}const fR=()=>({type:`excalidraw`,version:2,source:`ryugi`,elements:[],appState:{},files:{}}),pR=e=>{try{return d.default.readFileSync(e,`utf8`)}catch{return null}},mR=e=>{let t=e;return typeof e==`object`&&!!e&&[t.x,t.y,t.w,t.h].every(e=>typeof e==`number`&&Number.isFinite(e))},hR=e=>{let t=e;return typeof e==`object`&&!!e&&typeof t.sceneVersion==`number`&&typeof t.elements==`object`&&t.elements!==null&&!Array.isArray(t.elements)&&Object.values(t.elements).every(mR)};function gR(e,t){let n=`${e}.${process.pid}.tmp`;d.default.writeFileSync(n,t),d.default.renameSync(n,e)}function _R(e){let t=e.writeDelayMs??500,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=e.stateDir??p.default.join(e.root,`.state`),c=e=>p.default.join(s,`whiteboard`,e),l=(e,t)=>p.default.join(c(e),`pages`,t),u=(e,t)=>`${e}\n${t}`,f=t=>{let n=r.get(t);if(n)return n;let i=W(e.root,`whiteboard`,t);if(!i)return null;let a=p.default.join(i,He),o=pR(a),s=Xe(o),c={agentWarnings:[],dir:i,file:a,raw:s.pages,problem:s.error??null,written:o};return r.set(t,c),c},m=e=>{let t=f(e);return t?Ze(t.raw,_y(t.dir)):null},h=(t,n,r)=>{let i=Ze(r,_y(n.dir)).pages;n.raw=i;let a=et(i);a!==n.written&&(gR(n.file,a),n.written=a),e.onPages?.(t,i)},g=(t,r)=>{if(!Ge(r))return null;let i=n.get(u(t,r));if(i)return i;let a=W(e.root,`whiteboard`,t);if(!a)return null;let o=p.default.join(a,Ke(r)),s=pR(o),c=s===null?{scene:fR()}:my(s,Ke(r)),l={id:t,page:r,file:o,duplicates:`scene`in c?uR(c.scene.elements):[],scene:`scene`in c?{...c.scene,elements:lR(c.scene.elements)}:fR(),problem:`error`in c?c.error:null,conflicts:[],written:s,pending:!1,timer:null};return n.set(u(t,r),l),l},_=e=>{if(e.timer&&clearTimeout(e.timer),e.timer=null,!e.pending||e.problem||(pR(e.file)!==e.written&&y(e.id,e.page),e.timer&&clearTimeout(e.timer),e.timer=null,e.problem))return;e.pending=!1;let t=hy(e.scene);t!==e.written&&(d.default.mkdirSync(p.default.dirname(e.file),{recursive:!0}),gR(e.file,t),e.written=t)},v=e=>{e.pending=!0,e.timer&&clearTimeout(e.timer),e.timer=setTimeout(()=>_(e),t),e.timer.unref?.()},y=(t,n=Ve)=>{let r=g(t,n);if(!r)return;let i=pR(r.file);if(i===null||i===r.written)return;r.written=i;let a=my(i,Ke(n));if(`error`in a){r.problem=a.error;return}r.problem=null,r.duplicates=uR(a.scene.elements);let o=dR(r.scene.elements,a.scene.elements),s=r.scene.files,c=Object.fromEntries(Object.entries(a.scene.files).filter(([e])=>!(e in s)));r.scene={...a.scene,elements:o.elements,files:{...s,...a.scene.files}},r.conflicts=o.conflicts;let l=[...o.added,...o.updated],u=/* @__PURE__ */ new Set([...l,...o.deleted]),d=Object.keys(c).length>0;(u.size>0||d)&&e.onUpdate(t,{page:n,elements:o.elements.filter(e=>u.has(e.id)),agent:{changed:l,deleted:o.deleted.length,last:l.at(-1)??null},...d?{files:c}:{}}),v(r)},b=e=>{let t=f(e);if(!t)return;let n=pR(t.file);if(n===null||n===t.written)return;t.written=n;let r=Xe(n);if(r.error){t.problem=r.error;return}t.problem=null;let i=Qe(t.raw,r.pages);t.agentWarnings=Ze(i,_y(t.dir)).warnings,h(e,t,i)},x=e=>{if(!o.has(e)){o.add(e);for(let t of[`render.png`,`render.json`,`geometry.json`])d.default.rmSync(p.default.join(c(e),t),{force:!0})}},S=(t,n)=>Ge(n)&&W(e.root,`whiteboard`,t)!==null,C=e=>Je(m(e)?.pages??[]);return{scene:(e,t=Ve)=>g(e,t)?.scene??null,pages:e=>m(e)?.pages??[],livePages:C,pagesWarnings(e){let t=f(e);return t?[.../* @__PURE__ */ new Set([...t.problem?[t.problem]:[],...t.agentWarnings,...m(e).warnings])]:[]},pagesChanged:b,applyPages(e,t){b(e);let n=f(e),r=m(e);if(!n||!r)return!1;let i=$e(r.pages,t);return i?(h(e,n,i),!0):!1},elementPage(e,t){for(let n of C(e))if((g(e,n.id)?.scene)?.elements.some(e=>e.id===t&&!e.isDeleted))return n.id;return null},conflicts:(e,t=Ve)=>n.get(u(e,t))?.conflicts??[],duplicates:(e,t=Ve)=>n.get(u(e,t))?.duplicates??[],problem:(e,t=Ve)=>n.get(u(e,t))?.problem??null,applyBrowser(t,n,r={}){let i=r.page??`main`,a=g(t,i);if(!a)return;let o=cR(a.scene.elements,n,r),s=a.scene.files,c=Object.fromEntries(Object.entries(r.files??{}).filter(([e])=>!(e in s)));if(o.changed.length===0&&Object.keys(c).length===0)return;a.scene={...a.scene,elements:o.elements,files:{...s,...c}};let l=new Set(o.changed);e.onUpdate(t,{page:i,elements:o.elements.filter(e=>l.has(e.id)),...Object.keys(c).length?{files:c}:{}}),v(a)},fileChanged:y,geometry:(e,t=Ve)=>i.get(u(e,t))??null,reportGeometry(e,t,n=Ve){return!hR(t)||!S(e,n)?!1:(i.set(u(e,n),t),U(p.default.join(l(e,n),`geometry.json`),t),x(e),!0)},render:(e,t=Ve)=>a.get(u(e,t))??null,renderPathOf:(e,t=Ve)=>p.default.join(l(e,t),`render.png`),reportRender(e,t,n,r=Ve){if(!Number.isFinite(n)||!S(e,r))return!1;d.default.mkdirSync(l(e,r),{recursive:!0}),gR(p.default.join(l(e,r),`render.png`),t);let i={sceneVersion:n,at:(/* @__PURE__ */ new Date()).toISOString()};return a.set(u(e,r),i),U(p.default.join(l(e,r),`render.json`),i),x(e),!0},sync(e){b(e);for(let t of m(e)?.pages??[])y(e,t.id)},flush(e){b(e);for(let t of n.values())t.id===e&&(pR(t.file)!==t.written&&y(e,t.page),_(t))},close(){for(let e of n.values())_(e);n.clear(),r.clear()}}}const vR={claude:`Claude Code`,"claude-code":`Claude Code`,cowork:`Claude Cowork`,codex:`Codex`,cursor:`Cursor`,"cursor-cli":`Cursor`,gemini:`Gemini CLI`,"gemini-cli":`Gemini CLI`,grok:`Grok`,"grok-cli":`Grok`,"github-copilot":`GitHub Copilot`,"github-copilot-cli":`GitHub Copilot`,kilo:`Kilo Code`,omp:`OMP`,"oh-my-pi":`OMP`,opencode:`OpenCode`,"qwen-code":`Qwen Code`,antigravity:`Antigravity`,augment:`Augment`,"augment-cli":`Augment`,goose:`Goose`,amp:`Amp`,cline:`Cline`,roo:`Roo Code`,devin:`Devin`,replit:`Replit`,v0:`v0`};[...new Set(Object.values(vR))];const yR=[[`omp`,e=>!!e.OMPCODE],[`grok`,e=>!!(e.GROK_AGENT||e.GROK_SESSION_ID)],[`cowork`,e=>!!e.CLAUDE_CODE_IS_COWORK],[`kilo`,e=>!!e.KILO],[`codex`,e=>!!(e.CODEX_THREAD_ID||e.CODEX_SANDBOX||e.CODEX_CI)],[`cursor`,e=>!!(e.CURSOR_AGENT||e.CURSOR_TRACE_ID)],[`gemini`,e=>!!e.GEMINI_CLI],[`github-copilot`,e=>!!e.COPILOT_CLI],[`opencode`,e=>e.OPENCODE===`1`||!!e.OPENCODE_CLIENT],[`qwen-code`,e=>!!e.QWEN_CODE],[`antigravity`,e=>!!e.ANTIGRAVITY_AGENT],[`augment`,e=>!!e.AUGMENT_AGENT],[`cline`,e=>!!e.CLINE_ACTIVE],[`roo`,e=>!!e.ROO_ACTIVE],[`claude`,e=>!!(e.CLAUDECODE||e.CLAUDE_CODE)]],bR=e=>e?.trim().split(/[@_]/)[0]?.toLowerCase()||void 0;function xR(e){if(e.CLAUDE_CODE_IS_COWORK)return vR.cowork;let t=bR(e.AI_AGENT);if(t)return vR[t]??t;let n=yR.find(([,t])=>t(e))?.[0];if(n)return vR[n];let r=bR(e.AGENT);if(r&&!/^(?:1|true|yes)$/.test(r))return vR[r]??r}function SR(e,t){try{return(0,l.execFileSync)(`git`,[`config`,t],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:2e3}).trim()||void 0}catch{return}}function CR(e){let t=SR(e,`user.name`);if(!t)return;let n=SR(e,`user.email`);return n?{name:t,avatar:zN(n)}:{name:t}}function wR({stateDir:e,projectDir:t,cloud:n}){let r;return{human:()=>{let e=n?bt(n.credentialsFile,n.origin)?.login:void 0;return e?{name:e,avatar:RN(e)}:(r??={person:CR(t)},r.person)},agent:t=>{try{return xR(JSON.parse(d.default.readFileSync(p.default.join(e,t,`agent`),`utf8`)))}catch{return}}}}function TR(){return{artboardRuntime:AI(),dynamicBlocks:nL({maxErrors:20}),shotRuns:nL({maxErrors:20},{accepts:BD,missingWarnings:!1,urls:GD}),slidesReports:/* @__PURE__ */ new Map}}const ER=(e,t,n,r)=>({documentState:(n,r)=>NI(t,e,n,r),verdictPreparing:jI(n,e),deckDeps:RL(r)});function DR({broadcast:e,clients:t,direct:n,options:r,port:i,recordingChanged:a,refreshState:o,relayViewers:s,relayWatched:c,root:l,stateDir:u,token:d,viewed:f,writeState:m}){let h=_R({root:l,stateDir:u,onPages:(t,n)=>{e({type:`whiteboard-pages`,artifact:`whiteboard/${t}`,pages:n})},onUpdate:(t,n)=>{e({type:`whiteboard-update`,artifact:`whiteboard/${t}`,...n}),_.sceneChanged(t)}}),g=wR({stateDir:u,projectDir:p.default.resolve(l,`../..`),cloud:r.cloud}),_=RA({root:l,stateDir:u,names:g,broadcast:e,board:e=>{let t=h.livePages(e);return{find(t){let n=h.elementPage(e,t),r=n?h.scene(e,n)?.elements.find(e=>e.id===t&&!e.isDeleted):void 0;return n&&r?{element:r,page:n}:null},livePage:e=>t.some(t=>t.id===e)}}}),v=yp({stateDir:u}),y=(t,n)=>{let r=G(t);r&&(o(r,n),e({type:`change`,artifact:t,files:[]}))},b=KL({stateDir:u,onVoiced:y}),x=$L({voice:b,renderUrl:e=>`http://127.0.0.1:${i()}/${e}/render?key=${d}`,onChange:y}),S=mm({root:l,stateDir:u,names:g,broadcast:e}),C=FT({root:l,stateDir:u,names:g,broadcast:e,model:e=>{let t=W(l,`storyboard`,e);return t?tO(t,e).storyboard:null}}),w=IL(u),T=sw({root:l,stateDir:u,names:g,broadcast:e,outline:e=>{let t=W(l,`slides`,e);if(!t)return null;let n=Gb(t,e);return n.complete&&n.warnings.length===0?n.outline:null}}),E=iR({stateDir:u,onChange:e=>{let t={type:`artboard`,id:e},n=W(l,t.type,e);if(!n)return;let r=o(t,n);D.boardsChanged(e),a(t,r)}}),D=oc({root:l,stateDir:u,broadcast:e,names:g,evidenceHash:E.evidenceHash}),O=xa({root:l,stateDir:u,shiftPins:D.shiftPins}),k=Wk({root:l,broadcast:e,rowState:(e,t)=>{let n=W(l,`artboard`,e)&&D.groups(e).find(e=>e.id===t);return n&&n.kind===`verify`?n.verdict:`missing`}}),A=fL(u),j=dw(u),ee=Xu({root:l,stateDir:u,broadcast:e,names:g}),M=qI({root:l,stateDir:u,timing:r.documentTiming,openSession:r.openDocument,readDocument:r.readDocument,onSessionChange:(e,t)=>t?f.viewerJoined(`document/${e}`):f.viewerLeft(`document/${e}`),onSessionLost:e=>{let r=`document/${e}`;console.error(JSON.stringify({type:`document-session-lost`,root:l,document:e}));for(let e of t)e.destroy();n.drop(r),c().has(r)&&M.open(e).catch(()=>void 0)},viewed:e=>t.size>0||c().has(`document/${e}`)||n.viewing(`document/${e}`)||[...s()].some(t=>t.key===`document/${e}`),broadcast:e,names:g,onWarningsChange:t=>{let n=W(l,`document`,t);n&&(m({type:`document`,id:t},n),e({type:`change`,artifact:`document/${t}`,files:[]}))},onRefsChange:(t,n)=>{f.refresh(`document/${t}`);for(let t of n){let n=W(l,t.type,t.id);n&&(m(t,n),e({type:`change`,artifact:`${t.type}/${t.id}`,files:[]}))}},log:e=>console.info(JSON.stringify({type:`document-log`,line:e}))});return{arranges:O,boardComments:D,documents:M,exportRunner:x,names:g,previewComments:ee,previewProxies:A,recordings:E,reportComments:S,reportHistory:w,slidesComments:T,slidesSheets:j,sourceRunner:v,storyboardComments:C,verify:k,voiceRunner:b,whiteboardComments:_,whiteboards:h}}const OR=e=>e.split(p.default.sep).join(`/`),kR=e=>e===`.state`||e.startsWith(`.state/`);function AR(e,t=e,n=/* @__PURE__ */ new Map){let r;try{r=d.default.readdirSync(t,{withFileTypes:!0})}catch{return n}for(let i of r){let r=p.default.join(t,i.name),a=OR(p.default.relative(e,r));if(!kR(a)){if(i.isDirectory())AR(e,r,n);else try{n.set(a,d.default.statSync(r).mtimeMs)}catch{}}}return n}function jR(e,t,n=400){let r=AR(e),i=setInterval(()=>{let n=AR(e),i=[];for(let[e,t]of n)r.get(e)!==t&&i.push(e);for(let e of r.keys())n.has(e)||i.push(e);r=n,i.length>0&&t(i)},n);return{close:()=>clearInterval(i)}}function MR(e,t){try{let n=d.default.watch(e,{recursive:!0},(e,n)=>{n&&t([OR(n.toString())])});return n.on(`error`,()=>{}),{close:()=>n.close()}}catch{return null}}const NR=`project`,PR=`project-poll`,FR=e=>e===`.state`||e.startsWith(`.state/`);function IR({root:e,debounceMs:t=120,pollMs:n=2e3,onFiles:r,related:i=()=>[]}){let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set,u,d=!1,f=e=>{if(!d){for(let t of e)FR(t)||l.add(t);l.size!==0&&(clearTimeout(u),u=setTimeout(()=>{let e=[...l];l=/* @__PURE__ */ new Set,r(e);for(let e of[...s.keys()])v(e)},t))}},m=t=>{let r=p.default.join(e,...t.split(`/`)),i=e=>f(e.map(e=>`${t}/${e}`)),a=MR(r,i),o=jR(r,e=>{a??=MR(r,i),i(e)},n);return{close:()=>{a?.close(),o.close()}}},h=t=>t===`project-poll`?jR(e,f,n):t===`project`?MR(e,f)??jR(e,f,n):m(t),g=e=>{let t=(o.get(e)??0)+1;o.set(e,t),t===1&&c.set(e,h(e))},_=e=>{let t=(o.get(e)??0)-1;t>0?o.set(e,t):(o.delete(e),c.get(e)?.close(),c.delete(e))},v=e=>{if(d)return;let t=s.get(e)??/* @__PURE__ */ new Set,n=new Set(i(e).filter(t=>t!==e));for(let e of n)t.has(e)||g(e);for(let e of t)n.has(e)||_(e);s.set(e,n)};return{viewerJoined:e=>{if(d)return;let t=(a.get(e)??0)+1;a.set(e,t),g(e),t===1&&e!==`project`&&e!==`project-poll`&&v(e)},viewerLeft:e=>{if(d||!a.has(e))return;let t=a.get(e)-1;if(t>0)a.set(e,t);else{a.delete(e);for(let t of s.get(e)??[])_(t);s.delete(e)}_(e)},refresh:e=>{s.has(e)&&v(e)},watching:()=>[...c.keys()].sort(),close:()=>{d=!0,clearTimeout(u);for(let e of c.values())e.close();c.clear(),a.clear(),o.clear(),s.clear()}}}function LR(e){return{agentStatus:pI(e),...TR(),contentToken:F(),ranVersions:/* @__PURE__ */ new Map,runtimeSession:F(),runtimeWarnings:/* @__PURE__ */ new Map,stateWritten:!1}}function RR(e,t,n=[]){let r=oj[t.type],i=r.read(e,t.id);return{...i,warnings:[...i.warnings,...r.runtimeWarning?n.map(r.runtimeWarning):n]}}function zR(e){if(`title`in e&&typeof e.title==`string`&&e.title.trim())return e.title.trim();if(`canvas`in e){let t=e.canvas?.title;if(typeof t==`string`&&t.trim())return t.trim()}return`Untitled artifact`}function BR(e){let t=p.default.resolve(e.root),n=p.default.resolve(e.viewerDir),r=e.runtimeDir?p.default.resolve(e.runtimeDir):null,i=p.default.join(t,`.state`);d.default.mkdirSync(i,{recursive:!0,mode:448}),d.default.writeFileSync(p.default.join(i,`.gitignore`),`*
979
- `),e.configFile&&Jr(e.configFile);let a=p.default.join(i,`.last-port`),o=p.default.join(i,`.last-token`),s=e.mount,c=s?.token??(te(o)||F());s||d.default.writeFileSync(o,`${c}\n`,{mode:384});let l=e.memory??LR(t),{contentToken:u,agentStatus:f,runtimeWarnings:m,slidesReports:h}=l,g=on(e.host),_=e=>g||e!==null&&I(e,c),v=(e,t)=>g?e.headers.origin===void 0:t!==null&&I(t,c),y=(e,t)=>g||t!==null&&I(t,c)||I(L(e.headers.cookie)[le.cookieName]??``,c),b=e=>{let t=e.headers.origin,n=e.headers.host??``;return t===`http://${n}`||t===`https://${n}`},x=Dy(t),{backlinksOf:S,...C}=My({root:t,refLookup:x,documents:()=>re.documents}),w=`/c/${u}/`,T=/* @__PURE__ */ new Set,E=OI(i,(e,n)=>W(t,e,n)!==null);E.clearAll();let D=[],O=e.agentDirectory??nI(),k=e.memory?()=>void 0:O.register(f);D.push((e,t,n)=>{uI(n).length>0&&f.touched(`${e.type}/${e.id}`)&&ae.publishAgentStatus()});let A=[],j=Date.now(),ee=()=>{le.lastActivity=Date.now(),A.forEach(e=>e())},M=()=>le.boardPort?cj.origins(e.urlHost,le.boardPort):[],N=[],P=[],R=IR({root:t,debounceMs:e.debounceMs,pollMs:e.watchPollMs,onFiles:e=>VM(le,e),related:e=>e.startsWith(`document/`)?re.documents.refs(e.slice(9)).map(e=>`${lh(e)}/${uh(e)}`):[]}),ne=VN({version:s?.version??e.relay?.version??``,daemon:()=>e.agentDaemon?.available()??!1,handle:(t,n,r)=>e.agentDaemon&&Hj(n)?e.agentDaemon.request(t,n,g):kN(le,t,n,r,`http://127.0.0.1:${le.port}`),onActivity:()=>ee(),onOpen:e=>R.viewerJoined(e),onClose:(e,t)=>{DN(le,e),R.viewerLeft(t)}}),z=e=>{let t=lc(JSON.stringify(e));for(let e of T)e.write(t);le.relay?.emit(e.artifact,e),ne.emit(e.artifact,e),ae.afterBroadcast(e)},B=BN(e.fetch),re=DR({broadcast:z,clients:T,direct:ne,options:e,root:t,stateDir:i,token:c,viewed:R,port:()=>le.port,relayViewers:()=>le.relayViewers.values(),relayWatched:()=>le.relayWatched,refreshState:(e,t)=>ie.refreshState(e,t),writeState:(e,t)=>ie.writeState(e,t),recordingChanged:(e,t)=>{let n=`${e.type}/${e.id}`;z({type:`change`,artifact:n,files:[]}),se.autoPublisher?.changed(n),se.cloud?.changed(n),D.forEach(n=>n(e,t,[]))}}),ie=FN({backlinksOf:S,contentPrefix:w,ctx:()=>le,names:re.names,recordings:re.recordings,runtimeSession:l.runtimeSession,runtimeWarnings:m,stateDir:i}),ae=PN({agentDaemon:e.agentDaemon,agentDirectory:O,agentStatus:f,broadcast:z,clients:T,ctx:()=>le,root:t}),oe=setInterval(()=>{let e=Ts(i);re.boardComments.refreshListening(e),re.documents.refreshListening(e),re.documents.sweepIdle(Date.now()),f.expire(Date.now())&&ae.publishAgentStatus(),ae.publishThreadActivity()},3e3);oe.unref();let se=tI({broadcast:z,clients:T,options:e,root:t,stateDir:i,port:()=>le.port,inspect:e=>WN(le,x,e)}),ce={changed:e=>{},written:(e,t)=>{}},le={options:e,memory:l,root:t,viewerDir:n,runtimeDir:r,stateDir:i,portFile:a,agentReview:Dl(i),mount:s,token:c,contentToken:u,contentPrefix:w,loopback:g,policy:cn({host:e.host,urlHost:e.urlHost,ports:[],cloudOrigin:e.cloud?.origin}),port:0,boardPort:0,cookieName:``,startedAt:j,lastActivity:j,relay:null,relayViewers:/* @__PURE__ */ new Map,relayWatched:/* @__PURE__ */ new Set,viewed:R,keyOk:_,agentOk:v,isAuthorized:y,sameOrigin:b,touch:ee,boardOrigins:M,runtimeWarnings:m,ranVersions:l.ranVersions,artboardRuntime:l.artboardRuntime,dynamicBlocks:l.dynamicBlocks,shotRuns:l.shotRuns,...C,clients:T,selections:E,changeListeners:D,agentStatus:f,agentDirectory:O,leaveAgentDirectory:()=>{k(),ae.leaveDirectoryUpdates()},threadActivity:ae.threadActivity,deliverThreads:ae.deliverThreads,threadActivityFrames:ae.threadActivityFrames,agentStatusFrame:ae.agentStatusFrame,publishAgentStatus:ae.publishAgentStatus,activityListeners:A,relayListeners:N,reviewListeners:P,direct:ne,slidesReports:h,broadcast:z,avatars:B,...re,...ie,listeningTimer:oe,...se,...ER(t,re.documents,ie.readArtifact,e=>ce.changed(e)),deckFiles:ce};return le}const VR=e=>p.default.basename(p.default.dirname(p.default.dirname(e.root)));function HR(e,t,n,r,i=`main`){let{root:a,runtimeDir:o,options:s}=e;if(n.startsWith(`symbols/`)){let r=lj.symbolRequest(n.slice(8));if(!r){z(t,404,`Not found`);return}lj.renderSymbol(r.name,r.size,{cacheDir:p.default.join(e.stateDir,`symbols`)}).then(e=>{e?ie(t,e,{"Cache-Control":`public, max-age=86400`}):z(t,404,`Not found`)}).catch(e=>z(t,500,e.message));return}if(n.startsWith(`runtime/`)){if(!o){z(t,404,`Not found`);return}let e=tt(o,n.slice(8));if(!e){z(t,403,`Forbidden`);return}d.default.stat(e,(n,i)=>{let a=n?null:`"${i.size.toString(36)}-${Math.trunc(i.mtimeMs).toString(36)}"`,o={"Access-Control-Allow-Origin":`*`,"Cache-Control":`no-cache`,...a?{ETag:a}:{}};a&&r[`if-none-match`]===a?(t.writeHead(304,o),t.end()):ie(t,e,o)});return}let[c=``,l=``,...u]=n.split(`/`),f=W(a,c,l);if(!f){z(t,404,`Not found`);return}let m=G(`${c}/${l}`),h=u.join(`/`);if(!tt(f,h)){z(t,403,`Forbidden`);return}let g=oj[m.type],_=g.isPage(h),v=`${i===`board`?`/c/`:e.contentPrefix}runtime/`,y=e=>`${v}${e}`,b=g.ownPage?.(f,l,h,y,e);if(b!==void 0){b===null?z(t,404,`Not found`):z(t,200,b,{"Content-Type":`text/html; charset=utf-8`,"Content-Security-Policy":Lc(m.type,h,!1),"Access-Control-Allow-Origin":`*`});return}let x=_?g.compiledPage?.(f,h,`local`)??null:null,S=g.standIn?.(e,l,h)??g.resolveFile(f,h);if(!S&&x===null){z(t,404,`Not found`);return}let C={"Content-Security-Policy":i===`board`?cj.csp(s.urlHost,e.port,s.cloud?.origin):Lc(m.type,h,!1),...i===`board`?{}:{"Access-Control-Allow-Origin":`*`}};if(!_){ie(t,S,C,r.range);return}let w=(e,n)=>{e?z(t,404,`Not found`):z(t,200,rh(n,{uiRuntimeUrl:o?y(`ryugi-ui.js`):void 0,...g.pageRuntime?.(h,e=>o?y(e):void 0)}),{"Content-Type":`text/html; charset=utf-8`,...C})};x===null?d.default.readFile(S,`utf8`,w):w(null,x)}const UR={path:`/api/status`,raw:!0,auth:`key`,handle:(e,t,n)=>{B(t,200,{pid:process.pid,startedAt:n.startedAt,lastActivity:n.lastActivity,clients:n.clients.size,capabilities:{semanticOutputV1:!0,reviewReadsV1:!0,explicitAckV1:!0}})}},WR={path:`/robots.txt`,auth:`public`,handle:(e,t,n)=>{ie(t,p.default.join(n.viewerDir,`robots.txt`))}},GR={path:/^\/c\//,auth:`public`,handle:(e,t,n,{pathname:r})=>{r.startsWith(n.contentPrefix)?HR(n,t,r.slice(n.contentPrefix.length),e.headers):z(t,404,`Not found`)}},KR=e=>(t,n)=>{if(!ln(e.policy,t.headers.host)){z(n,403,`Forbidden host`);return}let r;try{r=decodeURIComponent(new URL(t.url??`/`,`http://board.local`).pathname)}catch{z(n,400,`Bad request`);return}try{let i=cj.route(t,r);if(i.kind===`robots`)z(n,200,`User-agent: *
980
- Disallow: /
981
- `);else if(i.kind===`runtime`)HR(e,n,i.rest,t.headers,`board`);else if(i.kind===`board`){let r=Si(e.root,`artboard`,i.address);!r||r.id===i.address?z(n,404,`Not found`):HR(e,n,`artboard/${r.id}/${i.rest}`,t.headers,`board`)}else z(n,404,`Not found`)}catch(e){n.headersSent?n.destroy():z(n,500,e.message)}},qR=/^\/api\/agent\/([^/]+)\/([^/]+)\/check$/;async function JR(e,t,n,r,i=null){let{root:a,stateDir:o,signatures:s}=t,c=G(`${n}/${r}`),l=c&&W(a,c.type,c.id);if(!c||!l){B(e,404,{error:`${n}/${r} not found in ${a}`});return}let u=oj[c.type].check??{},f=u.pages?.(t,c.id)??[];if(i!==null&&!f.includes(i)){B(e,404,{error:u.pages?`page ${i} is not on ${c.type}/${c.id}; pages: ${f.join(`, `)}`:`--page applies to whiteboards only`});return}let m=`${c.type}/${c.id}`;RM(t,c);let h=i===null?f:[i],g=await u.settle?.(t,c.id,l,h)===!0;await NM(c,l),RM(t,c);let _=t.writeState(c,l),v=JSON.parse(await d.default.promises.readFile(p.default.join(o,c.type,c.id,`warnings.json`),`utf8`)),y=i===null||!u.onlyPage?v:{...v,...u.onlyPage({warnings:v.warnings??[],pending:v.pending??[]},i,f)},b={pages:h,payload:_,state:y},x=Object.values(y.dynamic??{}),{required:S,observed:C}=u.evidence?.(t,c.id,b)??{required:x.length>0,observed:x.every(e=>e.ran===!0)};B(e,200,{...y,modules:wP(p.default.dirname(a),m),...g?{merging:!0}:{},...u.answer?.(t,c.id,b),evidence:{required:S,observed:C,fresh:!g&&s.get(m)===nr(l,c.type)}})}const YR={path:qR,methods:[`POST`],auth:`agent`,handle:(e,t,n,{match:r})=>JR(t,n,r[1],r[2],new URL(e.url??`/`,`http://x`).searchParams.get(`page`))},XR=e=>{if(typeof e!=`object`||!e)return!1;let t=e,n=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t;return(t.host===`claude`||t.host===`codex`||t.host===`antigravity`)&&n(t.session,200)&&n(t.event,64)&&typeof t.at==`number`&&Number.isFinite(t.at)&&(t.tool===void 0||n(t.tool,64))&&(t.paths===void 0||Array.isArray(t.paths)&&t.paths.length<=64&&t.paths.every(e=>n(e,4096)))},ZR={path:`/api/agent/event`,methods:[`POST`],auth:`agent`,handle:async(e,t,n)=>{let r=await yc(e);if(!XR(r)){B(t,400,{error:`not an agent event: need host, session, event, at and optional paths`});return}let i=n.agentStatus.turnArtifacts(r.host,r.session);n.agentDirectory.record(r),n.agentStatus.apply(r)&&n.publishAgentStatus();let a=/* @__PURE__ */ new Set([...i,...n.agentStatus.turnArtifacts(r.host,r.session)]);for(let e of a){let t=G(e);t&&RM(n,t)}z(t,204,``)}},QR=`ryugi.review/v1`,$R=e=>typeof e==`string`?e:void 0;function ez(e,t){let n=e.filters&&typeof e.filters==`object`?e.filters:void 0,r={artifact:t,agent:typeof e.agent==`string`&&e.agent.length>0&&e.agent.length<=100?e.agent:`Agent`,limit:e.limit===void 0?void 0:Number(e.limit),cursor:$R(e.cursor),snapshot:$R(e.snapshot),detail:e.detail===!0,all:e.all===!0,thread:$R(e.thread),fields:Array.isArray(e.fields)&&e.fields.every(e=>typeof e==`string`)?e.fields:void 0,...n?{filters:n}:{}};if(r.limit!==void 0&&(!Number.isInteger(r.limit)||r.limit<1||r.limit>100))throw new Sl(`E_ARGUMENT_INVALID`,`limit must be between 1 and 100.`);return r}function tz(e){let t=e.session;if(typeof t!=`object`||!t)return null;let{host:n,id:r}=t;return n!==`claude`&&n!==`codex`&&n!==`antigravity`||typeof r!=`string`?null:r.length>0&&r.length<=200?{host:n,id:r}:null}function nz(e,t,n,r){let i=tz(t);if(!i||!(n.detail||n.thread)||n.fields)return r;let a=r.items.flatMap(e=>typeof e.id==`string`?[e.id]:[]);return a.length&&e.deliverThreads(n.artifact,i.host,i.id,a),r}async function rz(e,t,n,r){return e.agentReview.threads({...r,threads:await t.threads(e,n,r.agent)})}async function iz(e,t,n,r,i){let a=t.sections?.[i],{items:o,actionable:s}=a?await a(e,n):{items:[],actionable:void 0};return e.agentReview.state({...r,section:i,items:o,actionable:s})}function az(e,t){let n=xl({...e,section:t});if(n)throw new Sl(`E_ARGUMENT_INVALID`,n)}async function oz(e,t,n,r,i,a){let o=uj.get(r);try{if(!(o.resolveDir?o.resolveDir(n.root,i):W(n.root,r,i)))throw new Sl(`E_ARTIFACT_NOT_FOUND`,`${r}/${i} not found.`,404);let s=await yc(e);if(!s||typeof s!=`object`||Array.isArray(s))throw new Sl(`E_ARGUMENT_INVALID`,`Expected a review request.`);let c=s,l=ez(c,`${r}/${i}`);if(c.op===`ack`){if(typeof c.receipt!=`string`)throw new Sl(`E_ARGUMENT_INVALID`,`An acknowledgement receipt is required.`);let{to:e,...r}=n.agentReview.ack({...l,receipt:c.receipt,kind:a===`changes`?`changes`:`threads`});a===`changes`&&e&&o.changes?.seen?.(n,i,e),n.reviewListeners.forEach(e=>e(l.artifact)),B(t,200,{schema:QR,artifact:l.artifact,receipt:c.receipt,...r});return}if(a===`changes`){if(!o.changes)throw new Sl(`E_ARGUMENT_INVALID`,`Changes apply to documents only.`);if(l.detail&&(l.limit!==void 0||l.cursor||l.fields))throw new Sl(`E_ARGUMENT_INVALID`,`A complete diff cannot use pagination or fields.`);let e=await o.changes.load(n,i),r=await n.agentReview.changes({...l,load:e});B(t,200,{schema:QR,artifact:l.artifact,...r});return}let u=c.op===`read`?`threads`:$R(c.section);if(c.op!==`list`&&c.op!==`read`)throw new Sl(`E_ARGUMENT_INVALID`,`Expected list, read or ack.`);if(c.op===`read`&&!l.thread)throw new Sl(`E_ARGUMENT_INVALID`,`A thread ID is required.`);if(c.sections!==void 0){if(c.op!==`list`||!Array.isArray(c.sections)||!c.sections.every(e=>typeof e==`string`))throw new Sl(`E_ARGUMENT_INVALID`,`sections requires a list of collection names and op=list.`);let e=bl({...l,section:u,sections:c.sections},l.artifact);if(e)throw new Sl(`E_ARGUMENT_INVALID`,e);let r={};for(let e of c.sections)r[e]=e===`threads`?nz(n,c,l,await rz(n,o,i,l)):await iz(n,o,i,l,e);B(t,200,{schema:QR,artifact:l.artifact,sections:r});return}if(az(l,u),u===`threads`)B(t,200,{schema:QR,artifact:l.artifact,section:u,...nz(n,c,l,await rz(n,o,i,l))});else if(u===`asks`||u===`groups`||u===`rounds`)B(t,200,{schema:QR,artifact:l.artifact,section:u,...await iz(n,o,i,l,u)});else{let e=await rz(n,o,i,{...l,limit:1}),r=await iz(n,o,i,l,`asks`),a=await iz(n,o,i,l,`groups`),s=await iz(n,o,i,l,`rounds`);B(t,200,{schema:QR,artifact:l.artifact,summary:{threads:e.page.total,waitingOnAgent:e.summary?.waitingOnAgent??0,asks:r.summary,groups:a.summary,rounds:s.summary}})}}catch(e){let n=e instanceof Sl;B(t,n?e.status:500,{schema:QR,code:n?e.code:`E_REVIEW_FAILED`,error:e instanceof Error?e.message:String(e)})}}const sz={path:RegExp(`^/api/agent/v1/(${[...uj.keys()].join(`|`)})/([^/]+)/(review|changes)$`),methods:[`POST`],auth:`agent`,handle:(e,t,n,{match:r})=>oz(e,t,n,r[1],r[2],r[3])},cz=`var(--ink)`,lz=/^(#[0-9a-f]{3,8}|[a-z]{3,20})$/i,uz=/* @__PURE__ */ new Set([`#000`,`#000000`,`#1e1e1e`,`#222`,`#222222`,`#333`,`#333333`,`black`]),dz=e=>e.replaceAll(/[&<>"']/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&apos;`})[e]),fz=(e,t=0)=>typeof e==`number`&&Number.isFinite(e)&&Math.abs(e)<=1e7?e:t,pz=(e,t,n=!1)=>typeof e!=`string`||!lz.test(e)?t:e===`transparent`?`none`:n&&uz.has(e.toLowerCase())?cz:e,mz=e=>Array.isArray(e.points)?e.points.filter(e=>Array.isArray(e)).map(([e,t])=>[fz(e),fz(t)]):[];function hz(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e){let e=fz(a.x),o=fz(a.y),s=[[0,0],[fz(a.width),fz(a.height)],...mz(a)];for(let[a,c]of s)t=Math.min(t,e+a),n=Math.min(n,o+c),r=Math.max(r,e+a),i=Math.max(i,o+c)}return Number.isFinite(t)?{minX:t,minY:n,maxX:r,maxY:i}:null}const gz=e=>Math.round(e*10)/10,_z=e=>[...e].reduce((e,t)=>e+(t.codePointAt(0)>=11904?1:.55),0);function vz(e,t,n,r,i){let a=t.step*.5;return e.map((e,o)=>{if(!e.trim())return``;let s=Math.min(t.width,Math.max(a,n(e))),c=r===`center`?t.x+(t.width-s)/2:r===`right`?t.x+t.width-s:t.x,l=t.y+t.step*o+(t.step-a)/2;return`<rect x="${gz(c)}" y="${gz(l)}" width="${gz(s)}" height="${gz(a)}" rx="${gz(a/2)}" fill="${i}" fill-opacity=".28"/>`}).join(``)}function yz(e,t){if(e.length<2)return``;let[n,r]=e.at(-2),[i,a]=e.at(-1),o=Math.atan2(a-r,i-n),s=7.5,c=Math.PI/6.5;return`<polyline points="${gz(i-s*Math.cos(o-c))},${gz(a-s*Math.sin(o-c))} ${i},${a} ${gz(i-s*Math.cos(o+c))},${gz(a-s*Math.sin(o+c))}" stroke="${t}" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>`}function bz(e,t,n){let r=fz(e.x),i=fz(e.y),a=fz(e.width)*n,o=fz(e.height)*n,s=pz(e.strokeColor,cz,!0),c=`stroke="${s}" stroke-width="1.5" fill="${pz(e.backgroundColor,`none`)}"`,[l,u]=t(r,i);switch(e.type){case`rectangle`:return`<rect x="${l}" y="${u}" width="${a}" height="${o}" rx="6" ${c}/>`;case`frame`:return`<rect x="${l}" y="${u}" width="${a}" height="${o}" rx="8" stroke="var(--border-strong)" stroke-width="1.1" stroke-dasharray="5 4" fill="none"/>`;case`ellipse`:return`<ellipse cx="${l+a/2}" cy="${u+o/2}" rx="${a/2}" ry="${o/2}" ${c}/>`;case`diamond`:return`<polygon points="${l+a/2},${u} ${l+a},${u+o/2} ${l+a/2},${u+o} ${l},${u+o/2}" ${c}/>`;case`arrow`:case`line`:case`freedraw`:{let n=mz(e).map(([e,n])=>t(r+e,i+n));return n.length?`<polyline points="${n.map(e=>e.join(`,`)).join(` `)}" stroke="${s}" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>${e.type===`arrow`?yz(n,s):``}`:``}case`richtext`:{let t=`<rect x="${l}" y="${u}" width="${a}" height="${o}" rx="6" stroke="${pz(e.strokeColor,`var(--wb-sticky-edge)`,!0)}" stroke-width="1" fill="${pz(e.backgroundColor,`var(--wb-sticky)`)}" filter="url(#wb-lift)"/>`,r=Math.max(4,Math.min(16,14*n)),i=8*n,s=r*1.35,c=Math.max(1,Math.floor((o-i*2)/s));return t+vz((e.text??``).split(`
982
- `).slice(0,c),{x:l+i,y:u+i,width:a-i*2,step:s},e=>_z(e)*r,`left`,`var(--wb-sticky-ink)`)}case`svg`:return e.svg?`<image href="data:image/svg+xml,${encodeURIComponent(e.svg)}" x="${l}" y="${u}" width="${a}" height="${o}"/>`:`<rect x="${l}" y="${u}" width="${a}" height="${o}" rx="4" stroke="var(--border-strong)" fill="none"/>`;case`text`:{let t=(e.text??``).split(`
983
- `).slice(0,40),r=Math.max(.55,...t.map(_z));return vz(t,{x:l,y:u,width:a,step:(o||12*n)/t.length},e=>_z(e)/r*a,e.textAlign,s)}default:return``}}function xz(e,t){let n=hz(t),r=`<defs><pattern id="wb-grid" width="24" height="24" patternUnits="userSpaceOnUse"><path d="M 24 0 L 0 0 0 24" fill="none" stroke="var(--wb-grid)" stroke-width="0.7"/></pattern><filter id="wb-lift" x="-18%" y="-18%" width="136%" height="145%"><feDropShadow dx="0" dy="3" stdDeviation="6" flood-color="var(--shadow)" flood-opacity=".1"/></filter></defs><rect x="0" y="0" width="600" height="360" fill="var(--desk-wb)"/><rect x="0" y="0" width="600" height="360" fill="url(#wb-grid)"/>`;if(!n)return`${r}<rect x="56" y="48" width="488" height="264" rx="10" fill="none" stroke="var(--border-strong)" stroke-width="1.2" stroke-dasharray="5 4"/><text x="300" y="186" font-size="22" fill="var(--ink)" font-weight="600" text-anchor="middle">${dz(e)}</text>`;let i=Math.min(536/Math.max(1,n.maxX-n.minX),296/Math.max(1,n.maxY-n.minY),2),a=(600-(n.maxX-n.minX)*i)/2,o=(360-(n.maxY-n.minY)*i)/2,s=(e,t)=>[Math.round((e-n.minX)*i+a),Math.round((t-n.minY)*i+o)];return r+t.map(e=>bz(e,s,i)).join(``)}const Z=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:{},Sz=e=>typeof e==`string`?e:``,Cz=e=>Array.isArray(e)?e.slice(0,200).map(Z):[],wz=e=>e.replaceAll(/[&<>"']/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&apos;`})[e]),Tz=e=>typeof e==`number`&&Number.isFinite(e)&&Math.abs(e)<=1e9,Q=(e,t,n,r,i=`var(--paper)`,a=`none`,o=0)=>`<rect x="${e}" y="${t}" width="${n}" height="${r}"${o>0?` rx="${o}"`:``} fill="${i}" stroke="${a}"/>`,Ez=(e,t,n,r=9,i=`var(--ink)`,a=400,o=``)=>`<text x="${e}" y="${t}" font-size="${r}" fill="${i}" font-weight="${a}"${o}>${wz(n)}</text>`,Dz=(e,t)=>t*(e.codePointAt(0)>=11904?1:.55),Oz=(e,t)=>{let n=0;for(let r of e)n+=Dz(r,t);return n};function kz(e,t,n,r){let i=[],a=e.slice(0,4e3).split(`
984
- `);for(let e of a){let a=e.match(/[\u2E80-\uFFFF]|[^\s\u2E80-\uFFFF]+\s?|\s/g)??[],o=``,s=0,c=()=>{i.push(o.trimEnd()),o=``,s=0};for(let e of a){let a=Oz(e,t);if(s+a<=n)o+=e,s+=a;else if(o&&a<=n){if(i.length===r-1)return i.push(`${o.trimEnd()}…`),i;c();let n=e.trimStart();o=n,s=Oz(n,t)}else for(let a of e){let e=Dz(a,t);if(s+e>n){if(i.length===r-1)return i.push(`${o.trimEnd()}…`),i;c()}o+=a,s+=e}}if(o||a.length===0){if(i.length===r)return i[r-1]=`${i[r-1].trimEnd()}…`,i;c()}if(i.length>=r)return i.slice(0,r)}return i}function Az(e){let t=[e],n=[];for(let e=0;t.length&&e<300;e++){let e=t.pop();typeof e.text==`string`?n.push(e.text.slice(0,4e3)):t.push(...Cz(e.children).reverse())}return n.join(``).slice(0,4e3)}const jz=(e,t=8,n=14,r=`.11`)=>`<filter id="${e}" x="-18%" y="-18%" width="136%" height="145%"><feDropShadow dx="0" dy="${t}" stdDeviation="${n}" flood-color="var(--shadow)" flood-opacity="${r}"/></filter>`;function Mz(e,t){let n=Cz(Z(Z(t.state).root).children),r=[`<rect x="64" y="20" width="472" height="520" rx="8" fill="var(--paper)" stroke="var(--edge)" filter="url(#doc-lift)"/>`,`<rect x="96" y="48" width="28" height="3" rx="1.5" fill="var(--accent)"/>`],i=76,a=(e,t,n,a=0,o=400,s=`var(--ink)`)=>{for(let c of kz(e,t,408-a,n))r.push(Ez(96+a,i,c,t,s,o)),i+=t*1.5},o=(e,t,n,r,i,a=`.34`)=>$(e,t-r*.65,Math.min(i,Oz(n,r)),r*.55,`var(--muted)`,a),s=(e,t,n,a=0)=>{for(let s of kz(e,t,408-a,n))r.push(o(96+a,i,s,t,408-a)),i+=t*1.5};n[0]?.type!==`heading`&&(a(e,18,2,0,650),i+=6);for(let e of n.slice(0,18)){if(i>332)break;let t=Sz(e.type);if(t===`heading`){let t=e.tag===`h1`?18:11.5;i+=e.tag===`h1`?0:8,a(Az(e),t,2,0,650),i+=6}else if(t===`table`){let t=Cz(e.children).slice(0,5),n=408/Math.max(1,...t.map(e=>Cz(e.children).length));t.forEach((e,t)=>{Cz(e.children).forEach((e,a)=>{r.push(Q(96+a*n,i-8+t*22,n,22,t===0?`var(--block)`:`var(--paper)`,`var(--border)`)),r.push(o(102+a*n,i+6+t*22,kz(Az(e),7.5,n-12,1)[0]??``,7.5,n-12,t===0?`.5`:`.34`))})}),i+=t.length*22+10}else if(t===`list`)Cz(e.children).slice(0,4).forEach(e=>{r.push(`<circle cx="99" cy="${i-3}" r="1.6" fill="var(--muted)"/>`),s(Az(e),9,2,13)}),i+=8;else if(t===`alert-quote`){let t=kz(Cz(Z(Z(e.content).root).children).map(Az).join(` `),9,382,3);r.push(Q(96,i-8,408,t.length*14+16,`var(--alert)`,`none`,4),Q(96,i-8,3,t.length*14+16,`var(--alert-bar)`,`none`,1.5)),t.forEach(e=>{r.push(o(110,i+7,e,9,382)),i+=14}),i+=20}else if(t===`code-block`){let t=kz(Sz(e.code),8,386,4);r.push(Q(96,i-8,408,t.length*12+18,`var(--block)`,`var(--border)`,4)),t.forEach(e=>{r.push(o(106,i+6,e,8,386)),i+=12}),i+=20}else t===`paragraph`||t===`quote`?(s(Az(e),9,3),i+=7):(r.push(Q(96,i-8,408,28,`var(--block)`,`none`,4),Ez(106,i+10,t.toUpperCase().slice(0,30),8,`var(--muted)`)),i+=38)}return`${Q(0,0,600,360,`var(--desk)`)}<defs>${jz(`doc-lift`,8,14,`.11`)}</defs><g transform="rotate(-2 300 260)"><g transform="translate(0 8)">${r.join(``)}</g></g>`}function Nz(e){let t=Z(e);return[t.x,t.y,t.w,t.h].every(Tz)&&t.w>0&&t.h>0?t:null}function Pz(e,t){let n={};for(let[r,i]of Object.entries(Z(e.boards)).slice(0,2e3)){let e=Nz(i);e&&Z(i).page===t&&(n[r]={x:e.x,y:e.y,w:e.w,h:e.h,page:t,file:``})}let r={};for(let[n,i]of Object.entries(Z(e.notes)).slice(0,200)){let e=Z(i);e.kind===`condition`&&e.page===t&&Tz(e.x)&&Tz(e.y)&&(r[n]={kind:`condition`,page:t,x:e.x,y:e.y,text:Sz(e.text).slice(0,200)})}let i={};for(let[t,n]of Object.entries(Z(e.edges)).slice(0,200)){let e=Z(n);typeof e.from==`string`&&typeof e.to==`string`&&(i[t]={from:e.from,to:e.to})}return{version:1,pages:[{id:t,name:t}],boards:n,notes:r,edges:i}}const $=(e,t,n,r,i=`var(--muted)`,a=`.34`)=>n>0&&r>0?`<rect x="${e}" y="${t}" width="${n}" height="${r}" rx="${r/2}" fill="${i}" fill-opacity="${a}"/>`:``;function Fz(e){let t=Z(e.canvas),n=Sz(t.activePage)||Sz(Cz(t.pages)[0]?.id),r=Z(Z(Z(e.layout).pages)[n]),i=Object.values(Z(t.boards)).slice(0,2e3).map(Z).filter(e=>e.page===n&&Nz(e)),a=Z(r.notes),o=Z(r.groups),s=Z(r.bounds),c=s.minX,l=s.minY,u=s.maxX,d=s.maxY;if(![c,l,u,d].every(Tz)||u<=c||d<=l){if(!i.length)return`${Q(0,0,600,360,`var(--bg)`)}<defs><pattern id="dots" width="16" height="16" patternUnits="userSpaceOnUse"><circle cx="1.5" cy="1.5" r=".9" fill="var(--dot)"/></pattern></defs>${Q(0,0,600,360,`url(#dots)`)}`;c=Math.min(...i.map(e=>e.x)),l=Math.min(...i.map(e=>e.y)),u=Math.max(...i.map(e=>e.x+e.w)),d=Math.max(...i.map(e=>e.y+e.h))}let f=Math.max(1,u-c),p=Math.max(1,d-l),m=Math.min(544/f,304/p),h=(600-f*m)/2-c*m,g=(360-p*m)/2-l*m,_=[];for(let[e,n]of Object.entries(o).slice(0,200)){let r=Nz(n);if(!r)continue;_.push(`<rect x="${r.x}" y="${r.y}" width="${r.w}" height="${r.h}" rx="${6/m}" fill="var(--paper)" fill-opacity=".35" stroke="var(--border-strong)" stroke-dasharray="${4/m} ${3/m}"/>`);let i=Sz(Z(Z(t.groups)[e]).title).trim();if(i&&r.w*m>50){let e=4.5/m,t=Math.min(r.w-24/m,Math.max(24/m,Oz(i,7/m)));_.push($(r.x+12/m,r.y+12/m,t,e,`var(--muted)`,`.36`))}}for(let e of yi(Pz(t,n),n)){let t=e.points.map(e=>`${e.x},${e.y}`).join(` `);_.push(`<polyline points="${t}" fill="none" stroke="var(--muted)" stroke-width="1.2" vector-effect="non-scaling-stroke"/>`);let n=e.points.at(-1);n&&_.push(`<circle cx="${n.x}" cy="${n.y}" r="${2.2/m}" fill="var(--muted)"/>`)}for(let e of i){let t=Nz(e),n=t.w*m,r=t.h*m,i=Math.min(5,Math.min(n,r)*.12)/m;if(_.push(`<rect x="${t.x}" y="${t.y}" width="${t.w}" height="${t.h}" rx="${i}" fill="var(--paper)" stroke="var(--border-strong)" filter="url(#ab-lift)"/>`),n>42&&r>34){let e=10/m,n=7/m,r=t.w-n*2;_.push(`<rect x="${t.x}" y="${t.y}" width="${t.w}" height="${e}" rx="${i}" fill="var(--paper-subtle)"/>`,`<line x1="${t.x}" y1="${t.y+e}" x2="${t.x+t.w}" y2="${t.y+e}" stroke="var(--border)" stroke-width=".7" vector-effect="non-scaling-stroke"/>`,`<rect x="${t.x+n}" y="${t.y+e+6/m}" width="${r*.48}" height="${4.5/m}" rx="${2/m}" fill="var(--border-strong)"/>`,`<rect x="${t.x+n}" y="${t.y+e+14/m}" width="${r}" height="${Math.max(8/m,(t.h-e-22/m)*.48)}" rx="${2.5/m}" fill="var(--block)"/>`)}let a=Sz(e.title).trim();if(a&&n>42){let e=3.5/m,n=Math.min(t.w*.72,Math.max(18/m,Oz(a,6/m)));_.push($(t.x,t.y-8/m,n,e,`var(--muted)`,`.34`))}}for(let[e,r]of Object.entries(Z(t.notes)).slice(0,200)){let t=Z(r),i=Nz(a[e]);if(t.page===n&&i){if(t.kind===`condition`){_.push(`<rect x="${i.x}" y="${i.y}" width="${i.w}" height="${i.h}" rx="${i.h/2}" fill="var(--paper)" stroke="var(--muted)"/>`);let e=Sz(t.text).trim();if(e&&i.w*m>26){let t=Math.min(i.h*.36,3.5/m),n=Math.min(i.w*.65,Math.max(12/m,Oz(e,5.5/m)));_.push($(i.x+(i.w-n)/2,i.y+(i.h-t)/2,n,t,`var(--muted)`,`.38`))}}else if(t.kind===`sticky`){let e=/^#[\da-f]{3}(?:[\da-f]{3})?$/i.test(Sz(t.color))?Sz(t.color):`var(--wb-sticky)`;_.push(`<rect x="${i.x}" y="${i.y}" width="${i.w}" height="${i.h}" rx="${4/m}" fill="${e}" stroke="var(--wb-sticky-edge)" filter="url(#ab-lift)"/>`);let n=Sz(t.text).trim();if(n&&i.w*m>28){let e=6/m,t=Math.max(0,i.w-e*2),r=3.2/m,a=6.5/m;kz(n,5/m,t,3).forEach((n,o)=>{let s=i.y+e+o*a;if(s+r>i.y+i.h-e/2)return;let c=Math.min(t,Math.max(r*2,Oz(n,5/m)));_.push($(i.x+e,s,c,r,`#514a37`,o===0?`.42`:`.26`))})}}else{let e=Tz(t.size)&&t.size>0?t.size:96,n=Sz(t.text).trim();if(n&&e*m>3){let t=Math.max(3/m,e*.42),r=Math.min(i.w,Math.max(t*2.5,Oz(n,e*.65)));_.push($(i.x,i.y+(i.h-t)/2,r,t,`var(--muted)`,`.38`))}}}}return Q(0,0,600,360,`var(--bg)`)+`<defs>${jz(`ab-lift`,4,7,`.09`)}<pattern id="dots" width="16" height="16" patternUnits="userSpaceOnUse"><circle cx="1.5" cy="1.5" r=".9" fill="var(--dot)"/></pattern></defs>`+Q(0,0,600,360,`url(#dots)`)+`<g transform="translate(${h} ${g}) scale(${m})">${_.join(``)}</g>`}function Iz(e,t){let n=Z(t.report),r=Cz(n.items),i=0,a=0,o=[];for(let e of r){let t=Sz(e.kind);if(t===`gap`)a+=1,o.length<5&&o.push({kind:`gap`,title:Sz(e.title)||`Unverified gap`,tag:`gap`});else if(t===`row`)i+=1,o.length<5&&o.push({kind:`row`,title:`${Sz(e.artboard)} / ${Sz(e.group)}`.replace(/^ \/ $/,`Artboard verify`),tag:`board`});else if(t===`claim`){i+=1;let t=Cz(e.evidence).some(e=>Sz(e.kind)===`output`);o.length<5&&o.push({kind:`claim`,title:Sz(e.title)||`Claim`,tag:t?`output`:`evidence`})}}let s=kz(e,15.5,430,1),c=[],l=84,u=(e,t,n,r=!0)=>{let i=Math.max(66,Math.round(Oz(e,9.5)+(r?30:22)));c.push(Q(l,94,i,22,t,`none`,11)),r&&c.push(`<circle cx="${l+13}" cy="105" r="3.5" fill="${n}"/>`),c.push(Ez(r?l+22:l+i/2,108.5,e,9.5,n,600,r?``:` text-anchor="middle"`)),l+=i+8};u(i>0?`${i} checked`:`Verified`,`var(--pass-bg)`,`var(--pass)`,!0),a>0&&u(`${a} gap${a>1?`s`:``}`,`var(--warn-bg)`,`var(--warn)`,!0),r.length>0&&u(`${r.length} items`,`var(--block)`,`var(--muted)`,!1);let d=o.map((e,t)=>{let n=158+t*42,r=e.kind===`gap`,i=r?`<circle cx="96" cy="${n}" r="7.5" fill="var(--warn-bg)"/><rect x="95.1" y="${n-4}" width="1.8" height="4.8" rx=".9" fill="var(--warn)"/><circle cx="96" cy="${n+3.2}" r="1.1" fill="var(--warn)"/>`:`<circle cx="96" cy="${n}" r="7.5" fill="var(--pass-bg)"/><path d="M 92.5 ${n} L 95.2 ${n+2.7} L 100 ${n-2.6}" fill="none" stroke="var(--pass)" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>`,a=kz(e.title,10.5,326,1)[0]??``;return i+Ez(114,n+3.5,a,10.5,`var(--ink)`,500)+Q(454,n-9,62,18,r?`var(--warn-bg)`:`var(--block)`,`none`,9)+Ez(485,n+3,e.tag,8,r?`var(--warn)`:`var(--muted)`,600,` text-anchor="middle"`)+`<line x1="84" y1="${n+21}" x2="516" y2="${n+21}" stroke="var(--border)" stroke-width=".7"/>`}).join(``),f=o.length===0?[0,1,2].map(e=>{let t=158+e*44;return`<circle cx="96" cy="${t}" r="7.5" fill="var(--pass-bg)"/><path d="M 92.5 ${t} L 95.2 ${t+2.7} L 100 ${t-2.6}" fill="none" stroke="var(--pass)" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>`+Q(114,t-4,240-e*36,8,`var(--block)`,`none`,4)+Q(454,t-8,62,16,`var(--block)`,`none`,8)}).join(``):``;return Q(0,0,600,360,`var(--desk-verify)`)+`<defs>${jz(`vf-lift`,8,14,`.1`)}</defs><rect x="56" y="24" width="488" height="352" rx="10" fill="var(--paper)" stroke="var(--edge)" filter="url(#vf-lift)"/>`+Ez(84,56,`VERIFY REPORT`,9,`var(--pass)`,650,` letter-spacing="0.06em"`)+Ez(84,80,s[0]??e,15.5,`var(--ink)`,650)+c.join(``)+`<line x1="56" y1="130" x2="544" y2="130" stroke="var(--border)" stroke-width="1"/>`+d+f}function Lz(e,t,n,r,i){if(e===`two-cols`){let e=(r-14)/2;return Q(t,n,e,i,`var(--paper-subtle)`,`var(--border)`,5)+$(t+12,n+14,e*.55,6,`var(--border-strong)`,`1`)+$(t+12,n+28,e-24,5,`var(--block)`,`1`)+$(t+12,n+40,e*.72,5,`var(--block)`,`1`)+Q(t+e+14,n,e,i,`var(--paper-subtle)`,`var(--border)`,5)+$(t+e+26,n+14,e*.55,6,`var(--border-strong)`,`1`)+$(t+e+26,n+28,e-24,5,`var(--block)`,`1`)+$(t+e+26,n+40,e*.65,5,`var(--block)`,`1`)}if(e===`code`)return Q(t,n,r,i,`var(--block)`,`var(--border)`,6)+$(t+14,n+14,74,5,`var(--accent)`,`.75`)+$(t+26,n+28,176,5,`var(--muted)`,`.42`)+$(t+26,n+40,132,5,`var(--muted)`,`.34`)+$(t+14,n+52,92,5,`var(--muted)`,`.38`);if(e===`image`){let e=r*.44,a=t+e+14,o=r-e-14;return $(t,n+10,e*.85,6,`var(--border-strong)`,`1`)+$(t,n+24,e*.95,5,`var(--block)`,`1`)+$(t,n+36,e*.75,5,`var(--block)`,`1`)+Q(a,n,o,i,`var(--block)`,`var(--border)`,6)+`<circle cx="${a+o*.28}" cy="${n+i*.34}" r="6" fill="var(--border-strong)"/><path d="M ${a+10} ${n+i-8} L ${a+o*.45} ${n+i*.46} L ${a+o*.7} ${n+i*.72} L ${a+o*.85} ${n+i*.56} L ${a+o-10} ${n+i-8} Z" fill="var(--border-strong)" fill-opacity=".65"/>`}return e===`quote`?Q(t,n+4,3.5,i-8,`var(--accent)`,`none`,1.75)+$(t+16,n+12,r*.82,7,`var(--ink-soft)`,`.32`)+$(t+16,n+28,r*.68,7,`var(--ink-soft)`,`.26`)+$(t+16,n+48,84,5,`var(--muted)`,`.35`):e===`fact`?Q(t,n,128,i,`var(--accent-soft)`,`none`,6)+$(t+18,n+i*.36,92,16,`var(--accent)`,`.82`)+$(t+146,n+16,r-160,6,`var(--border-strong)`,`1`)+$(t+146,n+30,(r-160)*.8,5,`var(--block)`,`1`)+$(t+146,n+42,(r-160)*.6,5,`var(--block)`,`1`):e===`statement`||e===`section`||e===`end`?$(t+r*.2,n+18,r*.6,7,`var(--border-strong)`,`.9`)+$(t+r*.32,n+34,r*.36,5,`var(--block)`,`1`):``}function Rz(e,t,n){return e===`two-cols`?Q(t+5,n+6,14,12,`var(--block)`,`none`,1.5)+Q(t+22,n+6,14,12,`var(--block)`,`none`,1.5):e===`code`?Q(t+5,n+6,32,12,`var(--block)`,`none`,2)+Q(t+8,n+9,14,2,`var(--accent)`,`none`,1):e===`image`?Q(t+5,n+7,13,3,`var(--border-strong)`,`none`,1)+Q(t+5,n+12,10,2,`var(--block)`,`none`,1)+Q(t+21,n+6,16,12,`var(--block)`,`none`,2):e===`fact`?Q(t+5,n+6,14,12,`var(--accent-soft)`,`none`,2)+Q(t+22,n+8,14,3,`var(--border-strong)`,`none`,1)+Q(t+22,n+13,10,2,`var(--block)`,`none`,1):e===`quote`?Q(t+6,n+6,2,12,`var(--accent)`,`none`,1)+Q(t+11,n+8,22,2.5,`var(--border-strong)`,`none`,1)+Q(t+11,n+13,16,2,`var(--block)`,`none`,1):e===`section`||e===`statement`||e===`end`?Q(t+11,n+10,20,3.5,`var(--border-strong)`,`none`,1.5):Q(t+5,n+6,18,3,`var(--border-strong)`,`none`,1)+Q(t+5,n+12,28,2,`var(--block)`,`none`,1)+Q(t+5,n+16,22,2,`var(--block)`,`none`,1)}function zz(e,t){let n=Array.isArray(t.outline)?t.outline.map(Z):Cz(Z(t.outline).slides),r=n.length,i=Sz(n[0]?.layout)||`cover`,a=r>0?`DECK · ${r} SLIDE${r===1?``:`S`}`:`SLIDES DECK`,o=kz(e,20.5,384,2),s=Lz(i,108,202,384,68),c=n.map(e=>Sz(e.title)).filter(Boolean).slice(0,3),l=s||(c.length>0?c.map((e,t)=>{let n=216+t*20,r=kz(e,9.5,356,1)[0]??``;return Ez(108,n,String(t+1).padStart(2,`0`),9.5,t===0?`var(--accent)`:`var(--muted)`,600)+Ez(128,n,r,9.5,t===0?`var(--ink-soft)`:`var(--muted)`,400)}).join(``):Q(108,210,236,7,`var(--block)`,`none`,3.5)+Q(108,226,184,7,`var(--block)`,`none`,3.5)+Q(108,242,140,7,`var(--block)`,`none`,3.5)),u=Math.min(4,Math.max(3,r||4)),d=Array.from({length:u},(e,t)=>{let r=204+t*50,i=t===0,a=Sz(n[t]?.layout)||(t===0?`cover`:`default`);return`<g${i?``:` opacity="${(.86-t*.12).toFixed(2)}"`}><rect x="${r}" y="308" width="42" height="24" rx="4" fill="var(--paper)" stroke="${i?`var(--accent)`:`var(--border-strong)`}" stroke-width="${i?`1.5`:`.8`}"/>`+Rz(a,r,308)+`</g>`}).join(``),f=r>0?Ez(204+u*50+6,324,`1 / ${r}`,9.5,`var(--muted)`,600):``;return Q(0,0,600,360,`var(--desk-slides)`)+`<defs>${jz(`sl-lift`,10,16,`.12`)}</defs>`+Q(104,22,392,220,`var(--slide-back)`,`var(--border)`,8)+`<rect x="76" y="36" width="448" height="252" rx="8" fill="var(--paper)" stroke="var(--border-strong)" filter="url(#sl-lift)"/>`+Q(108,66,36,4,`var(--accent)`,`none`,2)+Ez(108,94,a,9,`var(--muted)`,650,` letter-spacing="0.08em"`)+o.map((e,t)=>Ez(108,130+t*28,e,20.5,`var(--ink)`,700)).join(``)+`<line x1="108" y1="192" x2="492" y2="192" stroke="var(--border)" stroke-width=".8"/>`+l+d+f}function Bz(e,t,n,r,i){if(e===`cards`){let e=r>280?3:2,a=(r-10*(e-1))/e;return Array.from({length:e},(e,r)=>{let o=t+r*(a+10);return Q(o,n,a,i,`var(--paper-subtle)`,`var(--border)`,6)+$(o+10,n+12,a*.52,5.5,`var(--border-strong)`,`1`)+$(o+10,n+24,a-20,4.5,`var(--block)`,`1`)+$(o+10,n+34,a*.65,4.5,`var(--block)`,`1`)}).join(``)}if(e===`table`){let e=Math.max(2,Math.min(4,Math.floor(i/18))),a=i/e;return Q(t,n,r,i,`var(--paper)`,`var(--border)`,5)+Q(t,n,r,a,`var(--block)`,`none`,5)+Array.from({length:e},(e,i)=>{let o=n+i*a;return(i>0?`<line x1="${t}" y1="${o}" x2="${t+r}" y2="${o}" stroke="var(--border)" stroke-width=".7"/>`:``)+$(t+10,o+a*.35,r*.24,4.5,i===0?`var(--muted)`:`var(--border-strong)`,i===0?`.5`:`.8`)+$(t+r*.42,o+a*.35,r*.28,4.5,`var(--block)`,`1`)+$(t+r*.78,o+a*.35,r*.14,4.5,`var(--block)`,`1`)}).join(``)}if(e===`code`)return Q(t,n,r,i,`var(--block)`,`var(--border)`,6)+$(t+14,n+12,r*.28,5,`var(--accent)`,`.75`)+$(t+26,n+24,r*.56,4.5,`var(--muted)`,`.42`)+$(t+26,n+35,r*.42,4.5,`var(--muted)`,`.34`);if(e===`form`){let e=Math.min(r*.62,240);return Q(t,n,r,i,`var(--paper-subtle)`,`var(--border)`,6)+Q(t+12,n+10,e,18,`var(--paper)`,`var(--border)`,4)+Q(t+12,n+34,e,18,`var(--paper)`,`var(--border)`,4)+Q(t+e+22,n+34,Math.min(72,r-e-34),18,`var(--accent)`,`none`,4)}if(e===`chart`){let e=[.38,.62,.5,.82,.68,.94,.72],a=Math.min(26,(r-28-8*(e.length-1))/e.length);return Q(t,n,r,i,`var(--paper-subtle)`,`var(--border)`,6)+e.map((e,r)=>{let o=Math.max(8,(i-20)*e);return Q(t+14+r*(a+8),n+i-8-o,a,o,r===5?`var(--accent)`:`var(--chart-bar-mid)`,`none`,3)}).join(``)}if(e===`list`){let e=Math.max(2,Math.min(3,Math.floor(i/16)));return Array.from({length:e},(e,i)=>{let a=n+6+i*16;return`<circle cx="${t+5}" cy="${a+2.5}" r="2.5" fill="var(--accent)"/>`+$(t+16,a,r*(.78-i*.14),5,`var(--border-strong)`,`.85`)}).join(``)}return $(t,n+6,r*.92,5.5,`var(--border-strong)`,`.8`)+$(t,n+19,r*.84,5,`var(--block)`,`1`)+$(t,n+31,r*.62,5,`var(--block)`,`1`)}function Vz(e){let t=e.boxes.map(t=>{if(t.kind===`text`){let n=Math.max(3,Math.min(t.h*.65,14)),r=Math.round((t.y+(t.h-n)/2)*10)/10,i=n>=9?`.62`:`.36`;return`<rect x="${t.x}" y="${r}" width="${t.w}" height="${Math.round(n*10)/10}" rx="${Math.round(n/2*10)/10}" fill="${t.bg??e.ink??`var(--ink)`}" fill-opacity="${i}"/>`}let n=t.r??(t.kind===`control`?4:3),r=t.bg??`none`,i=t.border??`none`,a=`<rect x="${t.x}" y="${t.y}" width="${t.w}" height="${t.h}"${n>0?` rx="${n}"`:``} fill="${r}" stroke="${i}"/>`;if(t.kind===`media`&&t.w>=36&&t.h>=24){let n=Math.round((t.x+t.w*.3)*10)/10,r=Math.round((t.y+t.h*.34)*10)/10,i=Math.max(2.5,Math.min(6,Math.min(t.w,t.h)*.12));return`${a}<circle cx="${n}" cy="${r}" r="${Math.round(i*10)/10}" fill="${e.ink??`var(--muted)`}" fill-opacity=".2"/>`}return a}).join(``);return`<clipPath id="ht-vp"><rect x="45" y="60" width="510" height="300"/></clipPath><g clip-path="url(#ht-vp)"><rect x="45" y="60" width="510" height="300" fill="${e.bg}"/><g transform="translate(45 60) scale(0.85 0.8333)">${t}</g></g>`}function Hz(e,t,n){let r=e.project?.split(`/`).at(-1),i=r?`${r} / HTML`:`index.html`,a=Jl(n.domSnapshot);if(a)return Q(0,0,600,360,`var(--cover)`)+`<defs>${jz(`ht-lift`,8,14,`.1`)}</defs><rect x="44" y="26" width="512" height="352" rx="10" fill="var(--paper)" stroke="var(--border-strong)" filter="url(#ht-lift)"/><path d="M 45 36 Q 45 27 54 27 L 546 27 Q 555 27 555 36 L 555 60 L 45 60 Z" fill="var(--paper-subtle)"/><line x1="44" y1="60" x2="556" y2="60" stroke="var(--border)" stroke-width="1"/><circle cx="64" cy="43.5" r="4" fill="var(--border-strong)"/><circle cx="78" cy="43.5" r="4" fill="var(--border-strong)"/><circle cx="92" cy="43.5" r="4" fill="var(--border-strong)"/>`+Q(176,34,248,19,`var(--block)`,`none`,9.5)+Ez(300,46.5,kz(i,9,224,1)[0]??i,9,`var(--muted)`,500,` text-anchor="middle"`)+Ez(536,47,`</>`,10.5,`var(--muted)`,600,` text-anchor="end"`)+Vz(a);let o=Z(n.skeleton),s=o.hasNav===!0,c=o.hasSidebar===!0,l=Array.isArray(o.blocks)?o.blocks.filter(e=>typeof e==`string`&&[`cards`,`chart`,`code`,`form`,`list`,`table`,`text`].includes(e)):[],u=Sz(o.heading)||t,d=c?168:74,f=c?358:452,p=60,m=[];s&&(m.push(Q(45,60,510,26,`var(--paper)`,`none`),`<line x1="44" y1="86" x2="556" y2="86" stroke="var(--border)" stroke-width=".7"/>`,`<circle cx="66" cy="73" r="4.5" fill="var(--accent)"/>`,$(78,70.5,44,5,`var(--ink-soft)`,`.55`),$(366,71,32,4,`var(--muted)`,`.35`),$(408,71,32,4,`var(--muted)`,`.35`),$(450,71,32,4,`var(--muted)`,`.35`),Q(494,66,42,14,`var(--accent-soft)`,`none`,7)),p=86),c&&m.push(Q(45,p,108,378-p,`var(--paper-subtle)`,`none`),`<line x1="153" y1="${p}" x2="153" y2="378" stroke="var(--border)" stroke-width=".8"/>`,$(60,p+18,56,5.5,`var(--border-strong)`,`.95`),Q(56,p+34,84,18,`var(--accent-soft)`,`none`,4),$(64,p+40.5,48,5,`var(--accent)`,`.75`),$(64,p+64,62,4.5,`var(--muted)`,`.34`),$(64,p+80,52,4.5,`var(--muted)`,`.34`),$(64,p+96,68,4.5,`var(--muted)`,`.34`),$(64,p+112,44,4.5,`var(--muted)`,`.28`));let h=p+26,g=kz(u,18,f,2);m.push(g.map((e,t)=>Ez(d,h+t*24,e,18,`var(--ink)`,650)).join(``));let _=h+g.length*24+10;if(l.length>0){let e=Math.max(60,344-_),t=l.slice(0,2),n=Math.min(82,(e-12*(t.length-1))/t.length);t.forEach((e,t)=>{m.push(Bz(e,d,_+t*(n+12),f,n))})}else m.push(Bz(`cards`,d,_,f,66),Bz(`text`,d,_+78,f,44));return Q(0,0,600,360,`var(--cover)`)+`<defs>${jz(`ht-lift`,8,14,`.1`)}</defs><rect x="44" y="26" width="512" height="352" rx="10" fill="var(--paper)" stroke="var(--border-strong)" filter="url(#ht-lift)"/><path d="M 45 36 Q 45 27 54 27 L 546 27 Q 555 27 555 36 L 555 60 L 45 60 Z" fill="var(--paper-subtle)"/><line x1="44" y1="60" x2="556" y2="60" stroke="var(--border)" stroke-width="1"/><circle cx="64" cy="43.5" r="4" fill="var(--border-strong)"/><circle cx="78" cy="43.5" r="4" fill="var(--border-strong)"/><circle cx="92" cy="43.5" r="4" fill="var(--border-strong)"/>`+Q(176,34,248,19,`var(--block)`,`none`,9.5)+Ez(300,46.5,kz(i,9,224,1)[0]??i,9,`var(--muted)`,500,` text-anchor="middle"`)+Ez(536,47,`</>`,10.5,`var(--muted)`,600,` text-anchor="end"`)+m.join(``)}function Uz(e){let t=kz(e,16,444,1),n=[44,62,54,82,74,108,92,122,98].map((e,t)=>{let n=96+t*46,r=324-e;return Q(n,r,28,e,t===7?`var(--accent)`:t>=5?`var(--chart-bar-mid)`:`var(--chart-bar)`,`none`,4)}).join(``);return Q(0,0,600,360,`var(--desk-report)`)+`<defs>${jz(`rp-lift`,8,14,`.1`)}</defs><rect x="48" y="24" width="504" height="352" rx="10" fill="var(--paper)" stroke="var(--edge)" filter="url(#rp-lift)"/>`+Ez(78,54,`DATA REPORT`,9,`var(--muted)`,650,` letter-spacing="0.06em"`)+Ez(78,78,t[0]??e,16,`var(--ink)`,650)+Q(78,96,138,58,`var(--paper-subtle)`,`var(--border)`,6)+Q(92,110,46,5,`var(--border-strong)`,`none`,2.5)+`<rect x="92" y="124" width="76" height="14" rx="3" fill="var(--ink)" fill-opacity=".78"/>`+Q(230,96,138,58,`var(--paper-subtle)`,`var(--border)`,6)+Q(244,110,52,5,`var(--border-strong)`,`none`,2.5)+`<rect x="244" y="124" width="64" height="14" rx="3" fill="var(--accent)" fill-opacity=".88"/>`+Q(382,96,140,58,`var(--paper-subtle)`,`var(--border)`,6)+Q(396,110,58,5,`var(--border-strong)`,`none`,2.5)+`<rect x="396" y="124" width="70" height="14" rx="3" fill="var(--pass)" fill-opacity=".8"/><line x1="78" y1="202" x2="522" y2="202" stroke="var(--border)" stroke-width=".6" stroke-dasharray="3 3"/><line x1="78" y1="242" x2="522" y2="242" stroke="var(--border)" stroke-width=".6" stroke-dasharray="3 3"/><line x1="78" y1="282" x2="522" y2="282" stroke="var(--border)" stroke-width=".6" stroke-dasharray="3 3"/><line x1="78" y1="324" x2="522" y2="324" stroke="var(--border-strong)" stroke-width="1"/>`+n}function Wz(e){let t=kz(e,16,444,1),n=[0,1,2,3].map(e=>{let t=78+e*114;return Q(t,112,102,58,e===1?`var(--ink)`:`var(--paper-subtle)`,`var(--border)`,5)+Q(t+10,182,62,5,`var(--border-strong)`,`none`,2.5)+Q(t+10,194,44,5,`var(--border)`,`none`,2.5)}).join(``),r=[70,120,60,110,84].reduce((e,t,n)=>({x:e.x+t+4,svg:e.svg+Q(e.x,300,t,14,n===1?`var(--ink)`:`var(--block)`,`none`,3)}),{x:78,svg:``}).svg;return Q(0,0,600,360,`var(--cover)`)+`<defs>${jz(`sb-lift`,8,14,`.1`)}</defs><rect x="48" y="24" width="504" height="352" rx="10" fill="var(--paper)" stroke="var(--edge)" filter="url(#sb-lift)"/>`+Ez(78,54,`STORYBOARD`,9,`var(--muted)`,650,` letter-spacing="0.06em"`)+Ez(78,78,t[0]??e,16,`var(--ink)`,650)+n+`<line x1="78" y1="240" x2="522" y2="240" stroke="var(--border)" stroke-width=".6" stroke-dasharray="3 3"/>`+Q(78,258,300,6,`var(--border-strong)`,`none`,3)+Q(78,272,220,6,`var(--border)`,`none`,3)+r+`<line x1="190" y1="294" x2="190" y2="320" stroke="var(--accent)" stroke-width="2"/>`}function Gz(e,t){let n=e.title??e.id,r;if(e.type===`document`)r=Mz(n,Z(t));else if(e.type===`artboard`)r=Fz(Z(t));else if(e.type===`whiteboard`){let e=Z(t).scene;r=xz(n,Array.isArray(e)?e:[])}else r=e.type===`verify`?Iz(n,Z(t)):e.type===`slides`?zz(n,Z(t)):e.type===`report`?Uz(n):e.type===`storyboard`?Wz(n):Hz(e,n,Z(t));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 360"><title>${wz(n)}</title><style>:root{--ink:#1f1e1b;--ink-soft:#4c4943;--muted:#7e7a72;--paper:#ffffff;--paper-subtle:#f9f8f5;--bg:#f3f2ee;--border:#dedbd4;--border-strong:#ccc8be;--block:#f2f0eb;--alert:#f9f1e9;--alert-bar:#c65d3b;--accent:#c65d3b;--accent-soft:#f6e6df;--desk:#eeece7;--edge:#dedbd4;--dot:#d4d0c7;--shadow:#1a1814;--desk-wb:#f7f6f2;--wb-grid:#e7e5de;--wb-sticky:#fef2bd;--wb-sticky-edge:#e6d48a;--wb-sticky-ink:#5c4e24;--desk-verify:#edf2ee;--pass:#2b8a57;--pass-bg:#e4f4eb;--warn:#b87216;--warn-bg:#fbf0dc;--desk-slides:#e9ebef;--slide-back:#d8dce3;--cover:#eaf0f3;--desk-report:#eef0f3;--chart-bar:#d3d8e0;--chart-bar-mid:#b5becb}@media (prefers-color-scheme: dark){:root{--ink:#eceae4;--ink-soft:#c2bfb8;--muted:#8f8c84;--paper:#252522;--paper-subtle:#2c2c29;--bg:#191917;--border:#3a3a35;--border-strong:#4b4b45;--block:#30302c;--alert:#362d26;--alert-bar:#e07a57;--accent:#e07a57;--accent-soft:#3b2922;--desk:#1b1b19;--edge:#3a3a35;--dot:#363631;--shadow:#000000;--desk-wb:#1e1e1c;--wb-grid:#2b2b27;--wb-sticky:#3d3520;--wb-sticky-edge:#574a28;--wb-sticky-ink:#f0df9e;--desk-verify:#19201b;--pass:#4cc38a;--pass-bg:#1d3327;--warn:#e5a94c;--warn-bg:#352b1a;--desk-slides:#181a1f;--slide-back:#2d313a;--cover:#181e22;--desk-report:#191c20;--chart-bar:#343942;--chart-bar-mid:#48505e}}text{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,sans-serif}rect{stroke-width:.8;vector-effect:non-scaling-stroke}</style>${r}</svg>`}const Kz=/^\/api\/artifacts\/([^/]+)\/([^/]+)$/,qz=/^\/api\/preview\/([^/]+)\/([^/]+)$/,Jz=/^\/api\/thumbnail\/([^/]+)\/([^/]+)\.svg$/,Yz={path:`/api/artifacts`,auth:`viewer`,handle:(e,t,n)=>{let{artifacts:r,warnings:i}=BM(n),a=r.map(e=>{let t=ir(e.dir),r=oj[e.type].listedStateFile;if(r)try{let i=d.default.statSync(p.default.join(n.stateDir,e.type,e.id,r));t=Math.max(t,Math.floor(i.mtimeMs))}catch{}return{type:e.type,id:e.id,url:xi(n.root,e.type,e.id),title:zR(n.readArtifact(e.dir,e)),updatedAt:t}});B(t,200,{project:VR(n),artifacts:a,warnings:i})}},Xz={path:IN,auth:`viewer`,handle:(e,t,n,{match:r})=>{n.avatars.load(r[1],r[2]).then(({status:e,type:n,body:r})=>{r&&n?z(t,e,r,{"Content-Type":n,"Cache-Control":`private, max-age=86400`}):z(t,e,`No avatar`)})}},Zz={path:qz,auth:`viewer`,handle:async(e,t,n,{match:r})=>{let[,i=``,a=``]=r,o=W(n.root,i,a),s=G(`${i}/${a}`);if(!o||!s)B(t,404,{error:`Artifact not found`});else{await NM(s,o,{publish:!0});try{let e=n.readArtifact(o,s),r=zR(e);B(t,200,{...HN(s,o,r,e),title:r,warnings:e.warnings,contentBase:`${n.contentPrefix}${i}/${a}/`})}catch{B(t,422,{error:`Preview unavailable`})}}}},Qz={path:Jz,auth:`viewer`,handle:async(e,t,n,{match:r})=>{let i=G(`${r[1]}/${r[2]}`,Xn),a;try{a=i&&Si(n.root,i.type,i.id)}catch{a=null}if(!a){z(t,404,`Artifact not found`);return}let o={type:a.type,id:a.id};await NM(o,a.dir,{publish:!0});try{let e=n.readArtifact(a.dir,o),r=zR(e);z(t,200,Gz({id:o.id,type:o.type,title:r,project:VR(n)},HN(o,a.dir,r,e)),{"Content-Type":`image/svg+xml`,"Cache-Control":`private, max-age=31536000, immutable`,"Content-Security-Policy":`sandbox; default-src 'none'; style-src 'unsafe-inline'`,"X-Content-Type-Options":`nosniff`})}catch{z(t,422,`Thumbnail unavailable`)}}},$z={path:Kz,auth:`viewer`,handle:async(e,t,n,{match:r})=>{let[,i=``,a=``]=r,o=W(n.root,i,a);if(!o){B(t,404,{warnings:[`artifact ${i}/${a} not found`]});return}let s=G(`${i}/${a}`);await NM(s,o),RM(n,s),B(t,200,{...n.artifactMeta(s,o),...oj[s.type].localMeta?.(n,s.id)})}},eB={path:(e,t)=>t.cloud&&e===`/api/cloud/callback`?[e]:null,auth:`public`,handle:(e,t,n,{url:r})=>n.cloud.handleCallback(r,t,dF(fF(e.headers[`accept-language`])))},tB={path:(e,t)=>t.cloud&&e===`/api/cloud/callback/auto-publish`?[e]:null,auth:`public`,handle:(e,t,n)=>n.cloud.handleCallbackAutoPublish(e,t,dF(fF(e.headers[`accept-language`])))},nB={path:`/api/cloud/flush`,methods:[`POST`],auth:`agent`,handle:(e,t,n,{url:r})=>{let{autoPublisher:i,cloud:a}=n;if(!i){B(t,404,{error:`cloud publishing is not configured`});return}BM(n);let o=i.flush().then(()=>a?.syncModules());r.searchParams.get(`wait`)===`1`?o.then(()=>B(t,200,{flushed:!0})):B(t,202,{queued:!0})}},rB={path:(e,t)=>t.cloud?.match(e)??null,auth:`cloud`,handle:(e,t,n,{match:r})=>{let[,i,a,o]=r,s=(i===`reserve`||i===`publish`&&e.method===`POST`)&&a&&o?G(`${a}/${o}`):null;s&&RM(n,s),n.cloud.handle(e,t,r)}},iB={path:`/api/agent/daemon`,methods:[`POST`],auth:`same-origin`,handle:async(e,t,n)=>{let r=n.options.agentDaemon;if(!r){B(t,404,{error:`this computer has no daemon`});return}let i=await yc(e),{artifact:a,...o}=typeof i==`object`&&i?i:{};if(typeof a!=`string`||!G(a))B(t,400,{error:`need an artifact`});else try{B(t,200,{ok:!0,data:await r.request(a,o,n.loopback)})}catch(e){B(t,409,{ok:!1,error:e.message})}}},aB=/^\/relay\/a\/([\w-]{1,64})$/,oB=RegExp(`(?:^|/)(${we.join(`|`)})/([\\w-]+)`);function sB(e,t){let n=t===null?null:oB.exec(t);if(!n)return null;let r=n[1],i=n[2];if(W(e,r,i))return`${r}/${i}`;try{return`${r}/${Si(e,r,i)?.id??i}`}catch{return`${r}/${i}`}}const cB={path:aB,auth:`direct-relay`,handle:(e,t,n,{match:r,clientKey:i})=>{let a=n.servedArtifacts().get(r[1]);a?n.direct.accept(t,i,a):dc(t,404,`Not Found`)}},lB={path:`/ws`,auth:`socket`,handle:(e,t,n,{clientKey:r})=>{uc(t,r),n.clients.add(t);let i=sB(n.root,new URL(e.url??`/`,`http://x`).searchParams.get(`at`)),a=i?[NR,i]:[NR,PR];a.forEach(n.viewed.viewerJoined),t.write(n.agentStatusFrame());for(let e of n.threadActivityFrames())t.write(e);fc(t,e=>lN(n,t,e));let o=()=>{n.clients.delete(t)&&(n.selections.drop(t),a.forEach(n.viewed.viewerLeft))};t.on(`end`,()=>{o(),t.end()}),t.on(`close`,o),t.on(`error`,o),n.touch()}},uB={artboard:{fill:`M9.3 9a1.3 1.3 0 1 1-2.6 0a1.3 1.3 0 1 1 2.6 0z M13.3 7a1.3 1.3 0 1 1-2.6 0a1.3 1.3 0 1 1 2.6 0z M17.3 9.5a1.3 1.3 0 1 1-2.6 0a1.3 1.3 0 1 1 2.6 0z M8.8 13a1.3 1.3 0 1 1-2.6 0a1.3 1.3 0 1 1 2.6 0z`,stroke:`M12 3.5c-5 0-8.5 3.8-8.5 8.5s3.6 8.5 7.6 8.5c1.2 0 1.6-.8 1.6-1.9v-1.3c0-1.3 1-2.3 2.3-2.3h2.3c2.2 0 3.7-1.5 3.7-3.6 0-4.4-4-7.9-9-7.9z`},document:{fill:``,stroke:`M7 3h10a2.5 2.5 0 0 1 2.5 2.5v13a2.5 2.5 0 0 1-2.5 2.5H7a2.5 2.5 0 0 1-2.5-2.5v-13A2.5 2.5 0 0 1 7 3z M8.5 8.5h7M8.5 12h7M8.5 15.5h4`},html:{fill:``,stroke:`M8 7.5 3.5 12 8 16.5M16 7.5l4.5 4.5-4.5 4.5M13.5 5.5l-3 13`},whiteboard:{fill:``,stroke:`M5 4.5h14a1.5 1.5 0 0 1 1.5 1.5v10a1.5 1.5 0 0 1-1.5 1.5H5A1.5 1.5 0 0 1 3.5 16V6A1.5 1.5 0 0 1 5 4.5z M7 13.5c1.5-2.5 3-3.5 4-2s2.5 1 4.5-2 M9 17.5l-1.5 3M15 17.5l1.5 3`},verify:{fill:``,stroke:`M7 3h10a2.5 2.5 0 0 1 2.5 2.5v13a2.5 2.5 0 0 1-2.5 2.5H7a2.5 2.5 0 0 1-2.5-2.5v-13A2.5 2.5 0 0 1 7 3z M8.5 9l1.5 1.5 3-3M8.5 15l1.5 1.5 3-3M15 9.5h1M15 15.5h1`},slides:{fill:``,stroke:`M3.5 4.5h17M5 4.5V14a1.5 1.5 0 0 0 1.5 1.5h11A1.5 1.5 0 0 0 19 14V4.5M12 15.5v2.5M8.5 20.5l3.5-2.5 3.5 2.5M9 8.5h6M9 11.5h3.5`},report:{fill:``,stroke:`M4 20h16M7 16.5v-4M11 16.5v-8M15 16.5v-6M19 16.5V5.5`},storyboard:{fill:``,stroke:`M4 10h16v8.5a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 18.5V10z M4 10l-.6-3a1.3 1.3 0 0 1 1-1.5l12.7-2.4a1.3 1.3 0 0 1 1.5 1l.5 2.6L4 10z M8.4 4.9l2.5 3.2M12.9 4l2.5 3.2`}},dB=`#C65D3B`;function fB(e){let{fill:t,stroke:n}=uB[e],r=[`<svg xmlns="http://www.w3.org/2000/svg" viewBox="-2 -2 28 28">`,`<rect x="-2" y="-2" width="28" height="28" rx="6" fill="#FBEDE6"/>`,t&&`<path d="${t}" fill="${dB}"/>`,`<path d="${n}" fill="none" stroke="${dB}" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round"/>`,`</svg>`].join(``);return`data:image/svg+xml,${encodeURIComponent(r)}`}const pB=e=>e.replaceAll(/[&<>"']/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`})[e]);function mB(e,t){let n=t.locale??`en`,r={robots:`noindex, nofollow`,"og:locale":n===`zh`?`zh_CN`:`en_US`,description:t.description,"og:title":t.title,"og:description":t.description,"twitter:title":t.title,"twitter:description":t.description};return e.replace(/<html\b([^>]*)>/i,(e,r)=>`<html${r.replace(/\slang="[^"]*"/i,``)} lang="${uF[n]}"${t.artifactId?` data-ryugi-artifact-id="${pB(t.artifactId)}"`:``}${t.project?` data-ryugi-project="${pB(t.project)}"`:``}${t.embedParent?` data-ryugi-embed-parent="${pB(t.embedParent)}"`:``}>`).replace(/<title\b[^>]*>[\s\S]*?<\/title>/i,()=>`<title>${pB(t.title)}</title>`).replace(/(<link\b[^>]+\brel="icon"[^>]*\bhref=")[^"]*(")/i,(e,n,r)=>t.icon?`${n}${pB(t.icon)}${r}`:e).replaceAll(/(<meta\b[^>]+\b(?:name|property)="([^"]+)"[^>]*\bcontent=")([^"]*)("[^>]*>)/gi,(e,n,i,a,o)=>{let s=r[i]??(i===`og:image`||i===`twitter:image`?new URL(a,t.url).href:void 0);return s===void 0?e:`${n}${pB(s)}${o}`}).replace(/<\/head>/i,()=>`<link rel="canonical" href="${pB(t.url)}">\n<meta property="og:url" content="${pB(t.url)}">\n</head>`)}const hB=/<script\b(?![^>]+\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi;function gB(e,t){let n=[...t.matchAll(hB)].map(([,e])=>`'sha256-${(0,u.createHash)(`sha256`).update(e).digest(`base64`)}'`);return n.length?e.replace(/script-src [^;]*/,e=>`${e} ${n.join(` `)}`):e}const _B=RegExp(`^/(?:(${we.join(`|`)})/([^/]+)/?)?$`),vB=RegExp(`^/preview/(artboard|document|html)/${Vn}/?$`),yB=/^\/preview\/([a-z0-9][a-z0-9-]{0,63})\/?$/,bB=/^\/storyboard\/([^/]+)\/render\/?$/,xB=RegExp(`^/embed/(${we.join(`|`)})/([\\w-]{1,64})/?$`),SB=e=>[`default-src 'self'`,`script-src 'self' 'wasm-unsafe-eval'`,`style-src 'self' 'unsafe-inline'`,`img-src 'self' data: blob:`,`font-src 'self' data:`,`connect-src 'self' ${e.join(` `)}`,`frame-src 'self' ${e.join(` `)}`,`base-uri 'self'`,`form-action 'none'`,`frame-ancestors 'none'`].join(`; `);function CB(e,t,n,{pathname:r,key:i},a){let{root:o,options:s,loopback:c,viewerDir:l}=n,u=a!==null,f=vB.test(r),m=f?null:yB.exec(r),h=a||(m?null:G(r.replace(f?/^\/preview\//:/^\//,``).replace(/\/$/,``).replace(/^(storyboard\/[^/]+)\/render$/,`$1`),Xn)),g=h&&Si(o,h.type,h.id),_=g??h,v=g?.dir,y=VR(n),b=m?`${m[1]} · Preview · ${y}`:_?v?zR(n.readArtifact(v,_)):_.id:`${y} · Artifacts`,x=dF(fF(e.headers[`accept-language`])),S=vF(x),C=_?S(`meta.artifact`,{project:y,title:b,type:{artboard:`Artboard`,document:`Document`,html:`HTML`,whiteboard:`Whiteboard`,verify:`Verify report`,report:`Report`,slides:`Slides`,storyboard:`Storyboard`}[_.type]}):S(`meta.library`,{project:y}),w=m?`/preview/${m[1]}`:_?v?xi(o,_.type,_.id):`/${_.type}/${_.id}`:`/`,T=`http://${ne(s.urlHost)}:${n.port}${f?`/preview`:``}${w}`,E=m?[...n.boardOrigins(),`http://localhost:*`,`http://127.0.0.1:*`]:n.boardOrigins(),D=u?SB(E).replace(`frame-ancestors 'none'`,`frame-ancestors 'self'${s.cloud?` ${s.cloud.origin}`:``}`):f?SB(E).replace(`frame-ancestors 'none'`,`frame-ancestors 'self'`):SB(E),O={"Content-Type":`text/html; charset=utf-8`};(_||m)&&(O[`Referrer-Policy`]=`same-origin`),i!==null&&!c&&(O[`Set-Cookie`]=`${n.cookieName}=${n.token}; HttpOnly; SameSite=Strict; Path=/`);let k=f&&d.default.existsSync(p.default.join(l,`preview.html`))?`preview.html`:`index.html`;d.default.promises.readFile(p.default.join(l,k),`utf8`).then(n=>{let r=mB(n,{title:b,description:C,locale:x,url:T,icon:_?fB(_.type):void 0,artifactId:g?.id,project:y,embedParent:u&&e.headers[`sec-fetch-site`]!==`same-origin`?s.cloud?.origin:void 0});z(t,200,r,{...O,"Content-Security-Policy":gB(D,r)})}).catch(e=>z(t,e.code===`ENOENT`?404:500,`Viewer unavailable`))}const wB={path:/^\/embed\//,auth:`viewer`,handle:(e,t,n,r)=>{let i=xB.exec(r.pathname),a=i&&n.embedTarget(i[1],i[2]);a?CB(e,t,n,r,a):z(t,404,`Not found`)}},TB={path:e=>e===`/`||e===`/index.html`?[e]:null,auth:`navigation`,handle:(e,t,n,r)=>CB(e,t,n,r,null)},EB={path:e=>_B.exec(e)??vB.exec(e)??yB.exec(e)??bB.exec(e),auth:`viewer`,handle:(e,t,n,r)=>CB(e,t,n,r,null)},DB={path:e=>[e],auth:`viewer`,handle:(e,t,n,{pathname:r})=>{let i=tt(n.viewerDir,r.slice(1));i?ie(t,i,{"Content-Security-Policy":SB(n.boardOrigins())}):z(t,404,`Not found`)}},OB=[UR,WR,GR,eB,tB,Yz,Xz,Zz,Qz,nB,rB,sz,YR,iB,ZR,...we.flatMap(e=>oj[e].routes??[]),...sj.routes,$z,wB,TB,EB,DB],kB=[cB,lB];async function AB(e){let t=BR(e),{root:n,stateDir:r,mount:i,loopback:a,token:o,cloud:s,autoPublisher:c,clients:l}=t,u=(e,n)=>_N(OB,e,n,t),f=g.default.createServer((e,t)=>{try{u(e,t)}catch(e){t.headersSent||z(t,500,`Artifacts error: ${e.message}`)}}),m=(e,n)=>vN(kB,e,n,t);if(f.on(`upgrade`,m),i)t.port=i.port;else{let n=Number(te(t.portFile));try{t.port=await R(f,e.host,Number.isInteger(n)&&n>0?n:0)}catch{t.port=await R(f,e.host,0)}d.default.writeFileSync(t.portFile,`${t.port}\n`,{mode:384})}let h=t.port;t.cookieName=`ryugi_artifacts_${h}`;let _=KR(t),v=g.default.createServer(_);if(i)t.boardPort=i.boardPort;else if(a){let n=p.default.join(r,cj.portFile),i=Number(te(n));try{t.boardPort=await R(v,e.host,Number.isInteger(i)&&i>0&&i!==h?i:0)}catch{t.boardPort=await R(v,e.host,0)}d.default.writeFileSync(n,`${t.boardPort}\n`,{mode:384})}let y=t.boardPort;t.policy=cn({host:e.host,urlHost:e.urlHost,ports:y?[h,y]:[h],cloudOrigin:e.cloud?.origin});let b=`http://${ne(e.urlHost)}:${h}`,x=a?`${b}/`:`${b}/?key=${o}`,S=(e,t)=>`${b}${xi(n,e,t)}${a?``:`?key=${o}`}`,C=t.signatureBaseline(),w=[],T=er(n).artifacts;for(let e of T){let r=`${e.type}/${e.id}`,i=nr(e.dir,e.type);C&&C.get(r)!==i&&w.push({type:e.type,id:e.id}),t.signatures.set(r,i);try{xi(n,e.type,e.id)}catch{}oj[e.type].refreshOnStart&&t.refreshState(e,e.dir)}let E=new Set(T.map(e=>`${e.type}/${e.id}`));for(let e of C?.keys()??[]){let t=G(e);t&&!E.has(e)&&w.push(t)}t.saveSignatures(),U(p.default.join(r,`server-info`),{type:`server-started`,url:x,port:h,boardPort:y,root:n}),t.relay=i?{emit:(e,n)=>t.relayListeners.forEach(t=>t(e,n)),close:()=>{}}:e.relay&&e.cloud?sN({...e.relay,token:()=>vt(e.cloud.credentialsFile,e.cloud.origin)?.token??null,served:t.servedArtifacts,local:()=>({hostId:dM(e.cloud.credentialsFile),port:h,...a?{embed:!0,embedDocument:!0}:{key:o}}),handle:(e,n,r)=>kN(t,e,n,r),waiting:()=>hc(e.cloud.origin,vt(e.cloud.credentialsFile,e.cloud.origin)?.token??null),onActivity:t.touch,onWatch:e=>ON(t,e)}):null;for(let e of w)IM(t,e,[],{force:!0});let D=cl.onReady(e=>{for(let r of e){let e=p.default.relative(n,r),i=!e.startsWith(`..`)&&G(e.split(p.default.sep).join(`/`));i&&IM(t,i,[],{force:!0})}}),O=t.memory.stateWritten?[]:T.map(({type:e,id:t})=>({type:e,id:t})),k,A=()=>{for(let e of O.splice(0,4))RM(t,e);O.length?k=setImmediate(A):(k=void 0,t.memory.stateWritten=!0)};k=setImmediate(A);let j=0;return t.deckFiles.changed=e=>FM(t,e),t.deckFiles.written=(e,n)=>IM(t,{type:`slides`,id:e},n,{force:!0}),{port:h,boardPort:y,token:o,contentToken:t.contentToken,url:x,root:n,linkFor:S,handleRequest:(e,n)=>{j+=1,t.lastActivity=Date.now(),n.once(`close`,()=>{--j,t.lastActivity=Date.now()});try{u(e,n)}catch(e){n.headersSent||z(n,500,`Artifacts error: ${e.message}`)}},busy:()=>j>0||l.size>0||t.relayViewers.size>0||t.relayWatched.size>0||t.direct.size()>0||t.documents.openIds().length>0||(c?.active()??!1)||t.recordings.active()||t.voiceRunner.active()||t.sourceRunner.active(),lastActiveAt:()=>t.lastActivity,watch:e=>{let n=e?[e]:[NR,PR];n.forEach(t.viewed.viewerJoined);let r=!0;return()=>{r&&(r=!1,n.forEach(t.viewed.viewerLeft))}},watching:()=>t.viewed.watching(),handleUpgrade:m,handleBoardRequest:_,handleRelay:(e,n,r)=>kN(t,e,n,r),dropRelayViewer:e=>DN(t,e),flushDocuments:()=>t.documents.flushAll(),served:t.servedArtifacts,onRelayEvent:e=>t.relayListeners.push(e),onReview:e=>t.reviewListeners.push(e),deliverThreads:(e,n,r,i)=>t.deliverThreads(e,n,r,i),relayWatch:e=>ON(t,e),liveClients:()=>l.size,agentSessions:()=>t.agentStatus.sessions(),publishAgentStatus:()=>t.publishAgentStatus(),resolve:(e,t)=>Xn(t)?Si(n,e,t)?.id??null:null,cloudLinkFor:async(t,n)=>{if(!s||!e.cloud||!vt(e.cloud.credentialsFile,e.cloud.origin))return null;let{url:r}=await s.reserve({type:t,id:n});return r?Ir(r,dM(e.cloud.credentialsFile)):null},onArtifactChange:e=>{t.changeListeners.push(e)},*currentPayloads(e){let r=e?[G(e)]:er(n).artifacts.map(({type:e,id:t})=>({type:e,id:t}));for(let e of r){let n=e&&zM(t,e);e&&n&&(yield{ref:e,payload:n})}},onActivity:e=>t.activityListeners.push(e),close:async()=>{jr(),D(),k&&clearImmediate(k),clearInterval(t.listeningTimer),await t.recordings.close(),await new Promise(e=>{t.viewed.close(),t.deckDeps.close(),c?.close(),t.relay?.close(),t.direct.close(),t.selections.clearAll();for(let e of l)e.destroy();v.close(),v.closeAllConnections(),f.close(()=>e()),f.closeAllConnections()}),await t.documents.close().catch(()=>void 0),await t.previewProxies.close().catch(()=>void 0),t.whiteboards.close(),t.leaveAgentDirectory(),t.voiceRunner.close(),t.exportRunner.close()}}}const jB=e=>AB(e);function MB(e){let{boardPort:t,options:n,port:r}=e,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=n.documentEngineFile?MM({socketPath:yM(n.paths.home),engineFile:n.documentEngineFile,version:n.version,logFile:p.default.join(n.paths.home,`document-engine.log`)}):null,s=o?cl.use(o):null,c=o?({fillRefs:e,...t})=>o.open(t):void 0,l=/* @__PURE__ */ new Map,u=e=>{let t=l.get(e);return t||(t=LR(pr(e)),d.register(t.agentStatus),l.set(e,t)),t},d=nI(),f=/* @__PURE__ */ new Map,m=!1,h=s=>{if(m)return Promise.reject(/* @__PURE__ */ Error(`Artifacts server is stopping`));let l=i.get(s);return l||(l=jB({root:pr(s),viewerDir:n.viewerDir,runtimeDir:n.runtimeDir,host:n.host,urlHost:n.urlHost,configFile:p.default.join(s,`.ryugi`,`config.json`),cloud:n.cloud,fetch:n.fetch,debounceMs:n.debounceMs,agentDirectory:d,agentDaemon:e.agentDaemon(s),memory:u(s),openDocument:c,readDocument:o?(e,t)=>o.read(e,t):void 0,mount:{port:r,boardPort:t,token:n.token,version:n.version}}).then(t=>{f.set(s,t);let n=a.get(s);return n?.size&&t.relayWatch(n),e.onMounted(s,t),t}),l.catch(()=>i.delete(s)),i.set(s,l)),l},g=e=>{let t=i.get(e);return i.delete(e),f.delete(e),t};return{agentDirectory:d,closeAll:async()=>{let e=[...i.values()];i.clear(),f.clear(),await Promise.all(e.map(async e=>(await e.catch(()=>null))?.close())),s?.(),await o?.close()},closing:()=>m,documentHost:o,memories:l,mountOf:h,ready:f,relayWatch:e=>{a=e;for(let[t,n]of f)n.relayWatch(e.get(t)??/* @__PURE__ */ new Set);for(let[t,n]of e)f.has(t)||h(t).then(e=>e.relayWatch(a.get(t)??n)).catch(()=>void 0)},relayWatching:e=>!!a.get(e)?.size,stop:()=>{m=!0},take:g,unmount:async e=>{await(await g(e)?.catch(()=>null))?.close()}}}const NB=(e,t)=>t.map(t=>e.boards[t]?.page).find(e=>!!e);function PB(e){let t=e.canvas;if(!t||e.warnings.length>0)return!1;let n=Object.entries(t.boards);if(n.length===0)return!1;if(t.building===!0)return!0;let r=new Set(e.pending),i=n=>{let i=t.boards[n];return i?(e.versions[i.file]??0)>0&&!r.has(n):!1};if(n.every(([e])=>i(e)))return!0;let a=t.focus?.target,o=a&&t.boards[a]?a:void 0,s=a?t.groups?.[a]?a:o?Object.entries(t.groups??{}).find(([,e])=>e.boards.includes(o))?.[0]:void 0:void 0,c=s?t.groups?.[s]:void 0;if(c&&c.boards.length>0)return c.boards.every(i);let l=(o?t.boards[o].page:void 0)??(c?NB(t,c.boards):void 0)??t.activePage??t.pages[0]?.id;if(!l)return!1;let u=Object.entries(t.groups??{}).filter(([,e])=>e.boards.some(e=>t.boards[e]?.page===l));for(let[,e]of u)if(e.boards.length>0&&e.boards.every(i))return!0;if(u.length>0)return!1;let d=n.filter(([,e])=>e.page===l);return d.length===1?i(d[0][0]):d.filter(([e])=>i(e)).length>=2}function FB(e,t,n){let{artifact:r,openCmd:i}=t,a=!1,o=e.watch(r),s=(t,s)=>{if(a||r&&`${t.type}/${t.id}`!==r||(`canvas`in s?!PB(s):s.warnings.length>0))return;a=!0,o();let c=e.linkFor(t.type,t.id);e.cloudLinkFor(t.type,t.id).catch(()=>null).then(e=>n(e??c,c,i)).catch(()=>void 0)};e.onArtifactChange(s);for(let{ref:t,payload:n}of e.currentPayloads(r))if(s(t,n),a)break}const IB=`host`,LB=e=>{if(typeof e!=`object`||!e)return!1;let{op:t,comment:n}=e;return t===`comment`&&(n?.op===`create`||n?.op===`reply`)};function RB(e){let{loopback:t,machine:n,options:r,ordered:i,port:a}=e,{handler:o}=n,{agentInput:s,agentPanel:c,agentScreen:l,deviceTrusted:u,resumer:d}=e.agents,{mountOf:f,ready:m,relayWatch:h}=e.mounts,g=e=>p.default.join(e,`.ryugi`,`config.json`),_=e=>{let t=m.get(e);if(t)return t.served();let n=/* @__PURE__ */ new Map;for(let[t,r]of Object.entries(Gr(g(e)).config.artifacts))r.cloud&&n.set(r.cloud.id,t);return n},v=()=>{let e=/* @__PURE__ */ new Map;for(let t of i())for(let[n,r]of _(t.dir))e.has(n)||e.set(n,`${t.dir}
985
- ${r}`);return e},y=e=>{let t=e.lastIndexOf(`
986
- `);return{project:e.slice(0,t),key:e.slice(t+1)}},b=()=>r.cloud?hc(r.cloud.origin,vt(r.cloud.credentialsFile,r.cloud.origin)?.token??null):Promise.resolve(null),x=r.relay&&r.cloud?sN({...r.relay,token:()=>vt(r.cloud.credentialsFile,r.cloud.origin)?.token??null,served:v,refusedFile:p.default.join(r.paths.home,`relay-refused.json`),featuresFile:p.default.join(r.paths.home,`relay-features.json`),waiting:b,local:()=>({hostId:dM(r.cloud.credentialsFile),port:a,...t?{embed:!0,embedDocument:!0}:{key:r.token}}),handle:async(e,t,n,r)=>{let{project:i,key:a}=y(e),o=t?.op;if(o===`agent-sessions`)return c(i,a,await u(r));if(o===`agent-screen`)return l(i,a,r);if(o===`agent-input`)return s(i,a,t,r);if(n===IB&&!m.has(i))return{applied:0};let p=await(await f(i)).handleRelay(a,t,n);return r&&LB(t)&&d.onHumanInput({dir:i,key:a,deviceId:r}),p},onActivity:()=>{},...o?{machine:{info:n.info,handle:e=>o.handle(e)}}:{},onWatch:e=>{let t=/* @__PURE__ */ new Map;for(let n of e){let{project:e,key:r}=y(n);t.set(e,(t.get(e)??/* @__PURE__ */ new Set).add(r))}h(t)}}):null;return{close:()=>x?.close(),emit:(e,t,n)=>x?.emit(`${e}
987
- ${t}`,n),pullInbox:(e,t)=>{x?.state().connected&&b().then(n=>{for(let[r,i]of _(e))gj.test(i)&&(!n||n.has(r))&&t.handleRelay(i,{op:`inbox`},IB).catch(()=>void 0)})},refresh:()=>x?.refresh(),state:()=>x?.state()}}function zB(e){let{boardPort:t,index:n,options:r,ordered:i,port:a,ready:o,url:s}=e,c=Date.now(),l=c,u=/* @__PURE__ */ new Map,d=()=>{let e=/* @__PURE__ */ new Map;for(let t of n.list(1e4))e.set(t.project,(e.get(t.project)??0)+1);return i().map(t=>({dir:t.dir,name:p.default.basename(t.dir),lastUsedAt:t.lastUsedAt,dormant:hr(t),artifacts:e.get(t.dir)??0}))};return{artifactList:()=>{let e=[],t=[],n=/* @__PURE__ */ new Set;for(let r of i()){let i=pr(r.dir),a=er(i);for(let e of a.warnings)t.push(`${p.default.basename(r.dir)}: ${e}`);for(let t of a.artifacts){n.add(t.dir);try{let n=oj[t.type].listedStateFile,{stamp:a,updatedAt:o}=BB(t.dir,n?p.default.join(i,`.state`,t.type,t.id,n):null),s=u.get(t.dir);if(s?.stamp===a&&s.artifact.project===r.dir){e.push(s.artifact);continue}let c={project:r.dir,type:t.type,id:t.id,url:xi(i,t.type,t.id),title:zR(RR(t.dir,t)),updatedAt:o};u.set(t.dir,{artifact:c,stamp:a}),e.push(c)}catch{}}}for(let e of u.keys())n.has(e)||u.delete(e);return e.sort((e,t)=>t.updatedAt-e.updatedAt),{projects:d(),artifacts:e,warnings:t}},status:()=>{let n=e.relayState(),i=[...o.values()].reduce((e,t)=>e+t.liveClients(),0);return{pid:process.pid,version:r.version,latest:r.latest?.()??null,startedAt:c,lastActivity:l,clients:i,port:a,boardPort:t,url:s,relay:{connected:n?.connected??!1,announced:n?.announced??0,...n?.refused&&r.cloud?{refused:n.refused,upgradeUrl:`${r.cloud.origin}/billing`}:{}},live:{local:i,relay:n?.watched??0},projects:d()}},touch:()=>{l=Date.now()}}}function BB(e,t){let n=[],r=0,i=(e,t)=>{n.push(`${e}:${t.mtimeMs}:${t.size}`),r=Math.max(r,Math.floor(t.mtimeMs))};for(let t of d.default.readdirSync(e))if(!t.startsWith(`.`))try{i(t,d.default.statSync(p.default.join(e,t)))}catch{}if(t)try{i(`.skeleton`,d.default.statSync(t))}catch{}return{stamp:n.join(`|`),updatedAt:r}}async function VB(e){let t=on(e.host),n=e.paths.projects;mr(n);let r=()=>lr(n).sort((e,t)=>t.lastUsedAt-e.lastUsedAt),i=e=>r().some(t=>t.dir===e),a=vr(()=>r().map(e=>e.dir),{rescanAfterMs:0}),o=g.default.createServer(),s=g.default.createServer(),c=await se(o,e.host,e.ports),l=t?await se(s,e.host,e.boardPorts):0,u=cn({host:e.host,urlHost:e.urlHost,ports:l?[c,l]:[c],cloudOrigin:e.cloud?.origin}),f=MB({agentDaemon:e=>b.portFor(e),boardPort:l,onMounted:(e,t)=>{t.onRelayEvent((t,n)=>{S.emit(e,t,n),Ln(n)&&setImmediate(()=>v.trigger(e,t))}),t.onReview(t=>setImmediate(()=>v.trigger(e,t))),_.attach(e),S.pullInbox(e,t)},options:e,port:c}),{mountOf:m,ready:h}=f,_=await Qj({mountOf:m,options:e,ready:h}),{feed:v,feedStore:y}=_,b=qj({agentDirectory:f.agentDirectory,mountOf:m,options:e,ready:h}),x=_M({agents:b,closing:f.closing,mountOf:m,options:e,ordered:r,refreshRelay:()=>S.refresh(),register:e=>N(e),registered:i}),S=RB({agents:b,loopback:t,machine:x,mounts:f,options:e,ordered:r,port:c}),C=e=>p.default.join(e,`.ryugi`,`config.json`),w=t=>!!e.cloud&&!!vt(e.cloud.credentialsFile,e.cloud.origin)&&ai({globalFile:$r(e.cloud.credentialsFile),projectFile:C(t)}),T=`http://${ne(e.urlHost)}:${c}`,E=t?`${T}/`:`${T}/?key=${e.token}`,D=e=>p.default.join(pr(e),`.state`,`server-info`),O=e=>{try{d.default.mkdirSync(p.default.dirname(D(e)),{recursive:!0,mode:448}),U(D(e),{type:`server-started`,url:E,port:c,boardPort:l,root:pr(e)})}catch{}},k=zB({boardPort:l,index:a,options:e,ordered:r,port:c,ready:h,relayState:S.state,url:E}),{authorized:A,decode:j,fromAgent:ee,route:M}=wj({index:a,loopback:t,memories:f.memories,mountOf:m,ordered:r,port:c,ready:h,registered:i,token:e.token}),N=async(r,i)=>{let o=Cj(r);if(!o)throw Error(`Project directory not found: ${r}`);d.default.mkdirSync(pr(o),{recursive:!0});let s=dr(n,o);a.rescan(),O(o);let c=await m(o);return i&&e.open&&t&&FB(c,i,e.open),S.refresh(),s},P=e.idle?.unmountAfterMs??6e5,F=async e=>{let t=[...h].filter(([t,n])=>!f.relayWatching(t)&&!v.pinned(t)&&!n.busy()&&e-n.lastActiveAt()>=P);await Promise.all(t.map(([e])=>f.unmount(e))),y.sweep((e,t)=>v.connected(e,t));for(let[t,n]of f.memories)h.has(t)||n.agentStatus.expire(e)},I=setInterval(()=>void F(Date.now()),e.idle?.sweepMs??6e4);I.unref();let L=async e=>{let t=Cj(e)??p.default.resolve(e);fr(n,t),a.rescan(),d.default.rmSync(D(t),{force:!0}),await(await f.take(t))?.close()},{handleControl:te,handleHubApi:R}=Dj({authorized:A,feed:v,fromAgent:ee,options:e,ordered:r,policy:u,register:N,remove:L});o.on(`request`,(e,t)=>{(async()=>{if(!ln(u,e.headers.host)){z(t,403,`Forbidden host`);return}let n=new URL(e.url??`/`,`http://artifacts.local`);if(n.pathname===`/api/status`){A(e,n)?B(t,200,k.status()):z(t,403,`Forbidden: agent calls need ?key=`);return}if(Tj.test(n.pathname)){!A(e,n)||!un(u,e.headers.origin)?z(t,403,`Forbidden`):te(e,t,n);return}if(n.pathname===`/api/hub/artifacts`){!A(e,n)||!un(u,e.headers.origin)?z(t,403,`Forbidden`):B(t,200,k.artifactList());return}if(k.touch(),await R(e,t,n))return;let r=j(n.pathname);if(r===null){z(t,400,`Bad request`);return}let i=await M(e,n,r);i?`projects`in i?B(t,409,{error:`ambiguous_slug`,...i}):i.handleRequest(e,t):z(t,404,`Not found`)})().catch(e=>{t.headersSent||z(t,f.closing()?503:500,`Artifacts error: ${e.message}`)})}),o.on(`upgrade`,(e,t,n)=>{(async()=>{let r=new URL(e.url??`/`,`http://artifacts.local`),i=j(r.pathname)??`/`,a=await M(e,r,i);!a||`projects`in a?t.destroy():a.handleUpgrade(e,t,n)})().catch(()=>t.destroy())}),s.on(`request`,(e,t)=>{(async()=>{let n=j(new URL(e.url??`/`,`http://board.local`).pathname)??`/`,i=cj.route(e,n),o=i.kind===`board`?a.find(`artboard`,i.address)?.project??null:r()[0]?.dir??null,s=o?await m(o):null;s?s.handleBoardRequest(e,t):z(t,404,`Not found`)})().catch(e=>{t.headersSent||z(t,500,e.message)})});let re=[];for(let e of r())O(e.dir),w(e.dir)&&wr(p.default.join(pr(e.dir),`.state`,`auto-publish.json`))&&re.push(m(e.dir).catch(()=>void 0));return await Promise.all(re),{port:c,boardPort:l,token:e.token,url:E,status:k.status,projects:r,mounted:()=>[...h.values()],unmount:f.unmount,sweepIdle:F,documentProcess:()=>f.documentHost?.pid()??null,flushDocuments:async e=>{let t=Promise.all([...h.values()].map(e=>e.flushDocuments().catch(()=>void 0)));await Promise.race([t,new Promise(t=>setTimeout(t,e).unref())])},mountOf:m,register:N,remove:L,linkFor:async(e,t,n)=>(await m(e)).linkFor(t,n),close:async()=>{f.stop(),await _.close(),jr(),clearInterval(I),x.stop(),b.stop();let e=[o,s].map(e=>new Promise(t=>e.close(t)));S.close(),await f.closeAll();for(let e of r())d.default.rmSync(D(e.dir),{force:!0});for(let e of[o,s])e.closeAllConnections();await Promise.all(e)}}}const HB=/^node "(.+)"$/;function UB(e,t){let n=HB.exec(e.RYUGI_ARTIFACTS_LAUNCHER??``)?.[1];if(n)return[process.execPath,n];let r=p.default.join(t,`cli.cjs`);return d.default.existsSync(r)?[process.execPath,r]:null}function WB(e,t,n,r=Date.now()){let i=p.default.join(e.XDG_CACHE_HOME||p.default.join(t,`.cache`),`ryugi`,`artifacts`);d.default.mkdirSync(i,{recursive:!0});let a=p.default.join(i,`latest.json`),o=`${a}.${process.pid}`;d.default.writeFileSync(o,JSON.stringify({version:n,checkedAt:r})),d.default.renameSync(o,a)}function GB(e,t,n=process.env){let[r,...i]=t;r&&(0,l.spawn)(process.execPath,[...w(`relaunch`),`-e`,`
988
- const [pid, file, ...args] = process.argv.slice(1);
989
- const gone = () => { try { process.kill(Number(pid), 0); return false; } catch { return true; } };
990
- const tick = () => {
991
- if (!gone()) return setTimeout(tick, 100);
992
- require('child_process').spawn(file, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref();
993
- };
994
- tick();
995
- `,String(e),r,...i],{detached:!0,stdio:`ignore`,windowsHide:!0,env:n}).unref()}const KB=/* @__PURE__ */ new Set([`stop`,`stale_pid`]),qB=/* @__PURE__ */ new Set([`SIGTERM`,`SIGINT`,`SIGHUP`]);function JB(e){try{return JSON.parse(d.default.readFileSync(e,`utf8`)).reason}catch{return null}}function YB(e,t){let n=JB(e);qB.has(t)&&typeof n==`string`&&KB.has(n)||U(e,{reason:t,timestamp:Date.now()})}function XB(e){let t=setInterval(()=>{let n;try{n=d.default.readFileSync(e.file,`utf8`).trim()}catch{return}n&&n!==e.serverId&&(clearInterval(t),e.onSuperseded(n))},e.intervalMs??1e3);return t.unref(),()=>clearInterval(t)}function ZB(e,t){let n=e.split(/[.-]/).slice(0,3).map(Number),r=t.split(/[.-]/).slice(0,3).map(Number);for(let e=0;e<3;e++){let t=(n[e]||0)-(r[e]||0);if(t)return t>0}return!1}function QB(e){try{let t=JSON.parse(d.default.readFileSync(e,`utf8`));return typeof t.version==`string`&&Number.isFinite(t.checkedAt)?t:null}catch{return null}}function $B(e){let t=e.now??Date.now,n=e.fetch??fetch,r=QB(e.cacheFile),i=/^\d+\.\d+\.\d+/.test(e.current);return{latest(){return!i||!r?null:ZB(r.version,e.current)?r.version:null},async refresh(){if(i&&!(r&&t()-r.checkedAt<864e5))try{let{version:i}=await(await n(`https://registry.npmjs.org/ryugi-artifacts/latest`,{signal:AbortSignal.timeout(5e3)})).json();if(typeof i!=`string`)return;r={version:i,checkedAt:t()},d.default.writeFileSync(e.cacheFile,`${JSON.stringify(r)}\n`,{mode:384})}catch{}}}}const eV=36e5;async function tV(e){if(!Jt[process.platform]?.includes(process.arch))return;let t=await Zt({arch:process.arch,daemonSource:b||void 0,fetch,home:f.default.homedir(),configHome:process.env.XDG_CONFIG_HOME||void 0,run:(e,t)=>{let n=(0,l.spawnSync)(e,t,{encoding:`utf8`});return{status:n.status,stderr:n.stderr||(n.error?.message??``),stdout:n.stdout??``}},platform:process.platform,serverHome:e,uid:process.getuid?.()??0,version:y},wt(Ct())).catch(e=>({status:`failed`,error:e.message}));t.status!==`not-installed`&&t.status!==`other-hub`&&console.info(JSON.stringify({type:`daemon-update`,...t,at:(/* @__PURE__ */ new Date()).toISOString()}))}async function nV(e,t){let n=await rn({arch:process.arch,cleanup:t,env:process.env,fetch,home:f.default.homedir(),platform:process.platform,serverHome:e,version:y}).catch(e=>({status:`failed`,error:e.message}));n.status!==`other-hub`&&(n.status!==`done`||n.prefetched.length||n.failed.length||n.removed.length)&&console.info(JSON.stringify({type:`hook-prefetch`,...n,at:(/* @__PURE__ */ new Date()).toISOString()}))}function rV(e){try{let t=d.default.readFileSync(e,`utf8`).trim();if(/^[a-f0-9]{48}$/.test(t))return t}catch{}let t=u.default.randomBytes(24).toString(`hex`);return d.default.writeFileSync(e,`${t}\n`,{mode:384}),t}async function iV(){let e=le(process.env,process.argv.slice(2));process.platform!==`linux`&&C(`hub`,...e.serverId?[`--artifacts-server-id=${e.serverId}`]:[]);let t=ar();or(t.home);let n=$B({cacheFile:p.default.join(t.home,`latest.json`),current:y}),r=await VB({host:e.host,urlHost:e.urlHost,viewerDir:p.default.join(__dirname,`viewer`),documentEngineFile:p.default.join(__dirname,`document-engine.cjs`),agentSocket:O(),runtimeDir:p.default.join(__dirname,`runtime`),ports:e.ports,boardPorts:e.boardPorts,paths:t,token:rV(t.key),version:y,latest:()=>n.latest(),cloud:{origin:e.cloudOrigin,credentialsFile:yt(process.env,process.platform,f.default.homedir())},relay:{url:`${e.cloudOrigin.replace(/^http/,`ws`)}/api/relay/host`,version:y},control:{stop:()=>void a(`stop`),relaunch:e=>s(e)},open:async(t,n,r)=>{let i=r??e.openCmd;i?(0,l.exec)(`${i} ${JSON.stringify(t)}`,()=>{}):await fe(t,[n]).catch(e=>{console.error(JSON.stringify({type:`browser-open-error`,error:e.message}))})}});process.env.RYUGI_NO_UPDATE_CHECK!==`1`&&(n.refresh(),setInterval(()=>void n.refresh(),eV).unref());let i=!1;async function a(e,n=!0){i||(i=!0,console.info(JSON.stringify({type:`server-stopped`,reason:e,at:(/* @__PURE__ */ new Date()).toISOString()})),d.default.rmSync(t.info,{force:!0}),n&&YB(t.stopped,e),await r.close(),process.exit(0))}function o(){try{return d.default.readFileSync(t.version,`utf8`).trim()||y}catch{return y}}function s(t){let i=UB(process.env,__dirname),s=r.projects()[0]?.dir,c=n.latest(),l=!!process.env.RYUGI_ARTIFACTS_LAUNCHER;if(!i||!s||t&&(!c||!l))return!1;try{t&&c&&WB(process.env,f.default.homedir(),c)}catch{return!1}let u={...process.env};return delete u.CODEX_CI,l||(u.RYUGI_ARTIFACTS_VERSION=o()),GB(process.pid,[...i,`start`,`--json`,`--no-open`,`--project-dir`,s,`--host`,e.host,`--url-host`,e.urlHost,`--port`,String(r.port)],u),setImmediate(()=>void a(t?`upgrade`:`restart`,!1)),!0}e.serverId&&XB({file:t.serverId,serverId:e.serverId,onSuperseded:e=>{console.info(JSON.stringify({type:`server-superseded`,by:e,at:(/* @__PURE__ */ new Date()).toISOString()})),r.flushDocuments(2e3).finally(()=>process.exit(0))}}),process.on(`SIGTERM`,()=>void a(`SIGTERM`)),process.on(`SIGINT`,()=>void a(`SIGINT`)),process.on(`SIGHUP`,()=>void a(`SIGHUP`)),d.default.rmSync(t.stopped,{force:!0});let c={type:`server-started`,url:r.url,port:r.port,boardPort:r.boardPort,version:y,pid:process.pid,host:e.host,urlHost:e.urlHost,cloudOrigin:e.cloudOrigin};U(t.info,c),console.info(JSON.stringify({...c,at:(/* @__PURE__ */ new Date()).toISOString()})),tV(t.home),nV(t.home,!0),setInterval(()=>void nV(t.home,!1),eV).unref()}iV().catch(e=>{console.info(JSON.stringify({type:`server-error`,error:e.message})),process.exit(1)});